diff --git a/.eslintrc.js b/.eslintrc.js index c33f4de15b919..3cac46e7d2605 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -91,7 +91,6 @@ module.exports = { { files: ['x-pack/plugins/canvas/**/*.{js,ts,tsx}'], rules: { - 'react-hooks/exhaustive-deps': 'off', 'jsx-a11y/click-events-have-key-events': 'off', }, }, diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4bf659345d387..959c12af90463 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -661,18 +661,23 @@ To build the docs, you must clone the [elastic/docs](https://github.com/elastic/ repo as a sibling of your kibana repo. Follow the instructions in that project's README for getting the docs tooling set up. -**To build the docs and open them in your browser:** +**To build the Kibana docs and open them in your browser:** + +```bash +./docs/build_docs --doc kibana/docs/index.asciidoc --chunk 1 --open +``` +or ```bash node scripts/docs.js --open ``` -### Release Notes Process +### Release Notes process Part of this process only applies to maintainers, since it requires access to GitHub labels. -Kibana publishes major, minor and patch releases periodically through the year. During this process we run a script against this repo to collect the applicable PRs against that release and generate [Release Notes](https://www.elastic.co/guide/en/kibana/current/release-notes.html). -To include your change in the Release Notes: +Kibana publishes [Release Notes](https://www.elastic.co/guide/en/kibana/current/release-notes.html) for major and minor releases. To generate the Release Notes, the writers run a script against this repo to collect the merged PRs against the release. +To include your PRs in the Release Notes: 1. In the title, summarize what the PR accomplishes in language that is meaningful to the user. In general, use present tense (for example, Adds, Fixes) in sentence case. 2. Label the PR with the targeted version (ex: `v7.3.0`). @@ -681,9 +686,9 @@ To include your change in the Release Notes: * For an external-facing fix, use `release_note:fix`. Exception: docs, build, and test fixes do not go in the Release Notes. Neither fixes for issues that were only on `master` and never have been released. * For a deprecated feature, use `release_note:deprecation`. * For a breaking change, use `release_note:breaking`. - * To **NOT** include your changes in the Release Notes, please use `release_note:skip`. + * To **NOT** include your changes in the Release Notes, use `release_note:skip`. -We also produce a blog post that details more important breaking API changes every minor and major release. If the PR includes a breaking API change, apply the label `release_note:dev_docs`. Additionally add a brief summary of the break at the bottom of the PR using the format below: +We also produce a blog post that details more important breaking API changes in every major and minor release. When your PR includes a breaking API change, add the `release_note:dev_docs` label, and add a brief summary of the break at the bottom of the PR using the format below: ``` # Dev Docs diff --git a/docs/dev-tools/console/console.asciidoc b/docs/dev-tools/console/console.asciidoc index caffef7995fbf..9f225986d5df0 100644 --- a/docs/dev-tools/console/console.asciidoc +++ b/docs/dev-tools/console/console.asciidoc @@ -44,7 +44,7 @@ curl -XGET "http://localhost:9200/_search" -d' ---------------------------------- When you paste the command into Console, {kib} automatically converts it -to Console syntax. Alternatively, if you want to want to see Console syntax in cURL, +to Console syntax. Alternatively, if you want to see Console syntax in cURL, click the action icon (image:dev-tools/console/images/wrench.png[]) and select *Copy as cURL*. [float] diff --git a/docs/development/core/public/kibana-plugin-core-public.md b/docs/development/core/public/kibana-plugin-core-public.md index 9e4afe0f5133c..7c7c9729504de 100644 --- a/docs/development/core/public/kibana-plugin-core-public.md +++ b/docs/development/core/public/kibana-plugin-core-public.md @@ -132,6 +132,12 @@ The plugin integrates with the core system via lifecycle events: `setup` | [URLMeaningfulParts](./kibana-plugin-core-public.urlmeaningfulparts.md) | We define our own typings because the current version of @types/node declares properties to be optional "hostname?: string". Although, parse call returns "hostname: null \| string". | | [UserProvidedValues](./kibana-plugin-core-public.userprovidedvalues.md) | Describes the values explicitly set by user. | +## Variables + +| Variable | Description | +| --- | --- | +| [URL\_MAX\_LENGTH](./kibana-plugin-core-public.url_max_length.md) | The max URL length allowed by the current browser. Should be used to display warnings to users when query parameters cause URL to exceed this limit. | + ## Type Aliases | Type Alias | Description | diff --git a/docs/development/core/public/kibana-plugin-core-public.url_max_length.md b/docs/development/core/public/kibana-plugin-core-public.url_max_length.md new file mode 100644 index 0000000000000..993320d51909a --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.url_max_length.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [URL\_MAX\_LENGTH](./kibana-plugin-core-public.url_max_length.md) + +## URL\_MAX\_LENGTH variable + +The max URL length allowed by the current browser. Should be used to display warnings to users when query parameters cause URL to exceed this limit. + +Signature: + +```typescript +URL_MAX_LENGTH: number +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.getsearchparamsfromrequest.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.getsearchparamsfromrequest.md new file mode 100644 index 0000000000000..1923f0e2e4ea1 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.getsearchparamsfromrequest.md @@ -0,0 +1,44 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [getSearchParamsFromRequest](./kibana-plugin-plugins-data-public.getsearchparamsfromrequest.md) + +## getSearchParamsFromRequest() function + +Signature: + +```typescript +export declare function getSearchParamsFromRequest(searchRequest: SearchRequest, dependencies: { + injectedMetadata: CoreStart['injectedMetadata']; + uiSettings: IUiSettingsClient; +}): { + rest_total_hits_as_int: boolean; + ignore_unavailable: boolean; + ignore_throttled: boolean; + max_concurrent_shard_requests: any; + preference: any; + timeout: string | undefined; + index: any; + body: any; +}; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| searchRequest | SearchRequest | | +| dependencies | {
injectedMetadata: CoreStart['injectedMetadata'];
uiSettings: IUiSettingsClient;
} | | + +Returns: + +`{ + rest_total_hits_as_int: boolean; + ignore_unavailable: boolean; + ignore_throttled: boolean; + max_concurrent_shard_requests: any; + preference: any; + timeout: string | undefined; + index: any; + body: any; +}` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md index e818fb009fb19..bc1eb9100e85c 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md @@ -40,6 +40,7 @@ | [getEsPreference(uiSettings, sessionId)](./kibana-plugin-plugins-data-public.getespreference.md) | | | [getQueryLog(uiSettings, storage, appName, language)](./kibana-plugin-plugins-data-public.getquerylog.md) | | | [getSearchErrorType({ message })](./kibana-plugin-plugins-data-public.getsearcherrortype.md) | | +| [getSearchParamsFromRequest(searchRequest, dependencies)](./kibana-plugin-plugins-data-public.getsearchparamsfromrequest.md) | | | [getTime(indexPattern, timeRange, options)](./kibana-plugin-plugins-data-public.gettime.md) | | | [plugin(initializerContext)](./kibana-plugin-plugins-data-public.plugin.md) | | diff --git a/docs/drilldowns/drilldowns.asciidoc b/docs/drilldowns/drilldowns.asciidoc new file mode 100644 index 0000000000000..2687441c99340 --- /dev/null +++ b/docs/drilldowns/drilldowns.asciidoc @@ -0,0 +1,108 @@ +[[drilldowns]] +== Use drilldowns for dashboard actions + +Drilldowns, also known as custom actions, allow you to configure a +workflow for analyzing and troubleshooting your data. +Using a drilldown, you can navigate from one dashboard to another, +taking the current time range, filters, and other parameters with you, +so the context remains the same. You can continue your analysis from a new perspective. + +For example, you might have a dashboard that shows the overall status of multiple data centers. +You can create a drilldown that navigates from this dashboard to a dashboard +that shows a single data center or server. + +[float] +[[how-drilldowns-work]] +=== How drilldowns work + +Drilldowns are {kib} actions that you configure and store +in the dashboard saved object. Drilldowns are specific to the dashboard panel +for which you create them—they are not shared across panels. +A panel can have multiple drilldowns. + +This example shows a dashboard panel that contains a pie chart. +Typically, clicking a pie slice applies the current filter. +When a panel has a drilldown, clicking a pie slice opens a menu with +the default action and your drilldowns. Refer to the <> +for instructions on how to create this drilldown. + +[role="screenshot"] +image::images/drilldown_on_piechart.gif[Drilldown on pie chart that navigates to another dashboard] + +Third-party developers can create drilldowns. +Refer to https://github.com/elastic/kibana/tree/master/x-pack/examples/ui_actions_enhanced_examples[this example plugin] +to learn how to code drilldowns. + +[float] +[[create-manage-drilldowns]] +=== Create and manage drilldowns + +Your dashboard must be in *Edit* mode to create a drilldown. +Once a panel has at least one drilldown, the menu also includes a *Manage drilldowns* action +for editing and deleting drilldowns. + +[role="screenshot"] +image::images/drilldown_menu.png[Panel menu with Create drilldown and Manage drilldown actions] + +[float] +[[drilldowns-example]] +=== Try it: Create a drilldown + +This example shows how to create the *Host Overview* drilldown shown earlier in this doc. + +[float] +==== Set up the dashboards + +. Add the <> data set. + +. Create a new dashboard, called `Host Overview`, and include these visualizations +from the sample data set: ++ +[%hardbreaks] +*[Logs] Heatmap* +*[Logs] Visitors by OS* +*[Logs] Host, Visits, and Bytes Table* +*[Logs] Total Requests and Bytes* ++ +TIP: If you don’t see data for a panel, try changing the time range. + +. Open the *[Logs] Web traffic* dashboard. + +. Set a search and filter. ++ +[%hardbreaks] +Search: `extension.keyword:( “gz” or “css” or “deb”)` +Filter: `geo.src : CN` + +[float] +==== Create the drilldown + + +. In the dashboard menu bar, click *Edit*. + +. In *[Logs] Visitors by OS*, open the panel menu, and then select *Create drilldown*. + +. Give the drilldown a name. + +. Select *Host Overview* as the destination dashboard. + +. Keep both filters enabled so that the drilldown carries over the global filters and date range. ++ +Your input should look similar to this: ++ +[role="screenshot"] +image::images/drilldown_create.png[Create drilldown with entries for drilldown name and destination] + +. Click *Create drilldown.* + +. Save the dashboard. ++ +If you don’t save the drilldown, and then navigate away, the drilldown is lost. + +. In *[Logs] Visitors by OS*, click the `win 8` slice of the pie, and then select the name of your drilldown. ++ +[role="screenshot"] +image::images/drilldown_on_panel.png[Drilldown on pie chart that navigates to another dashboard] ++ +You are navigated to your destination dashboard. Verify that the search query, filters, +and time range are carried over. diff --git a/docs/drilldowns/images/drilldown_create.png b/docs/drilldowns/images/drilldown_create.png new file mode 100644 index 0000000000000..1573a3dfb4f4f Binary files /dev/null and b/docs/drilldowns/images/drilldown_create.png differ diff --git a/docs/drilldowns/images/drilldown_menu.png b/docs/drilldowns/images/drilldown_menu.png new file mode 100644 index 0000000000000..28e0d995f840d Binary files /dev/null and b/docs/drilldowns/images/drilldown_menu.png differ diff --git a/docs/drilldowns/images/drilldown_on_panel.png b/docs/drilldowns/images/drilldown_on_panel.png new file mode 100644 index 0000000000000..591f3280c7eca Binary files /dev/null and b/docs/drilldowns/images/drilldown_on_panel.png differ diff --git a/docs/drilldowns/images/drilldown_on_piechart.gif b/docs/drilldowns/images/drilldown_on_piechart.gif new file mode 100644 index 0000000000000..c9b3311df0325 Binary files /dev/null and b/docs/drilldowns/images/drilldown_on_piechart.gif differ diff --git a/docs/settings/alert-action-settings.asciidoc b/docs/settings/alert-action-settings.asciidoc index 547b4fdedcec6..e02c7f212277e 100644 --- a/docs/settings/alert-action-settings.asciidoc +++ b/docs/settings/alert-action-settings.asciidoc @@ -1,6 +1,6 @@ [role="xpack"] [[alert-action-settings-kb]] -=== Alerting and action settings in Kibana +=== Alerting and action settings in {kib} ++++ Alerting and action settings ++++ diff --git a/docs/settings/apm-settings.asciidoc b/docs/settings/apm-settings.asciidoc index b781930485243..f78b0642f7fa3 100644 --- a/docs/settings/apm-settings.asciidoc +++ b/docs/settings/apm-settings.asciidoc @@ -12,7 +12,7 @@ It is enabled by default. [float] [[apm-indices-settings-kb]] -==== APM Indices +==== APM indices // This content is reused in the APM app documentation. // Any changes made in this file will be seen there as well. diff --git a/docs/settings/dev-settings.asciidoc b/docs/settings/dev-settings.asciidoc index c43b96a8668e0..e92e9c2928793 100644 --- a/docs/settings/dev-settings.asciidoc +++ b/docs/settings/dev-settings.asciidoc @@ -1,6 +1,6 @@ [role="xpack"] [[dev-settings-kb]] -=== Development tools settings in Kibana +=== Development tools settings in {kib} ++++ Development tools settings ++++ @@ -21,7 +21,7 @@ They are enabled by default. [float] [[profiler-settings]] -==== {searchprofiler} Settings +==== {searchprofiler} settings [cols="2*<"] |=== diff --git a/docs/settings/graph-settings.asciidoc b/docs/settings/graph-settings.asciidoc index 8ccff21a26f74..a66785242c19a 100644 --- a/docs/settings/graph-settings.asciidoc +++ b/docs/settings/graph-settings.asciidoc @@ -1,6 +1,6 @@ [role="xpack"] [[graph-settings-kb]] -=== Graph settings in Kibana +=== Graph settings in {kib} ++++ Graph settings ++++ diff --git a/docs/settings/i18n-settings.asciidoc b/docs/settings/i18n-settings.asciidoc index 6d92e74f17cb2..8f498c507a8c2 100644 --- a/docs/settings/i18n-settings.asciidoc +++ b/docs/settings/i18n-settings.asciidoc @@ -1,12 +1,15 @@ [role="xpack"] [[i18n-settings-kb]] -=== i18n settings in Kibana +=== i18n settings in {kib} +++++ +i18n settings +++++ You do not need to configure any settings to run Kibana in English. [float] [[general-i18n-settings-kb]] -==== General i18n Settings +==== General i18n settings `i18n.locale`:: {kib} supports the following locales: diff --git a/docs/settings/infrastructure-ui-settings.asciidoc b/docs/settings/infrastructure-ui-settings.asciidoc index ed69c27feab72..c29ed567531d5 100644 --- a/docs/settings/infrastructure-ui-settings.asciidoc +++ b/docs/settings/infrastructure-ui-settings.asciidoc @@ -1,6 +1,6 @@ [role="xpack"] [[infrastructure-ui-settings-kb]] -=== Metrics settings in Kibana +=== Metrics settings in {kib} ++++ Metrics settings ++++ @@ -11,4 +11,4 @@ You do not need to configure any settings to use the Metrics app in {kib}. It is [[general-infra-ui-settings-kb]] ==== General Metrics settings -include::general-infra-logs-ui-settings.asciidoc[] \ No newline at end of file +include::general-infra-logs-ui-settings.asciidoc[] diff --git a/docs/settings/logs-ui-settings.asciidoc b/docs/settings/logs-ui-settings.asciidoc index 5b6dd902091ae..e7321b7f0768c 100644 --- a/docs/settings/logs-ui-settings.asciidoc +++ b/docs/settings/logs-ui-settings.asciidoc @@ -1,6 +1,6 @@ [role="xpack"] [[logs-ui-settings-kb]] -=== Logs app settings in Kibana +=== Logs settings in {kib} ++++ Logs settings ++++ diff --git a/docs/settings/ml-settings.asciidoc b/docs/settings/ml-settings.asciidoc index 83443636fa633..92d0c0b491ce7 100644 --- a/docs/settings/ml-settings.asciidoc +++ b/docs/settings/ml-settings.asciidoc @@ -1,12 +1,12 @@ [role="xpack"] [[ml-settings-kb]] -=== Machine learning settings in Kibana +=== Machine learning settings in {kib} ++++ Machine learning settings ++++ You do not need to configure any settings to use {kib} {ml-features}. They are -enabled by default. +enabled by default. [[general-ml-settings-kb]] ==== General {ml} settings @@ -26,4 +26,4 @@ enabled by default. [[advanced-ml-settings-kb]] ==== Advanced {ml} settings -Refer to <>. \ No newline at end of file +Refer to <>. diff --git a/docs/settings/monitoring-settings.asciidoc b/docs/settings/monitoring-settings.asciidoc index f180f2c3ecc97..48b5b5eb5d0c0 100644 --- a/docs/settings/monitoring-settings.asciidoc +++ b/docs/settings/monitoring-settings.asciidoc @@ -1,6 +1,6 @@ [role="xpack"] [[monitoring-settings-kb]] -=== Monitoring settings in Kibana +=== Monitoring settings in {kib} ++++ Monitoring settings ++++ diff --git a/docs/settings/reporting-settings.asciidoc b/docs/settings/reporting-settings.asciidoc index da109331ae0fb..928878fdcdb03 100644 --- a/docs/settings/reporting-settings.asciidoc +++ b/docs/settings/reporting-settings.asciidoc @@ -1,6 +1,6 @@ [role="xpack"] [[reporting-settings-kb]] -=== Reporting settings in Kibana +=== Reporting settings in {kib} ++++ Reporting settings ++++ diff --git a/docs/settings/security-settings.asciidoc b/docs/settings/security-settings.asciidoc index 8f6905d643139..4eaa4dfa55c4d 100644 --- a/docs/settings/security-settings.asciidoc +++ b/docs/settings/security-settings.asciidoc @@ -1,6 +1,6 @@ [role="xpack"] [[security-settings-kb]] -=== Security settings in Kibana +=== Security settings in {kib} ++++ Security settings ++++ diff --git a/docs/settings/settings-xkb.asciidoc b/docs/settings/settings-xkb.asciidoc index f9727db838d55..4d594b4113e69 100644 --- a/docs/settings/settings-xkb.asciidoc +++ b/docs/settings/settings-xkb.asciidoc @@ -1,9 +1,9 @@ [role="xpack"] [[settings-xpack-kb]] -== {xpack} Settings in {kib} +== {xpack} settings in {kib} [subs="attributes"] ++++ -{xpack} Settings +{xpack} settings ++++ include::{asciidoc-dir}/../../shared/settings.asciidoc[] diff --git a/docs/settings/telemetry-settings.asciidoc b/docs/settings/telemetry-settings.asciidoc index 33f167b13b310..89c018a86eca6 100644 --- a/docs/settings/telemetry-settings.asciidoc +++ b/docs/settings/telemetry-settings.asciidoc @@ -1,5 +1,5 @@ [[telemetry-settings-kbn]] -=== Telemetry settings in Kibana +=== Telemetry settings in {kib} ++++ Telemetry settings ++++ @@ -29,7 +29,7 @@ See our https://www.elastic.co/legal/privacy-statement[Privacy Statement] to lea | Set to `'server'` to report the cluster statistics from the {kib} server. If the server fails to connect to our endpoint at https://telemetry.elastic.co/, it assumes it is behind a firewall and falls back to `'browser'` to send it from users' browsers - when they are navigating through {kib}. Defaults to 'browser'. + when they are navigating through {kib}. Defaults to `'server'`. | `telemetry.optIn` | Set to `true` to automatically opt into reporting cluster statistics. You can also opt out through diff --git a/docs/setup/access.asciidoc b/docs/setup/access.asciidoc index a7374a37ddaec..49aa411e91512 100644 --- a/docs/setup/access.asciidoc +++ b/docs/setup/access.asciidoc @@ -1,5 +1,5 @@ [[access]] -== Accessing Kibana +== Access {kib} Kibana is a web application that you access through port 5601. All you need to do is point your web browser at the machine where Kibana is running and specify the port number. For example, `localhost:5601` or `http://YOURDOMAIN.com:5601`. @@ -13,7 +13,7 @@ If you still don't see any results, it's possible that you don't *have* any docu [float] [[status]] -=== Checking Kibana Status +=== Check {kib} status You can reach the Kibana server's status page by navigating to the status endpoint, for example, `localhost:5601/status`. The status page displays information about the server's resource usage and lists the installed plugins. diff --git a/docs/setup/connect-to-elasticsearch.asciidoc b/docs/setup/connect-to-elasticsearch.asciidoc index 6137e028db3fd..6d6996c2094c6 100644 --- a/docs/setup/connect-to-elasticsearch.asciidoc +++ b/docs/setup/connect-to-elasticsearch.asciidoc @@ -1,5 +1,5 @@ [[connect-to-elasticsearch]] -== Adding data +== Add data to {kib} To start working with your data in {kib}, you can: diff --git a/docs/setup/docker.asciidoc b/docs/setup/docker.asciidoc index e8029ed1bbe9b..fb4cbbada9a33 100644 --- a/docs/setup/docker.asciidoc +++ b/docs/setup/docker.asciidoc @@ -1,5 +1,5 @@ [[docker]] -== Running Kibana on Docker +=== Install Kibana with Docker Docker images for Kibana are available from the Elastic Docker registry. The base image is https://hub.docker.com/_/centos/[centos:7]. @@ -16,7 +16,7 @@ Elastic license levels. [float] [[pull-image]] -=== Pulling the image +=== Pull the image Obtaining Kibana for Docker is as simple as issuing a +docker pull+ command against the Elastic Docker registry. @@ -40,7 +40,7 @@ available under the Apache 2.0 license. To download the images, go to https://www.docker.elastic.co[www.docker.elastic.co]. [float] -=== Running Kibana on Docker for development +=== Run Kibana on Docker for development Kibana can be quickly started and connected to a local Elasticsearch container for development or testing use with the following command: -------------------------------------------- @@ -50,7 +50,7 @@ endif::[] [float] [[configuring-kibana-docker]] -=== Configuring Kibana on Docker +=== Configure Kibana on Docker The Docker images provide several methods for configuring Kibana. The conventional approach is to provide a `kibana.yml` file as described in diff --git a/docs/setup/install.asciidoc b/docs/setup/install.asciidoc index f557dd2280e4c..73036da8f1390 100644 --- a/docs/setup/install.asciidoc +++ b/docs/setup/install.asciidoc @@ -1,13 +1,13 @@ [[install]] -== Installing Kibana +== Install {kib} [float] -=== Hosted Kibana +=== Hosted {kib} If you are running our hosted Elasticsearch Service on Elastic Cloud, you access Kibana with a single click. (You can {ess-trial}[sign up for a free trial] and start exploring data in minutes.) [float] -=== Installing Kibana Yourself +=== Install {kib} yourself NOTE: Starting with version 6.0.0, Kibana only supports 64 bit operating systems. @@ -59,10 +59,12 @@ additional setup instructions. include::install/targz.asciidoc[] +include::install/windows.asciidoc[] + include::install/deb.asciidoc[] include::install/rpm.asciidoc[] -include::install/windows.asciidoc[] +include::{kib-repo-dir}/setup/docker.asciidoc[] include::install/brew.asciidoc[] diff --git a/docs/setup/install/brew-running.asciidoc b/docs/setup/install/brew-running.asciidoc index ba78dd1659d04..d73102b098ec1 100644 --- a/docs/setup/install/brew-running.asciidoc +++ b/docs/setup/install/brew-running.asciidoc @@ -1,6 +1,6 @@ -==== Running Kibana with `brew services` +==== Run {kib} with `brew services` -With Homebrew, Kibana can be started and stopped as follows: +With Homebrew, Kibana can be started and stopped as follows: [source,sh] -------------------------------------------------- diff --git a/docs/setup/install/deb-init.asciidoc b/docs/setup/install/deb-init.asciidoc index 1b92eeadd2efb..6e21b8f97cf7e 100644 --- a/docs/setup/install/deb-init.asciidoc +++ b/docs/setup/install/deb-init.asciidoc @@ -1,4 +1,4 @@ -==== Running Kibana with SysV `init` +==== Run {kib} with SysV `init` Use the `update-rc.d` command to configure Kibana to start automatically when the system boots up: @@ -18,4 +18,3 @@ sudo -i service kibana stop If Kibana fails to start for any reason, it will print the reason for failure to `STDOUT`. Log files can be found in `/var/log/kibana/`. - diff --git a/docs/setup/install/deb.asciidoc b/docs/setup/install/deb.asciidoc index 62ab661d9a66c..8193a088c8b7e 100644 --- a/docs/setup/install/deb.asciidoc +++ b/docs/setup/install/deb.asciidoc @@ -1,15 +1,15 @@ [[deb]] -=== Install Kibana with Debian Package +=== Install {kib} with Debian package The Debian package for Kibana can be <> or from our <>. It can be used to install Kibana on any Debian-based system such as Debian and Ubuntu. -This package is free to use under the Elastic license. It contains open source -and free commercial features and access to paid commercial features. -{stack-ov}/license-management.html[Start a 30-day trial] to try out all of the -paid commercial features. See the -https://www.elastic.co/subscriptions[Subscriptions] page for information about +This package is free to use under the Elastic license. It contains open source +and free commercial features and access to paid commercial features. +{stack-ov}/license-management.html[Start a 30-day trial] to try out all of the +paid commercial features. See the +https://www.elastic.co/subscriptions[Subscriptions] page for information about Elastic license levels. The latest stable version of Kibana can be found on the @@ -17,7 +17,7 @@ link:/downloads/kibana[Download Kibana] page. Other versions can be found on the link:/downloads/past-releases[Past Releases page]. [[deb-key]] -==== Import the Elastic PGP Key +==== Import the Elastic PGP key include::key.asciidoc[] @@ -27,7 +27,7 @@ wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add ------------------------- [[deb-repo]] -==== Installing from the APT repository +==== Install from the APT repository ifeval::["{release-state}"=="unreleased"] @@ -151,9 +151,9 @@ sudo dpkg -i kibana-{version}-amd64.deb <1> Compare the SHA produced by `shasum` with the https://artifacts.elastic.co/downloads/kibana/kibana-{version}-amd64.deb.sha512[published SHA]. -Alternatively, you can download the following package, which contains only -features that are available under the Apache 2.0 license: -https://artifacts.elastic.co/downloads/kibana/kibana-oss-{version}-amd64.deb +Alternatively, you can download the following package, which contains only +features that are available under the Apache 2.0 license: +https://artifacts.elastic.co/downloads/kibana/kibana-oss-{version}-amd64.deb endif::[] @@ -169,7 +169,7 @@ include::deb-init.asciidoc[] include::systemd.asciidoc[] [[deb-configuring]] -==== Configuring Kibana via config file +==== Configure {kib} via the config file Kibana loads its configuration from the `/etc/kibana/kibana.yml` file by default. The format of this config file is explained in @@ -205,7 +205,7 @@ locations for a Debian-based system: | The location of the data files written to disk by Kibana and its plugins | /var/lib/kibana | path.data - + | logs | Logs files location | /var/log/kibana diff --git a/docs/setup/install/rpm-init.asciidoc b/docs/setup/install/rpm-init.asciidoc index 6b3d6d49a4ead..08282635a014f 100644 --- a/docs/setup/install/rpm-init.asciidoc +++ b/docs/setup/install/rpm-init.asciidoc @@ -1,4 +1,4 @@ -==== Running Kibana with SysV `init` +==== Run {kib} with SysV `init` Use the `chkconfig` command to configure Kibana to start automatically when the system boots up: diff --git a/docs/setup/install/rpm.asciidoc b/docs/setup/install/rpm.asciidoc index 77a16e67cf2a4..c3922ffba1efa 100644 --- a/docs/setup/install/rpm.asciidoc +++ b/docs/setup/install/rpm.asciidoc @@ -1,5 +1,5 @@ [[rpm]] -=== Install Kibana with RPM +=== Install {kib} with RPM The RPM for Kibana can be <> or from our <>. It can be used to install @@ -9,11 +9,11 @@ and Oracle Enterprise. NOTE: RPM install is not supported on distributions with old versions of RPM, such as SLES 11 and CentOS 5. Please see <> instead. -This package is free to use under the Elastic license. It contains open source -and free commercial features and access to paid commercial features. -{stack-ov}/license-management.html[Start a 30-day trial] to try out all of the -paid commercial features. See the -https://www.elastic.co/subscriptions[Subscriptions] page for information about +This package is free to use under the Elastic license. It contains open source +and free commercial features and access to paid commercial features. +{stack-ov}/license-management.html[Start a 30-day trial] to try out all of the +paid commercial features. See the +https://www.elastic.co/subscriptions[Subscriptions] page for information about Elastic license levels. The latest stable version of Kibana can be found on the @@ -21,7 +21,7 @@ link:/downloads/kibana[Download Kibana] page. Other versions can be found on the link:/downloads/past-releases[Past Releases page]. [[rpm-key]] -==== Import the Elastic PGP Key +==== Import the Elastic PGP key include::key.asciidoc[] @@ -143,9 +143,9 @@ sudo rpm --install kibana-{version}-x86_64.rpm <1> Compare the SHA produced by `shasum` with the https://artifacts.elastic.co/downloads/kibana/kibana-{version}-x86_64.rpm.sha512[published SHA]. -Alternatively, you can download the following package, which contains only +Alternatively, you can download the following package, which contains only features that are available under the Apache 2.0 license: -https://artifacts.elastic.co/downloads/kibana/kibana-oss-{version}-x86_64.rpm +https://artifacts.elastic.co/downloads/kibana/kibana-oss-{version}-x86_64.rpm endif::[] @@ -160,7 +160,7 @@ include::rpm-init.asciidoc[] include::systemd.asciidoc[] [[rpm-configuring]] -==== Configuring Kibana via config file +==== Configure {kib} via the config file Kibana loads its configuration from the `/etc/kibana/kibana.yml` file by default. The format of this config file is explained in @@ -196,7 +196,7 @@ locations for an RPM-based system: | The location of the data files written to disk by Kibana and its plugins | /var/lib/kibana | path.data - + | logs | Logs files location | /var/log/kibana diff --git a/docs/setup/install/systemd.asciidoc b/docs/setup/install/systemd.asciidoc index 3053972f9e384..6fcb82217affc 100644 --- a/docs/setup/install/systemd.asciidoc +++ b/docs/setup/install/systemd.asciidoc @@ -1,4 +1,4 @@ -==== Running Kibana with `systemd` +==== Run {kib} with `systemd` To configure Kibana to start automatically when the system boots up, run the following commands: diff --git a/docs/setup/install/targz-running.asciidoc b/docs/setup/install/targz-running.asciidoc index dd4fd722e127e..d3813d9811b13 100644 --- a/docs/setup/install/targz-running.asciidoc +++ b/docs/setup/install/targz-running.asciidoc @@ -1,4 +1,4 @@ -==== Running Kibana from the command line +==== Run {kib} from the command line Kibana can be started from the command line as follows: diff --git a/docs/setup/install/targz.asciidoc b/docs/setup/install/targz.asciidoc index 31970888a976b..a53360900657e 100644 --- a/docs/setup/install/targz.asciidoc +++ b/docs/setup/install/targz.asciidoc @@ -1,5 +1,5 @@ [[targz]] -=== Install {kib} from archive on Linux or MacOS +=== Install {kib} from archive on Linux or macOS Kibana is provided for Linux and Darwin as a `.tar.gz` package. These packages are the easiest formats to use when trying out Kibana. @@ -101,7 +101,7 @@ include::targz-running.asciidoc[] [[targz-configuring]] -==== Configuring Kibana via config file +==== Configure {kib} via the config file Kibana loads its configuration from the `$KIBANA_HOME/config/kibana.yml` file by default. The format of this config file is explained in diff --git a/docs/setup/install/windows-running.asciidoc b/docs/setup/install/windows-running.asciidoc index 57d756a07c13d..832284edc8f39 100644 --- a/docs/setup/install/windows-running.asciidoc +++ b/docs/setup/install/windows-running.asciidoc @@ -1,4 +1,4 @@ -==== Running Kibana from the command line +==== Run {kib} from the command line Kibana can be started from the command line as follows: diff --git a/docs/setup/install/windows.asciidoc b/docs/setup/install/windows.asciidoc index db55451f01aae..1cfbaaa0eda2f 100644 --- a/docs/setup/install/windows.asciidoc +++ b/docs/setup/install/windows.asciidoc @@ -1,13 +1,13 @@ [[windows]] -=== Install Kibana on Windows +=== Install {kib} on Windows Kibana can be installed on Windows using the `.zip` package. -This package is free to use under the Elastic license. It contains open source -and free commercial features and access to paid commercial features. -{stack-ov}/license-management.html[Start a 30-day trial] to try out all of the -paid commercial features. See the -https://www.elastic.co/subscriptions[Subscriptions] page for information about +This package is free to use under the Elastic license. It contains open source +and free commercial features and access to paid commercial features. +{stack-ov}/license-management.html[Start a 30-day trial] to try out all of the +paid commercial features. See the +https://www.elastic.co/subscriptions[Subscriptions] page for information about Elastic license levels. The latest stable version of Kibana can be found on the @@ -39,9 +39,9 @@ terminal window, `CD` to the `$KIBANA_HOME` directory, for instance: CD c:\kibana-{version}-windows-x86_64 ---------------------------- -Alternatively, you can download the following package, which contains only +Alternatively, you can download the following package, which contains only features that are available under the Apache 2.0 license: -https://artifacts.elastic.co/downloads/kibana/kibana-oss-{version}-windows-x86_64.zip +https://artifacts.elastic.co/downloads/kibana/kibana-oss-{version}-windows-x86_64.zip endif::[] @@ -49,7 +49,7 @@ endif::[] include::windows-running.asciidoc[] [[windows-configuring]] -==== Configuring Kibana via config file +==== Configure {kib} via the config file Kibana loads its configuration from the `$KIBANA_HOME/config/kibana.yml` file by default. The format of this config file is explained in diff --git a/docs/setup/production.asciidoc b/docs/setup/production.asciidoc index 19f9d64d13623..72f275e237490 100644 --- a/docs/setup/production.asciidoc +++ b/docs/setup/production.asciidoc @@ -1,5 +1,5 @@ [[production]] -== Using Kibana in a production environment +== Use {kib} in a production environment * <> * <> @@ -23,7 +23,7 @@ and an Elasticsearch client node on the same machine. For more information, see [float] [[configuring-kibana-shield]] -=== Using {stack} {security-features} +=== Use {stack} {security-features} You can use {stack} {security-features} to control what {es} data users can access through Kibana. @@ -59,13 +59,13 @@ csp.strict: true [float] [[enabling-ssl]] -=== Enabling SSL +=== Enable SSL See <>. [float] [[load-balancing-es]] -=== Load Balancing Across Multiple Elasticsearch Nodes +=== Load Balancing across multiple {es} nodes If you have multiple nodes in your Elasticsearch cluster, the easiest way to distribute Kibana requests across the nodes is to run an Elasticsearch _Coordinating only_ node on the same machine as Kibana. Elasticsearch Coordinating only nodes are essentially smart load balancers that are part of the cluster. They @@ -145,7 +145,7 @@ bin/kibana -c config/instance2.yml [float] [[high-availability]] -=== High availability across multiple Elasticsearch nodes +=== High availability across multiple {es} nodes Kibana can be configured to connect to multiple Elasticsearch nodes in the same cluster. In situations where a node becomes unavailable, Kibana will transparently connect to an available node and continue operating. Requests to available hosts will be routed in a round robin fashion. diff --git a/docs/setup/secure-settings.asciidoc b/docs/setup/secure-settings.asciidoc index a7ccd3f77405e..10380eb5d8fa4 100644 --- a/docs/setup/secure-settings.asciidoc +++ b/docs/setup/secure-settings.asciidoc @@ -9,7 +9,7 @@ NOTE: All commands here should be run as the user which will run Kibana. [float] [[creating-keystore]] -=== Creating the keystore +=== Create the keystore To create the `kibana.keystore`, use the `create` command: @@ -23,7 +23,7 @@ The file `kibana.keystore` will be created in the directory defined by the [float] [[list-settings]] -=== Listing settings in the keystore +=== List settings in the keystore A list of the settings in the keystore is available with the `list` command: @@ -34,7 +34,7 @@ bin/kibana-keystore list [float] [[add-string-to-keystore]] -=== Adding string settings +=== Add string settings Sensitive string settings, like authentication credentials for Elasticsearch can be added using the `add` command: @@ -65,7 +65,7 @@ cat /file/containing/setting/value | bin/kibana-keystore add the.setting.name.to [float] [[remove-settings]] -=== Removing settings +=== Remove settings To remove a setting from the keystore, use the `remove` command: diff --git a/docs/setup/settings.asciidoc b/docs/setup/settings.asciidoc index 1be9d5b1ef35b..c4f5439e25489 100644 --- a/docs/setup/settings.asciidoc +++ b/docs/setup/settings.asciidoc @@ -1,5 +1,5 @@ [[settings]] -== Configuring {kib} +== Configure {kib} The {kib} server reads properties from the `kibana.yml` file on startup. The location of this file differs depending on how you installed {kib}. For example, diff --git a/docs/setup/start-stop.asciidoc b/docs/setup/start-stop.asciidoc index 2fcc440680f12..198bc76bbb400 100644 --- a/docs/setup/start-stop.asciidoc +++ b/docs/setup/start-stop.asciidoc @@ -1,15 +1,15 @@ [[start-stop]] -== Starting and stopping Kibana +== Start and stop {kib} -The method for starting and stopping {kib} varies depending on how you installed -it. +The method for starting and stopping {kib} varies depending on how you installed +it. [float] [[start-start-targz]] === Archive packages (`.tar.gz`) -If you installed {kib} on Linux or Darwin with a `.tar.gz` package, you can -start and stop {kib} from the command line. +If you installed {kib} on Linux or Darwin with a `.tar.gz` package, you can +start and stop {kib} from the command line. [float] include::install/targz-running.asciidoc[] @@ -18,8 +18,8 @@ include::install/targz-running.asciidoc[] [[start-stop-zip]] === Archive packages (`.zip`) -If you installed {kib} on Windows with a `.zip` package, you can -stop and start {kib} from the command line. +If you installed {kib} on Windows with a `.zip` package, you can +stop and start {kib} from the command line. [float] include::install/windows-running.asciidoc[] diff --git a/docs/setup/upgrade.asciidoc b/docs/setup/upgrade.asciidoc index 982f1167f3871..6d69b6921b612 100644 --- a/docs/setup/upgrade.asciidoc +++ b/docs/setup/upgrade.asciidoc @@ -1,15 +1,15 @@ [[upgrade]] -== Upgrading {kib} +== Upgrade {kib} Depending on the {kib} version you're upgrading from, the upgrade process to 7.0 -varies. +varies. -NOTE: {kib} upgrades automatically when starting a new version, as described in +NOTE: {kib} upgrades automatically when starting a new version, as described in <>. Although you do not need to manually back up {kib} before upgrading, we recommend -that you have a backup on hand. You can use +that you have a backup on hand. You can use <> to back up {kib} -data by targeting `.kibana*` indices. If you are using the Reporting plugin, +data by targeting `.kibana*` indices. If you are using the Reporting plugin, you can also target `.reporting*` indices. [float] @@ -23,44 +23,44 @@ Before you upgrade {kib}: * Back up your data with {es} {ref}/modules-snapshots.html[snapshots]. To roll back to an earlier version, you **must** have a backup of your data. * If you are using custom plugins, check that a compatible version is - available. -* Shut down all {kib} nodes. Running more than one {kib} version against the - same Elasticseach index is unsupported. If you upgrade while older {kib} nodes are + available. +* Shut down all {kib} nodes. Running more than one {kib} version against the + same Elasticseach index is unsupported. If you upgrade while older {kib} nodes are running, the upgrade can fail. -To identify the changes you need to make to upgrade, and to enable you to -perform an Elasticsearch rolling upgrade with no downtime, you must upgrade to +To identify the changes you need to make to upgrade, and to enable you to +perform an Elasticsearch rolling upgrade with no downtime, you must upgrade to 6.7 before you upgrade to 7.0. -For a comprehensive overview of the upgrade process, refer to +For a comprehensive overview of the upgrade process, refer to *{stack-ref}/upgrading-elastic-stack.html[Upgrading the Elastic Stack]*. [float] [[upgrade-5x-earlier]] -=== Upgrading from 5.x or earlier -{es} can read indices created in the previous major version. Before you upgrade -to 7.0.0, you must reindex or delete any indices created in 5.x or earlier. -For more information, refer to +=== Upgrade from 5.x or earlier +{es} can read indices created in the previous major version. Before you upgrade +to 7.0.0, you must reindex or delete any indices created in 5.x or earlier. +For more information, refer to {stack-ref}/upgrading-elastic-stack.html#oss-stack-upgrade[Upgrading the Elastic Stack]. -When your reindex is complete, follow the <> -instructions. +When your reindex is complete, follow the <> +instructions. [float] [[upgrade-6x]] -=== Upgrading from 6.x +=== Upgrade from 6.x -The recommended path is to upgrade to 6.8 before upgrading to 7.0. This makes it -easier to identify the required changes, and enables you to use the Upgrade +The recommended path is to upgrade to 6.8 before upgrading to 7.0. This makes it +easier to identify the required changes, and enables you to use the Upgrade Assistant to prepare for your upgrade to 7.0. -TIP: The ability to import {kib} 6.x saved searches, visualizations, and +TIP: The ability to import {kib} 6.x saved searches, visualizations, and dashboards is supported. [float] [[upgrade-67]] -=== Upgrading from 6.8 -To help you prepare for your upgrade to 7.0, 6.8 includes an https://www.elastic.co/guide/en/kibana/6.8/upgrade-assistant.html[Upgrade Assistant] +=== Upgrade from 6.8 +To help you prepare for your upgrade to 7.0, 6.8 includes an https://www.elastic.co/guide/en/kibana/6.8/upgrade-assistant.html[Upgrade Assistant] To access the assistant, go to *Management > 7.0 Upgrade Assistant*. After you have addressed any issues that were identified by the Upgrade @@ -70,4 +70,3 @@ Assistant, <>. include::upgrade/upgrade-standard.asciidoc[] include::upgrade/upgrade-migrations.asciidoc[] - diff --git a/docs/setup/upgrade/upgrade-migrations.asciidoc b/docs/setup/upgrade/upgrade-migrations.asciidoc index 81ff8344c4c5f..cbe56b9e65894 100644 --- a/docs/setup/upgrade/upgrade-migrations.asciidoc +++ b/docs/setup/upgrade/upgrade-migrations.asciidoc @@ -1,10 +1,10 @@ [[upgrade-migrations]] -=== Troubleshooting saved object migrations +=== Migrate saved objects Every time {kib} is upgraded it checks to see if all saved objects, such as dashboards, visualizations, and index patterns, are compatible with the new version. If any objects need to be updated, then the automatic saved object migration process is kicked off. -NOTE: 6.7 includes an https://www.elastic.co/guide/en/kibana/6.7/upgrade-assistant.html[Upgrade Assistant] -to help you prepare for your upgrade to 7.0. To access the assistant, go to *Management > 7.0 Upgrade Assistant*. +NOTE: 6.7 includes an https://www.elastic.co/guide/en/kibana/6.7/upgrade-assistant.html[Upgrade Assistant] +to help you prepare for your upgrade to 7.0. To access the assistant, go to *Management > 7.0 Upgrade Assistant*. [float] [[upgrade-migrations-process]] @@ -46,11 +46,9 @@ The first instance that triggers saved object migrations will run the entire pro [[upgrade-migrations-rolling-back]] ==== Rolling back to a previous version of {kib} -When rolling {kib} back to a previous version, point the `.kibana` alias to -the appropriate {kib} index. When you have the previous version running again, -delete the more recent `.kibana_N` index or indices so that future upgrades are +When rolling {kib} back to a previous version, point the `.kibana` alias to +the appropriate {kib} index. When you have the previous version running again, +delete the more recent `.kibana_N` index or indices so that future upgrades are based on the current {kib} index. You must restart {kib} to re-trigger the migration. WARNING: Rolling back to a previous {kib} version can result in saved object data loss if you had successfully upgraded and made changes to saved objects before rolling back. - - diff --git a/docs/setup/upgrade/upgrade-standard.asciidoc b/docs/setup/upgrade/upgrade-standard.asciidoc index 683383525a3bb..df38427881d65 100644 --- a/docs/setup/upgrade/upgrade-standard.asciidoc +++ b/docs/setup/upgrade/upgrade-standard.asciidoc @@ -1,8 +1,8 @@ [[upgrade-standard]] === Standard upgrade -NOTE: 6.7 includes an https://www.elastic.co/guide/en/kibana/6.7/upgrade-assistant.html[Upgrade Assistant] -to help you prepare for your upgrade to 7.0. To access the assistant, go to *Management > 7.0 Upgrade Assistant*. +NOTE: 6.7 includes an https://www.elastic.co/guide/en/kibana/6.7/upgrade-assistant.html[Upgrade Assistant] +to help you prepare for your upgrade to 7.0. To access the assistant, go to *Management > 7.0 Upgrade Assistant*. [IMPORTANT] =========================================== @@ -13,7 +13,7 @@ necessary remediation steps as per those instructions. =========================================== [float] -==== Upgrading using a `deb` or `rpm` package +==== Upgrade using a `deb` or `rpm` package . Stop the existing {kib} process using the appropriate command for your system. @@ -37,7 +37,7 @@ otherwise {kib} will fail to start. . Start the new {kib} process using the appropriate command for your system. [float] -==== Upgrading using a `zip` or `tar.gz` archive +==== Upgrade using a `zip` or `tar.gz` archive . Extract the `zip` or `tar.gz` archive to a new directory to be sure that you don't overwrite the `config` or `data` directories. + diff --git a/docs/user/alerting/action-types/pre-configured-connectors.asciidoc b/docs/user/alerting/action-types/pre-configured-connectors.asciidoc index b3e401256f27b..e41bd0939495d 100644 --- a/docs/user/alerting/action-types/pre-configured-connectors.asciidoc +++ b/docs/user/alerting/action-types/pre-configured-connectors.asciidoc @@ -28,7 +28,7 @@ two out-of-the box connectors: <> and < actionTypeId: .slack <2> name: 'Slack #xyz' <3> - config: <4> + secrets: <4> webhookUrl: 'https://hooks.slack.com/services/abcd/efgh/ijklmnopqrstuvwxyz' webhook-service: actionTypeId: .webhook diff --git a/docs/user/dashboard.asciidoc b/docs/user/dashboard.asciidoc index 1614f00f37ac7..b90593c46db4c 100644 --- a/docs/user/dashboard.asciidoc +++ b/docs/user/dashboard.asciidoc @@ -159,6 +159,8 @@ When you're finished adding and arranging the panels, save the dashboard. . Enter the dashboard *Title* and optional *Description*, then *Save* the dashboard. +include::{kib-repo-dir}/drilldowns/drilldowns.asciidoc[] + [[sharing-dashboards]] == Share the dashboard diff --git a/docs/user/monitoring/configuring-monitoring.asciidoc b/docs/user/monitoring/configuring-monitoring.asciidoc index 776a76b24c4ec..7bcddcac923b2 100644 --- a/docs/user/monitoring/configuring-monitoring.asciidoc +++ b/docs/user/monitoring/configuring-monitoring.asciidoc @@ -1,20 +1,20 @@ [role="xpack"] [[configuring-monitoring]] -== Configuring monitoring in {kib} +== Configure monitoring in {kib} ++++ -Configuring monitoring +Configure monitoring ++++ -If you enable the {monitor-features} in your cluster, there are two methods to +If you enable the {monitor-features} in your cluster, there are two methods to collect metrics about {kib}: * <> * <> -You can also use {kib} to +You can also use {kib} to <>. -To learn about monitoring in general, see +To learn about monitoring in general, see {ref}/monitor-elasticsearch-cluster.html[Monitor a cluster]. include::monitoring-metricbeat.asciidoc[] diff --git a/docs/user/monitoring/monitoring-kibana.asciidoc b/docs/user/monitoring/monitoring-kibana.asciidoc index bb619ac79e143..ba55e2d16c150 100644 --- a/docs/user/monitoring/monitoring-kibana.asciidoc +++ b/docs/user/monitoring/monitoring-kibana.asciidoc @@ -1,45 +1,45 @@ [role="xpack"] [[monitoring-kibana]] -=== Collecting monitoring data using legacy collectors +=== Collect monitoring data using legacy collectors ++++ Legacy collection methods ++++ -If you enable the Elastic {monitor-features} in your cluster, you can -optionally collect metrics about {kib}. +If you enable the Elastic {monitor-features} in your cluster, you can +optionally collect metrics about {kib}. -The following method involves sending the metrics to the production cluster, -which ultimately routes them to the monitoring cluster. For the recommended -method, see <>. +The following method involves sending the metrics to the production cluster, +which ultimately routes them to the monitoring cluster. For the recommended +method, see <>. -To learn about monitoring in general, see -{ref}/monitor-elasticsearch-cluster.html[Monitor a cluster]. +To learn about monitoring in general, see +{ref}/monitor-elasticsearch-cluster.html[Monitor a cluster]. . Set the `xpack.monitoring.collection.enabled` setting to `true` on each -node in the production cluster. By default, it is is disabled (`false`). -+ +node in the production cluster. By default, it is is disabled (`false`). ++ -- -NOTE: You can specify this setting in either the `elasticsearch.yml` on each -node or across the cluster as a dynamic cluster setting. If {es} -{security-features} are enabled, you must have `monitor` cluster privileges to +NOTE: You can specify this setting in either the `elasticsearch.yml` on each +node or across the cluster as a dynamic cluster setting. If {es} +{security-features} are enabled, you must have `monitor` cluster privileges to view the cluster settings and `manage` cluster privileges to change them. -- ** To update the cluster settings in {kib}: -... Open {kib} in your web browser. +... Open {kib} in your web browser. + -- -By default, if you are running {kib} locally, go to `http://localhost:5601/`. +By default, if you are running {kib} locally, go to `http://localhost:5601/`. -If {es} {security-features} are enabled, log in. +If {es} {security-features} are enabled, log in. -- ... In the side navigation, click *Stack Monitoring*. If data collection is -disabled, you are prompted to turn it on. +disabled, you are prompted to turn it on. -** From the Console or command line, set `xpack.monitoring.collection.enabled` +** From the Console or command line, set `xpack.monitoring.collection.enabled` to `true` on the production cluster. + + -- @@ -57,13 +57,13 @@ PUT _cluster/settings } ---------------------------------- -For more information, see {ref}/monitoring-settings.html[Monitoring settings in {es}] +For more information, see {ref}/monitoring-settings.html[Monitoring settings in {es}] and {ref}/cluster-update-settings.html[Cluster update settings]. -- . Verify that `monitoring.enabled` and -`monitoring.kibana.collection.enabled` are set to `true` in the -`kibana.yml` file. These are the default values. For +`monitoring.kibana.collection.enabled` are set to `true` in the +`kibana.yml` file. These are the default values. For more information, see <>. . Identify where to send monitoring data. {kib} automatically @@ -72,13 +72,13 @@ in the `kibana.yml` file. This property has a default value of `http://localhost:9200`. + + -- -[TIP] +[TIP] =============================== -In production environments, we strongly recommend using a separate cluster -(referred to as the _monitoring cluster_) to store the data. Using a separate -monitoring cluster prevents production cluster outages from impacting your -ability to access your monitoring data. It also prevents monitoring activities -from impacting the performance of your production cluster. +In production environments, we strongly recommend using a separate cluster +(referred to as the _monitoring cluster_) to store the data. Using a separate +monitoring cluster prevents production cluster outages from impacting your +ability to access your monitoring data. It also prevents monitoring activities +from impacting the performance of your production cluster. If {security} is enabled on the production cluster, use an HTTPS URL such as `https://:9200` in this setting. @@ -97,4 +97,4 @@ used when {kib} sends monitoring data to the production cluster. . <>. -. <>. +. <>. diff --git a/docs/user/monitoring/monitoring-metricbeat.asciidoc b/docs/user/monitoring/monitoring-metricbeat.asciidoc index 61aeaf21d3a4b..f2b32ba1de5dd 100644 --- a/docs/user/monitoring/monitoring-metricbeat.asciidoc +++ b/docs/user/monitoring/monitoring-metricbeat.asciidoc @@ -1,19 +1,19 @@ [role="xpack"] [[monitoring-metricbeat]] -=== Collecting {kib} monitoring data with {metricbeat} +=== Collect {kib} monitoring data with {metricbeat} [subs="attributes"] ++++ -Collecting monitoring data with {metricbeat} +Collect monitoring data with {metricbeat} ++++ -In 6.4 and later, you can use {metricbeat} to collect data about {kib} -and ship it to the monitoring cluster, rather than routing it through the -production cluster as described in <>. +In 6.4 and later, you can use {metricbeat} to collect data about {kib} +and ship it to the monitoring cluster, rather than routing it through the +production cluster as described in <>. image::user/monitoring/images/metricbeat.png[Example monitoring architecture] -To learn about monitoring in general, see -{ref}/monitor-elasticsearch-cluster.html[Monitor a cluster]. +To learn about monitoring in general, see +{ref}/monitor-elasticsearch-cluster.html[Monitor a cluster]. //NOTE: The tagged regions are re-used in the Stack Overview. @@ -21,46 +21,46 @@ To learn about monitoring in general, see + -- // tag::disable-kibana-collection[] -Add the following setting in the {kib} configuration file (`kibana.yml`): +Add the following setting in the {kib} configuration file (`kibana.yml`): [source,yaml] ---------------------------------- monitoring.kibana.collection.enabled: false ---------------------------------- -Leave the `monitoring.enabled` set to its default value (`true`). +Leave the `monitoring.enabled` set to its default value (`true`). // end::disable-kibana-collection[] -For more information, see +For more information, see <>. -- . <>. -. Set the `xpack.monitoring.collection.enabled` setting to `true` on +. Set the `xpack.monitoring.collection.enabled` setting to `true` on each node in the production cluster. By default, it is disabled (`false`). + -- -NOTE: You can specify this setting in either the `elasticsearch.yml` on each -node or across the cluster as a dynamic cluster setting. If {es} -{security-features} are enabled, you must have `monitor` cluster privileges to +NOTE: You can specify this setting in either the `elasticsearch.yml` on each +node or across the cluster as a dynamic cluster setting. If {es} +{security-features} are enabled, you must have `monitor` cluster privileges to view the cluster settings and `manage` cluster privileges to change them. -- ** In {kib}: -... Open {kib} in your web browser. +... Open {kib} in your web browser. + -- -If you are running {kib} locally, go to `http://localhost:5601/`. +If you are running {kib} locally, go to `http://localhost:5601/`. -If the Elastic {security-features} are enabled, log in. +If the Elastic {security-features} are enabled, log in. -- ... In the side navigation, click *Stack Monitoring*. If data collection is -disabled, you are prompted to turn it on. +disabled, you are prompted to turn it on. -** From the Console or command line, set `xpack.monitoring.collection.enabled` +** From the Console or command line, set `xpack.monitoring.collection.enabled` to `true` on the production cluster. + + -- @@ -78,7 +78,7 @@ PUT _cluster/settings } ---------------------------------- -For more information, see {ref}/monitoring-settings.html[Monitoring settings in {es}] +For more information, see {ref}/monitoring-settings.html[Monitoring settings in {es}] and {ref}/cluster-update-settings.html[Cluster update settings]. -- @@ -89,7 +89,7 @@ same server as {kib}. + -- // tag::enable-kibana-module[] -For example, to enable the default configuration in the `modules.d` directory, +For example, to enable the default configuration in the `modules.d` directory, run the following command: ["source","sh",subs="attributes,callouts"] @@ -97,9 +97,9 @@ run the following command: metricbeat modules enable kibana-xpack ---------------------------------------------------------------------- -For more information, see -{metricbeat-ref}/configuration-metricbeat.html[Specify which modules to run] and -{metricbeat-ref}/metricbeat-module-kibana.html[{kib} module]. +For more information, see +{metricbeat-ref}/configuration-metricbeat.html[Specify which modules to run] and +{metricbeat-ref}/metricbeat-module-kibana.html[{kib} module]. // end::enable-kibana-module[] -- @@ -130,15 +130,15 @@ access it via HTTPS. For example, use a `hosts` setting like // end::configure-kibana-module[] // tag::remote-monitoring-user[] -If the Elastic {security-features} are enabled, you must also provide a user -ID and password so that {metricbeat} can collect metrics successfully: +If the Elastic {security-features} are enabled, you must also provide a user +ID and password so that {metricbeat} can collect metrics successfully: -.. Create a user on the production cluster that has the -`remote_monitoring_collector` {ref}/built-in-roles.html[built-in role]. -Alternatively, use the `remote_monitoring_user` +.. Create a user on the production cluster that has the +`remote_monitoring_collector` {ref}/built-in-roles.html[built-in role]. +Alternatively, use the `remote_monitoring_user` {ref}/built-in-users.html[built-in user]. -.. Add the `username` and `password` settings to the {kib} module configuration +.. Add the `username` and `password` settings to the {kib} module configuration file. // end::remote-monitoring-user[] -- @@ -156,19 +156,19 @@ the following command: ---------------------------------------------------------------------- metricbeat modules disable system ---------------------------------------------------------------------- -// end::disable-system-module[] +// end::disable-system-module[] -- . Identify where to send the monitoring data. + + -- -TIP: In production environments, we strongly recommend using a separate cluster -(referred to as the _monitoring cluster_) to store the data. Using a separate -monitoring cluster prevents production cluster outages from impacting your -ability to access your monitoring data. It also prevents monitoring activities +TIP: In production environments, we strongly recommend using a separate cluster +(referred to as the _monitoring cluster_) to store the data. Using a separate +monitoring cluster prevents production cluster outages from impacting your +ability to access your monitoring data. It also prevents monitoring activities from impacting the performance of your production cluster. -For example, specify the {es} output information in the {metricbeat} +For example, specify the {es} output information in the {metricbeat} configuration file (`metricbeat.yml`): [source,yaml] @@ -176,13 +176,13 @@ configuration file (`metricbeat.yml`): output.elasticsearch: # Array of hosts to connect to. hosts: ["http://es-mon-1:9200", "http://es-mon2:9200"] <1> - + # Optional protocol and basic auth credentials. #protocol: "https" #username: "elastic" #password: "changeme" ---------------------------------- -<1> In this example, the data is stored on a monitoring cluster with nodes +<1> In this example, the data is stored on a monitoring cluster with nodes `es-mon-1` and `es-mon-2`. If you configured the monitoring cluster to use encrypted communications, you @@ -192,22 +192,22 @@ must access it via HTTPS. For example, use a `hosts` setting like IMPORTANT: The {es} {monitor-features} use ingest pipelines, therefore the cluster that stores the monitoring data must have at least one ingest node. -If the {es} {security-features} are enabled on the monitoring cluster, you -must provide a valid user ID and password so that {metricbeat} can send metrics -successfully: +If the {es} {security-features} are enabled on the monitoring cluster, you +must provide a valid user ID and password so that {metricbeat} can send metrics +successfully: -.. Create a user on the monitoring cluster that has the -`remote_monitoring_agent` {ref}/built-in-roles.html[built-in role]. -Alternatively, use the `remote_monitoring_user` +.. Create a user on the monitoring cluster that has the +`remote_monitoring_agent` {ref}/built-in-roles.html[built-in role]. +Alternatively, use the `remote_monitoring_user` {ref}/built-in-users.html[built-in user]. -.. Add the `username` and `password` settings to the {es} output information in +.. Add the `username` and `password` settings to the {es} output information in the {metricbeat} configuration file. -For more information about these configuration options, see +For more information about these configuration options, see {metricbeat-ref}/elasticsearch-output.html[Configure the {es} output]. -- -. {metricbeat-ref}/metricbeat-starting.html[Start {metricbeat}]. +. {metricbeat-ref}/metricbeat-starting.html[Start {metricbeat}]. -. <>. +. <>. diff --git a/docs/user/monitoring/viewing-metrics.asciidoc b/docs/user/monitoring/viewing-metrics.asciidoc index 0a5535e6e1a91..48dd2be9ee6a2 100644 --- a/docs/user/monitoring/viewing-metrics.asciidoc +++ b/docs/user/monitoring/viewing-metrics.asciidoc @@ -1,96 +1,96 @@ [role="xpack"] [[monitoring-data]] -=== Viewing monitoring data in {kib} +=== View monitoring data in {kib} ++++ -Viewing monitoring data +View monitoring data ++++ -After you collect monitoring data for one or more products in the {stack}, you -can configure {kib} to retrieve that information and display it in on the +After you collect monitoring data for one or more products in the {stack}, you +can configure {kib} to retrieve that information and display it in on the *Stack Monitoring* page. At a minimum, you must have monitoring data for the {es} production cluster. Once that data exists, {kib} can display monitoring data for other products in the cluster. -. Identify where to retrieve monitoring data from. +. Identify where to retrieve monitoring data from. + -- -The cluster that contains the monitoring data is referred to -as the _monitoring cluster_. +The cluster that contains the monitoring data is referred to +as the _monitoring cluster_. -TIP: If the monitoring data is stored on a *dedicated* monitoring cluster, it is -accessible even when the cluster you're monitoring is not. If you have at least -a gold license, you can send data from multiple clusters to the same monitoring -cluster and view them all through the same instance of {kib}. +TIP: If the monitoring data is stored on a *dedicated* monitoring cluster, it is +accessible even when the cluster you're monitoring is not. If you have at least +a gold license, you can send data from multiple clusters to the same monitoring +cluster and view them all through the same instance of {kib}. -By default, data is retrieved from the cluster specified in the +By default, data is retrieved from the cluster specified in the `elasticsearch.hosts` value in the `kibana.yml` file. If you want to retrieve it from a different cluster, set `monitoring.ui.elasticsearch.hosts`. -To learn more about typical monitoring architectures, -see {ref}/how-monitoring-works.html[How monitoring works] and +To learn more about typical monitoring architectures, +see {ref}/how-monitoring-works.html[How monitoring works] and {ref}/monitoring-production.html[Monitoring in a production environment]. -- . Verify that `monitoring.ui.enabled` is set to `true`, which is the -default value, in the `kibana.yml` file. For more information, see +default value, in the `kibana.yml` file. For more information, see <>. -. If the Elastic {security-features} are enabled on the monitoring cluster, you -must provide a user ID and password so {kib} can retrieve the data. +. If the Elastic {security-features} are enabled on the monitoring cluster, you +must provide a user ID and password so {kib} can retrieve the data. -.. Create a user that has the `monitoring_user` +.. Create a user that has the `monitoring_user` {ref}/built-in-roles.html[built-in role] on the monitoring cluster. -.. Add the `monitoring.ui.elasticsearch.username` and +.. Add the `monitoring.ui.elasticsearch.username` and `monitoring.ui.elasticsearch.password` settings in the `kibana.yml` file. If these settings are omitted, {kib} uses the `elasticsearch.username` and -`elasticsearch.password` setting values. For more +`elasticsearch.password` setting values. For more information, see {kibana-ref}/using-kibana-with-security.html[Configuring security in {kib}]. -. (Optional) Configure {kib} to encrypt communications between the {kib} server -and the monitoring cluster. See <>. +. (Optional) Configure {kib} to encrypt communications between the {kib} server +and the monitoring cluster. See <>. -. If the Elastic {security-features} are enabled on the {kib} server, only users -that have the authority to access {kib} indices and to read the monitoring indices -can use the monitoring dashboards. +. If the Elastic {security-features} are enabled on the {kib} server, only users +that have the authority to access {kib} indices and to read the monitoring indices +can use the monitoring dashboards. + -- -NOTE: These users must exist on the monitoring cluster. If you are accessing a -remote monitoring cluster, you must use credentials that are valid on both the +NOTE: These users must exist on the monitoring cluster. If you are accessing a +remote monitoring cluster, you must use credentials that are valid on both the {kib} server and the monitoring cluster. -- -.. Create users that have the `monitoring_user` and `kibana_admin` +.. Create users that have the `monitoring_user` and `kibana_admin` {ref}/built-in-roles.html[built-in roles]. -. Open {kib} in your web browser. +. Open {kib} in your web browser. + -- -By default, if you are running {kib} locally, go to `http://localhost:5601/`. +By default, if you are running {kib} locally, go to `http://localhost:5601/`. -If the Elastic {security-features} are enabled, log in. +If the Elastic {security-features} are enabled, log in. -- -. In the side navigation, click *Stack Monitoring*. +. In the side navigation, click *Stack Monitoring*. + -- -If data collection is disabled, you are prompted to turn on data collection. -If {es} {security-features} are enabled, you must have `manage` cluster -privileges to turn on data collection. +If data collection is disabled, you are prompted to turn on data collection. +If {es} {security-features} are enabled, you must have `manage` cluster +privileges to turn on data collection. -NOTE: If you are using a separate monitoring cluster, you do not need to turn on -data collection. The dashboards appear when there is data in the monitoring -cluster. +NOTE: If you are using a separate monitoring cluster, you do not need to turn on +data collection. The dashboards appear when there is data in the monitoring +cluster. -- You'll see cluster alerts that require your attention and a summary of the available monitoring metrics for {es}, Logstash, {kib}, and Beats. To view additional information, click the -Overview, Nodes, Indices, or Instances links. See <>. +Overview, Nodes, Indices, or Instances links. See <>. [role="screenshot"] image::images/monitoring-dashboard.png[Monitoring dashboard] diff --git a/docs/user/security/securing-communications/index.asciidoc b/docs/user/security/securing-communications/index.asciidoc index 3bdc59b90b3fd..0509c6b13d54a 100644 --- a/docs/user/security/securing-communications/index.asciidoc +++ b/docs/user/security/securing-communications/index.asciidoc @@ -1,7 +1,7 @@ [[configuring-tls]] -=== Encrypting communications in {kib} +=== Encrypt communications in {kib} ++++ -Encrypting communications +Encrypt communications ++++ Secure Sockets Layer (SSL) and Transport Layer Security (TLS) provide encryption for data-in-transit. While these terms are often used @@ -14,7 +14,7 @@ contains a public key and has an associated -- but separate -- private key; thes supports certificates and private keys in PEM or PKCS#12 format. [[configuring-tls-browser-kib]] -==== Encrypting traffic between the browser and {kib} +==== Encrypt traffic between the browser and {kib} NOTE: You do not need to enable the {es} {security-features} for this type of encryption. @@ -106,7 +106,7 @@ server.ssl.enabled: true After making these changes, you must always access {kib} via HTTPS. For example, https://.com. [[configuring-tls-kib-es]] -==== Encrypting traffic between {kib} and {es} +==== Encrypt traffic between {kib} and {es} NOTE: To perform this step, you must {ref}/configuring-security.html[enable the {es} {security-features}] or you must have a proxy that provides an HTTPS endpoint for {es}. diff --git a/docs/user/security/securing-kibana.asciidoc b/docs/user/security/securing-kibana.asciidoc index f4178bacb111e..33c81961fcd7b 100644 --- a/docs/user/security/securing-kibana.asciidoc +++ b/docs/user/security/securing-kibana.asciidoc @@ -1,8 +1,8 @@ [role="xpack"] [[using-kibana-with-security]] -== Configuring security in {kib} +== Configure security in {kib} ++++ -Configuring security +Configure security ++++ {kib} users have to log in when {security} is enabled on your cluster. You diff --git a/docs/user/setup.asciidoc b/docs/user/setup.asciidoc index 53e2de66c5287..31e7d157d1bc7 100644 --- a/docs/user/setup.asciidoc +++ b/docs/user/setup.asciidoc @@ -1,5 +1,5 @@ [[setup]] -= Set Up Kibana += Set up Kibana [partintro] -- @@ -48,11 +48,9 @@ the patch version. include::{kib-repo-dir}/setup/install.asciidoc[] -include::{kib-repo-dir}/setup/start-stop.asciidoc[] - include::{kib-repo-dir}/setup/settings.asciidoc[] -include::{kib-repo-dir}/setup/docker.asciidoc[] +include::{kib-repo-dir}/setup/start-stop.asciidoc[] include::{kib-repo-dir}/setup/access.asciidoc[] diff --git a/package.json b/package.json index 9423ee31c8bbe..419edcf268356 100644 --- a/package.json +++ b/package.json @@ -127,7 +127,7 @@ "@elastic/charts": "19.2.0", "@elastic/datemath": "5.0.3", "@elastic/ems-client": "7.8.0", - "@elastic/eui": "23.3.1", + "@elastic/eui": "24.1.0", "@elastic/filesaver": "1.1.2", "@elastic/good": "8.1.1-kibana2", "@elastic/numeral": "^2.5.0", @@ -298,7 +298,7 @@ "@elastic/eslint-config-kibana": "0.15.0", "@elastic/eslint-plugin-eui": "0.0.2", "@elastic/github-checks-reporter": "0.0.20b3", - "@elastic/makelogs": "^5.0.1", + "@elastic/makelogs": "^6.0.0", "@kbn/dev-utils": "1.0.0", "@kbn/es": "1.0.0", "@kbn/eslint-import-resolver-kibana": "2.0.0", diff --git a/packages/kbn-dev-utils/src/tooling_log/index.ts b/packages/kbn-dev-utils/src/tooling_log/index.ts index f8009a255f010..acf944f23a816 100644 --- a/packages/kbn-dev-utils/src/tooling_log/index.ts +++ b/packages/kbn-dev-utils/src/tooling_log/index.ts @@ -19,5 +19,5 @@ export { ToolingLog } from './tooling_log'; export { ToolingLogTextWriter, ToolingLogTextWriterConfig } from './tooling_log_text_writer'; -export { pickLevelFromFlags, parseLogLevel, LogLevel } from './log_levels'; +export { pickLevelFromFlags, parseLogLevel, LogLevel, ParsedLogLevel } from './log_levels'; export { ToolingLogCollectingWriter } from './tooling_log_collecting_writer'; diff --git a/packages/kbn-dev-utils/src/tooling_log/tooling_log_collecting_writer.ts b/packages/kbn-dev-utils/src/tooling_log/tooling_log_collecting_writer.ts index 7e79077032156..fd59ebe5c46dc 100644 --- a/packages/kbn-dev-utils/src/tooling_log/tooling_log_collecting_writer.ts +++ b/packages/kbn-dev-utils/src/tooling_log/tooling_log_collecting_writer.ts @@ -18,13 +18,14 @@ */ import { ToolingLogTextWriter } from './tooling_log_text_writer'; +import { LogLevel } from './log_levels'; export class ToolingLogCollectingWriter extends ToolingLogTextWriter { messages: string[] = []; - constructor() { + constructor(level: LogLevel = 'verbose') { super({ - level: 'verbose', + level, writeTo: { write: (msg) => { // trim trailing new line diff --git a/packages/kbn-dev-utils/src/tooling_log/tooling_log_text_writer.ts b/packages/kbn-dev-utils/src/tooling_log/tooling_log_text_writer.ts index b8c12433a0ebb..28ccc60428ae3 100644 --- a/packages/kbn-dev-utils/src/tooling_log/tooling_log_text_writer.ts +++ b/packages/kbn-dev-utils/src/tooling_log/tooling_log_text_writer.ts @@ -47,7 +47,7 @@ export interface ToolingLogTextWriterConfig { function shouldWriteType(level: ParsedLogLevel, type: MessageTypes) { if (type === 'write') { - return true; + return level.name !== 'silent'; } return Boolean(level.flags[type === 'success' ? 'info' : type]); diff --git a/packages/kbn-pm/dist/index.js b/packages/kbn-pm/dist/index.js index 7b233ef010653..ef2b7e7c06a25 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__(705); +/* harmony import */ var _production__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(697); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "buildProductionProjects", function() { return _production__WEBPACK_IMPORTED_MODULE_1__["buildProductionProjects"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "prepareExternalProjectDependencies", function() { return _production__WEBPACK_IMPORTED_MODULE_1__["prepareExternalProjectDependencies"]; }); @@ -105,10 +105,10 @@ __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_project__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(517); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Project", function() { return _utils_project__WEBPACK_IMPORTED_MODULE_3__["Project"]; }); -/* harmony import */ var _utils_workspaces__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(578); +/* harmony import */ var _utils_workspaces__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(573); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "copyWorkspacePackages", function() { return _utils_workspaces__WEBPACK_IMPORTED_MODULE_4__["copyWorkspacePackages"]; }); -/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(579); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(574); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getProjectPaths", function() { return _config__WEBPACK_IMPORTED_MODULE_5__["getProjectPaths"]; }); /* @@ -143,17 +143,17 @@ __webpack_require__.r(__webpack_exports__); "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "run", function() { return run; }); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(chalk__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var dedent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(14); -/* harmony import */ var dedent__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(dedent__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var getopts__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(15); -/* harmony import */ var getopts__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(getopts__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(16); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var _commands__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(17); +/* harmony import */ var dedent__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); +/* harmony import */ var dedent__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(dedent__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var getopts__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); +/* harmony import */ var getopts__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(getopts__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 _kbn_dev_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5); +/* harmony import */ var _kbn_dev_utils__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_kbn_dev_utils__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _commands__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(488); /* harmony import */ var _run__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(689); -/* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(34); +/* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(500); /* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with @@ -181,37 +181,43 @@ __webpack_require__.r(__webpack_exports__); function help() { - const availableCommands = Object.keys(_commands__WEBPACK_IMPORTED_MODULE_4__["commands"]).map(commandName => _commands__WEBPACK_IMPORTED_MODULE_4__["commands"][commandName]).map(command => `${command.name} - ${command.description}`); - _utils_log__WEBPACK_IMPORTED_MODULE_6__["log"].write(dedent__WEBPACK_IMPORTED_MODULE_1___default.a` - usage: kbn [] + _utils_log__WEBPACK_IMPORTED_MODULE_6__["log"].info(dedent__WEBPACK_IMPORTED_MODULE_0___default.a` + usage: kbn [] - By default commands are run for Kibana itself, all packages in the 'packages/' - folder and for all plugins in './plugins' and '../kibana-extra'. + By default commands are run for Kibana itself, all packages in the 'packages/' + folder and for all plugins in './plugins' and '../kibana-extra'. - Available commands: + Available commands: - ${availableCommands.join('\n ')} + ${Object.values(_commands__WEBPACK_IMPORTED_MODULE_4__["commands"]).map(command => `${command.name} - ${command.description}`).join('\n ')} - Global options: + Global options: - -e, --exclude Exclude specified project. Can be specified multiple times to exclude multiple projects, e.g. '-e kibana -e @kbn/pm'. - -i, --include Include only specified projects. If left unspecified, it defaults to including all projects. - --oss Do not include the x-pack when running command. - --skip-kibana-plugins Filter all plugins in ./plugins and ../kibana-extra when running command. - --no-cache Disable the bootstrap cache - `); + -e, --exclude Exclude specified project. Can be specified multiple times to exclude multiple projects, e.g. '-e kibana -e @kbn/pm'. + -i, --include Include only specified projects. If left unspecified, it defaults to including all projects. + --oss Do not include the x-pack when running command. + --skip-kibana-plugins Filter all plugins in ./plugins and ../kibana-extra when running command. + --no-cache Disable the bootstrap cache + --verbose Set log level to verbose + --debug Set log level to debug + --quiet Set log level to error + --silent Disable log output + ` + '\n'); } async function run(argv) { - // We can simplify this setup (and remove this extra handling) once Yarn + _utils_log__WEBPACK_IMPORTED_MODULE_6__["log"].setLogLevel(Object(_kbn_dev_utils__WEBPACK_IMPORTED_MODULE_3__["pickLevelFromFlags"])(getopts__WEBPACK_IMPORTED_MODULE_1___default()(argv, { + boolean: ['verbose', 'debug', 'quiet', 'silent'] + }))); // We can simplify this setup (and remove this extra handling) once Yarn // starts forwarding the `--` directly to this script, see // https://github.com/yarnpkg/yarn/blob/b2d3e1a8fe45ef376b716d597cc79b38702a9320/src/cli/index.js#L174-L182 + if (argv.includes('--')) { - _utils_log__WEBPACK_IMPORTED_MODULE_6__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.red(`Using "--" is not allowed, as it doesn't work with 'yarn kbn'.`)); + _utils_log__WEBPACK_IMPORTED_MODULE_6__["log"].error(`Using "--" is not allowed, as it doesn't work with 'yarn kbn'.`); process.exit(1); } - const options = getopts__WEBPACK_IMPORTED_MODULE_2___default()(argv, { + const options = getopts__WEBPACK_IMPORTED_MODULE_1___default()(argv, { alias: { e: 'exclude', h: 'help', @@ -231,7 +237,7 @@ async function run(argv) { // built version of this tool. - const rootPath = Object(path__WEBPACK_IMPORTED_MODULE_3__["resolve"])(__dirname, '../../../'); + const rootPath = Object(path__WEBPACK_IMPORTED_MODULE_2__["resolve"])(__dirname, '../../../'); const commandName = args[0]; const extraArgs = args.slice(1); const commandOptions = { @@ -242,7 +248,7 @@ async function run(argv) { const command = _commands__WEBPACK_IMPORTED_MODULE_4__["commands"][commandName]; if (command === undefined) { - _utils_log__WEBPACK_IMPORTED_MODULE_6__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.red(`[${commandName}] is not a valid command, see 'kbn --help'`)); + _utils_log__WEBPACK_IMPORTED_MODULE_6__["log"].error(`[${commandName}] is not a valid command, see 'kbn --help'`); process.exit(1); } @@ -255,9872 +261,11181 @@ async function run(argv) { "use strict"; -const escapeStringRegexp = __webpack_require__(3); -const ansiStyles = __webpack_require__(4); -const stdoutColor = __webpack_require__(10).stdout; - -const template = __webpack_require__(13); - -const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); - -// `supportsColor.level` → `ansiStyles.color[name]` mapping -const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; - -// `color-convert` models to exclude from the Chalk API due to conflicts and such -const skipModels = new Set(['gray']); -const styles = Object.create(null); +function dedent(strings) { -function applyOptions(obj, options) { - options = options || {}; + var raw = void 0; + if (typeof strings === "string") { + // dedent can be used as a plain function + raw = [strings]; + } else { + raw = strings.raw; + } - // Detect level if not set manually - const scLevel = stdoutColor ? stdoutColor.level : 0; - obj.level = options.level === undefined ? scLevel : options.level; - obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; -} + // first, perform interpolation + var result = ""; + for (var i = 0; i < raw.length; i++) { + result += raw[i]. + // join lines when there is a suppressed newline + replace(/\\\n[ \t]*/g, ""). -function Chalk(options) { - // We check for this.template here since calling `chalk.constructor()` - // by itself will have a `this` of a previously constructed chalk object - if (!this || !(this instanceof Chalk) || this.template) { - const chalk = {}; - applyOptions(chalk, options); + // handle escaped backticks + replace(/\\`/g, "`"); - chalk.template = function () { - const args = [].slice.call(arguments); - return chalkTag.apply(null, [chalk.template].concat(args)); - }; + if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) { + result += arguments.length <= i + 1 ? undefined : arguments[i + 1]; + } + } - Object.setPrototypeOf(chalk, Chalk.prototype); - Object.setPrototypeOf(chalk.template, chalk); + // now strip indentation + var lines = result.split("\n"); + var mindent = null; + lines.forEach(function (l) { + var m = l.match(/^(\s+)\S+/); + if (m) { + var indent = m[1].length; + if (!mindent) { + // this is the first indented line + mindent = indent; + } else { + mindent = Math.min(mindent, indent); + } + } + }); - chalk.template.constructor = Chalk; + if (mindent !== null) { + result = lines.map(function (l) { + return l[0] === " " ? l.slice(mindent) : l; + }).join("\n"); + } - return chalk.template; - } + // dedent eats leading and trailing whitespace too + result = result.trim(); - applyOptions(this, options); + // handle escaped newlines at the end to ensure they don't get stripped too + return result.replace(/\\n/g, "\n"); } -// Use bright blue on Windows as the normal blue color is illegible -if (isSimpleWindowsTerm) { - ansiStyles.blue.open = '\u001B[94m'; +if (true) { + module.exports = dedent; } -for (const key of Object.keys(ansiStyles)) { - ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); - - styles[key] = { - get() { - const codes = ansiStyles[key]; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); - } - }; -} -styles.visible = { - get() { - return build.call(this, this._styles || [], true, 'visible'); - } -}; +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { -ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); -for (const model of Object.keys(ansiStyles.color.ansi)) { - if (skipModels.has(model)) { - continue; - } +"use strict"; - styles[model] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles.color.close, - closeRe: ansiStyles.color.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; -} -ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); -for (const model of Object.keys(ansiStyles.bgColor.ansi)) { - if (skipModels.has(model)) { - continue; - } +const EMPTYARR = [] +const SHORTSPLIT = /$|[!-@[-`{-~][\s\S]*/g +const isArray = Array.isArray - const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); - styles[bgModel] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles.bgColor.close, - closeRe: ansiStyles.bgColor.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; +const parseValue = function(any) { + if (any === "") return "" + if (any === "false") return false + const maybe = Number(any) + return maybe * 0 === 0 ? maybe : any } -const proto = Object.defineProperties(() => {}, styles); - -function build(_styles, _empty, key) { - const builder = function () { - return applyStyle.apply(builder, arguments); - }; - - builder._styles = _styles; - builder._empty = _empty; - - const self = this; - - Object.defineProperty(builder, 'level', { - enumerable: true, - get() { - return self.level; - }, - set(level) { - self.level = level; - } - }); +const parseAlias = function(aliases) { + let out = {}, + key, + alias, + prev, + len, + any, + i, + k - Object.defineProperty(builder, 'enabled', { - enumerable: true, - get() { - return self.enabled; - }, - set(enabled) { - self.enabled = enabled; - } - }); + for (key in aliases) { + any = aliases[key] + alias = out[key] = isArray(any) ? any : [any] - // See below for fix regarding invisible grey/dim combination on Windows - builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; + for (i = 0, len = alias.length; i < len; i++) { + prev = out[alias[i]] = [key] - // `__proto__` is used because we must return a function, but there is - // no way to create a function with a different prototype - builder.__proto__ = proto; // eslint-disable-line no-proto + for (k = 0; k < len; k++) { + if (i !== k) prev.push(alias[k]) + } + } + } - return builder; + return out } -function applyStyle() { - // Support varags, but simply cast to string in case there's only one arg - const args = arguments; - const argsLen = args.length; - let str = String(arguments[0]); +const parseDefault = function(aliases, defaults) { + let out = {}, + key, + alias, + value, + len, + i - if (argsLen === 0) { - return ''; - } + for (key in defaults) { + value = defaults[key] + alias = aliases[key] - if (argsLen > 1) { - // Don't slice `arguments`, it prevents V8 optimizations - for (let a = 1; a < argsLen; a++) { - str += ' ' + args[a]; - } - } + out[key] = value - if (!this.enabled || this.level <= 0 || !str) { - return this._empty ? '' : str; - } + if (alias === undefined) { + aliases[key] = EMPTYARR + } else { + for (i = 0, len = alias.length; i < len; i++) { + out[alias[i]] = value + } + } + } - // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, - // see https://github.com/chalk/chalk/issues/58 - // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. - const originalDim = ansiStyles.dim.open; - if (isSimpleWindowsTerm && this.hasGrey) { - ansiStyles.dim.open = ''; - } + return out +} - for (const code of this._styles.slice().reverse()) { - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - str = code.open + str.replace(code.closeRe, code.open) + code.close; +const parseOptions = function(aliases, options, value) { + let out = {}, + key, + alias, + len, + end, + i, + k - // Close the styling before a linebreak and reopen - // after next line to fix a bleed issue on macOS - // https://github.com/chalk/chalk/pull/92 - str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); - } + if (options !== undefined) { + for (i = 0, len = options.length; i < len; i++) { + key = options[i] + alias = aliases[key] - // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue - ansiStyles.dim.open = originalDim; + out[key] = value - return str; + if (alias === undefined) { + aliases[key] = EMPTYARR + } else { + for (k = 0, end = alias.length; k < end; k++) { + out[alias[k]] = value + } + } + } + } + + return out } -function chalkTag(chalk, strings) { - if (!Array.isArray(strings)) { - // If chalk() was called by itself or with a string, - // return the string itself as a string. - return [].slice.call(arguments, 1).join(' '); - } +const write = function(out, key, value, aliases, unknown) { + let i, + prev, + alias = aliases[key], + len = alias === undefined ? -1 : alias.length - const args = [].slice.call(arguments, 2); - const parts = [strings.raw[0]]; + if (len >= 0 || unknown === undefined || unknown(key)) { + prev = out[key] - for (let i = 1; i < strings.length; i++) { - parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); - parts.push(String(strings.raw[i])); - } + if (prev === undefined) { + out[key] = value + } else { + if (isArray(prev)) { + prev.push(value) + } else { + out[key] = [prev, value] + } + } - return template(chalk, parts.join('')); + for (i = 0; i < len; i++) { + out[alias[i]] = out[key] + } + } } -Object.defineProperties(Chalk.prototype, styles); +const getopts = function(argv, opts) { + let unknown = (opts = opts || {}).unknown, + aliases = parseAlias(opts.alias), + strings = parseOptions(aliases, opts.string, ""), + values = parseDefault(aliases, opts.default), + bools = parseOptions(aliases, opts.boolean, false), + stopEarly = opts.stopEarly, + _ = [], + out = { _ }, + i = 0, + k = 0, + len = argv.length, + key, + arg, + end, + match, + value -module.exports = Chalk(); // eslint-disable-line new-cap -module.exports.supportsColor = stdoutColor; -module.exports.default = module.exports; // For TypeScript + for (; i < len; i++) { + arg = argv[i] + if (arg[0] !== "-" || arg === "-") { + if (stopEarly) while (i < len) _.push(argv[i++]) + else _.push(arg) + } else if (arg === "--") { + while (++i < len) _.push(argv[i]) + } else if (arg[1] === "-") { + end = arg.indexOf("=", 2) + if (arg[2] === "n" && arg[3] === "o" && arg[4] === "-") { + key = arg.slice(5, end >= 0 ? end : undefined) + value = false + } else if (end >= 0) { + key = arg.slice(2, end) + value = + bools[key] !== undefined || + (strings[key] === undefined + ? parseValue(arg.slice(end + 1)) + : arg.slice(end + 1)) + } else { + key = arg.slice(2) + value = + bools[key] !== undefined || + (len === i + 1 || argv[i + 1][0] === "-" + ? strings[key] === undefined + ? true + : "" + : strings[key] === undefined + ? parseValue(argv[++i]) + : argv[++i]) + } + write(out, key, value, aliases, unknown) + } else { + SHORTSPLIT.lastIndex = 2 + match = SHORTSPLIT.exec(arg) + end = match.index + value = match[0] -/***/ }), -/* 3 */ -/***/ (function(module, exports, __webpack_require__) { + for (k = 1; k < end; k++) { + write( + out, + (key = arg[k]), + k + 1 < end + ? strings[key] === undefined || + arg.substring(k + 1, (k = end)) + value + : value === "" + ? len === i + 1 || argv[i + 1][0] === "-" + ? strings[key] === undefined || "" + : bools[key] !== undefined || + (strings[key] === undefined ? parseValue(argv[++i]) : argv[++i]) + : bools[key] !== undefined || + (strings[key] === undefined ? parseValue(value) : value), + aliases, + unknown + ) + } + } + } -"use strict"; + for (key in values) if (out[key] === undefined) out[key] = values[key] + for (key in bools) if (out[key] === undefined) out[key] = false + for (key in strings) if (out[key] === undefined) out[key] = "" + return out +} -var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; +module.exports = getopts -module.exports = function (str) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - return str.replace(matchOperatorsRe, '\\$&'); -}; +/***/ }), +/* 4 */ +/***/ (function(module, exports) { +module.exports = require("path"); /***/ }), -/* 4 */ +/* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* WEBPACK VAR INJECTION */(function(module) { -const colorConvert = __webpack_require__(6); - -const wrapAnsi16 = (fn, offset) => function () { - const code = fn.apply(colorConvert, arguments); - return `\u001B[${code + offset}m`; -}; -const wrapAnsi256 = (fn, offset) => function () { - const code = fn.apply(colorConvert, arguments); - return `\u001B[${38 + offset};5;${code}m`; -}; +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = __webpack_require__(6); +var proc_runner_1 = __webpack_require__(7); +exports.withProcRunner = proc_runner_1.withProcRunner; +exports.ProcRunner = proc_runner_1.ProcRunner; +tslib_1.__exportStar(__webpack_require__(400), exports); +var serializers_1 = __webpack_require__(405); +exports.createAbsolutePathSerializer = serializers_1.createAbsolutePathSerializer; +var certs_1 = __webpack_require__(430); +exports.CA_CERT_PATH = certs_1.CA_CERT_PATH; +exports.ES_KEY_PATH = certs_1.ES_KEY_PATH; +exports.ES_CERT_PATH = certs_1.ES_CERT_PATH; +exports.ES_P12_PATH = certs_1.ES_P12_PATH; +exports.ES_P12_PASSWORD = certs_1.ES_P12_PASSWORD; +exports.ES_EMPTYPASSWORD_P12_PATH = certs_1.ES_EMPTYPASSWORD_P12_PATH; +exports.ES_NOPASSWORD_P12_PATH = certs_1.ES_NOPASSWORD_P12_PATH; +exports.KBN_KEY_PATH = certs_1.KBN_KEY_PATH; +exports.KBN_CERT_PATH = certs_1.KBN_CERT_PATH; +exports.KBN_P12_PATH = certs_1.KBN_P12_PATH; +exports.KBN_P12_PASSWORD = certs_1.KBN_P12_PASSWORD; +var run_1 = __webpack_require__(431); +exports.run = run_1.run; +exports.createFailError = run_1.createFailError; +exports.createFlagError = run_1.createFlagError; +exports.combineErrors = run_1.combineErrors; +exports.isFailError = run_1.isFailError; +var repo_root_1 = __webpack_require__(407); +exports.REPO_ROOT = repo_root_1.REPO_ROOT; +var kbn_client_1 = __webpack_require__(436); +exports.KbnClient = kbn_client_1.KbnClient; +tslib_1.__exportStar(__webpack_require__(479), exports); +tslib_1.__exportStar(__webpack_require__(486), exports); -const wrapAnsi16m = (fn, offset) => function () { - const rgb = fn.apply(colorConvert, arguments); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; -}; -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39], +/***/ }), +/* 6 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - // Bright color - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - - // Fix humans - styles.color.grey = styles.color.gray; - - for (const groupName of Object.keys(styles)) { - const group = styles[groupName]; - - for (const styleName of Object.keys(group)) { - const style = group[styleName]; - - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; - - group[styleName] = styles[styleName]; - - codes.set(style[0], style[1]); - } - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - } - - const ansi2ansi = n => n; - const rgb2rgb = (r, g, b) => [r, g, b]; - - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; - - styles.color.ansi = { - ansi: wrapAnsi16(ansi2ansi, 0) - }; - styles.color.ansi256 = { - ansi256: wrapAnsi256(ansi2ansi, 0) - }; - styles.color.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 0) - }; - - styles.bgColor.ansi = { - ansi: wrapAnsi16(ansi2ansi, 10) - }; - styles.bgColor.ansi256 = { - ansi256: wrapAnsi256(ansi2ansi, 10) - }; - styles.bgColor.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 10) - }; - - for (let key of Object.keys(colorConvert)) { - if (typeof colorConvert[key] !== 'object') { - continue; - } - - const suite = colorConvert[key]; - - if (key === 'ansi16') { - key = 'ansi'; - } - - if ('ansi16' in suite) { - styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); - styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); - } - - if ('ansi256' in suite) { - styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); - styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); - } - - if ('rgb' in suite) { - styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); - styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); - } - } - - return styles; -} - -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(5)(module))) - -/***/ }), -/* 5 */ -/***/ (function(module, exports) { - -module.exports = function(module) { - if (!module.webpackPolyfill) { - module.deprecate = function() {}; - module.paths = []; - // module.parent = undefined by default - if (!module.children) module.children = []; - Object.defineProperty(module, "loaded", { - enumerable: true, - get: function() { - return module.l; - } - }); - Object.defineProperty(module, "id", { - enumerable: true, - get: function() { - return module.i; - } - }); - module.webpackPolyfill = 1; - } - return module; -}; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__extends", function() { return __extends; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__assign", function() { return __assign; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__rest", function() { return __rest; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__decorate", function() { return __decorate; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__param", function() { return __param; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__metadata", function() { return __metadata; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__awaiter", function() { return __awaiter; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__generator", function() { return __generator; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__exportStar", function() { return __exportStar; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__values", function() { return __values; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__read", function() { return __read; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spread", function() { return __spread; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__await", function() { return __await; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncGenerator", function() { return __asyncGenerator; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncDelegator", function() { return __asyncDelegator; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncValues", function() { return __asyncValues; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__makeTemplateObject", function() { return __makeTemplateObject; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importStar", function() { return __importStar; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importDefault", function() { return __importDefault; }); +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +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); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var __assign = function() { + __assign = Object.assign || function __assign(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); +} + +function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +} + +function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} + +function __param(paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } +} + +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} + +function __awaiter(thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +function __exportStar(m, exports) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} + +function __values(o) { + var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; + if (m) return m.call(o); + return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; +} + +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; + +function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result.default = mod; + return result; +} + +function __importDefault(mod) { + return (mod && mod.__esModule) ? mod : { default: mod }; +} /***/ }), -/* 6 */ +/* 7 */ /***/ (function(module, exports, __webpack_require__) { -var conversions = __webpack_require__(7); -var route = __webpack_require__(9); - -var convert = {}; - -var models = Object.keys(conversions); - -function wrapRaw(fn) { - var wrappedFn = function (args) { - if (args === undefined || args === null) { - return args; - } - - if (arguments.length > 1) { - args = Array.prototype.slice.call(arguments); - } - - return fn(args); - }; - - // preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; -} - -function wrapRounded(fn) { - var wrappedFn = function (args) { - if (args === undefined || args === null) { - return args; - } - - if (arguments.length > 1) { - args = Array.prototype.slice.call(arguments); - } +"use strict"; - var result = fn(args); +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +var with_proc_runner_1 = __webpack_require__(8); +exports.withProcRunner = with_proc_runner_1.withProcRunner; +var proc_runner_1 = __webpack_require__(9); +exports.ProcRunner = proc_runner_1.ProcRunner; - // we're assuming the result is an array here. - // see notice in conversions.js; don't use box types - // in conversion functions. - if (typeof result === 'object') { - for (var len = result.length, i = 0; i < len; i++) { - result[i] = Math.round(result[i]); - } - } - return result; - }; +/***/ }), +/* 8 */ +/***/ (function(module, exports, __webpack_require__) { - // preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } +"use strict"; - return wrappedFn; +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const proc_runner_1 = __webpack_require__(9); +/** + * Create a ProcRunner and pass it to an async function. When + * the async function finishes the ProcRunner is torn-down + * automatically + * + * @param {ToolingLog} log + * @param {async Function} fn + * @return {Promise} + */ +async function withProcRunner(log, fn) { + const procs = new proc_runner_1.ProcRunner(log); + try { + await fn(procs); + } + finally { + await procs.teardown(); + } } - -models.forEach(function (fromModel) { - convert[fromModel] = {}; - - Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); - Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); - - var routes = route(fromModel); - var routeModels = Object.keys(routes); - - routeModels.forEach(function (toModel) { - var fn = routes[toModel]; - - convert[fromModel][toModel] = wrapRounded(fn); - convert[fromModel][toModel].raw = wrapRaw(fn); - }); -}); - -module.exports = convert; +exports.withProcRunner = withProcRunner; /***/ }), -/* 7 */ +/* 9 */ /***/ (function(module, exports, __webpack_require__) { -/* MIT license */ -var cssKeywords = __webpack_require__(8); - -// NOTE: conversions should only return primitive values (i.e. arrays, or -// values that give correct `typeof` results). -// do not use box values types (i.e. Number(), String(), etc.) - -var reverseKeywords = {}; -for (var key in cssKeywords) { - if (cssKeywords.hasOwnProperty(key)) { - reverseKeywords[cssKeywords[key]] = key; - } -} +"use strict"; -var convert = module.exports = { - rgb: {channels: 3, labels: 'rgb'}, - hsl: {channels: 3, labels: 'hsl'}, - hsv: {channels: 3, labels: 'hsv'}, - hwb: {channels: 3, labels: 'hwb'}, - cmyk: {channels: 4, labels: 'cmyk'}, - xyz: {channels: 3, labels: 'xyz'}, - lab: {channels: 3, labels: 'lab'}, - lch: {channels: 3, labels: 'lch'}, - hex: {channels: 1, labels: ['hex']}, - keyword: {channels: 1, labels: ['keyword']}, - ansi16: {channels: 1, labels: ['ansi16']}, - ansi256: {channels: 1, labels: ['ansi256']}, - hcg: {channels: 3, labels: ['h', 'c', 'g']}, - apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, - gray: {channels: 1, labels: ['gray']} -}; - -// hide .channels and .labels properties -for (var model in convert) { - if (convert.hasOwnProperty(model)) { - if (!('channels' in convert[model])) { - throw new Error('missing channels property: ' + model); - } - - if (!('labels' in convert[model])) { - throw new Error('missing channel labels property: ' + model); - } - - if (convert[model].labels.length !== convert[model].channels) { - throw new Error('channel and label counts mismatch: ' + model); - } - - var channels = convert[model].channels; - var labels = convert[model].labels; - delete convert[model].channels; - delete convert[model].labels; - Object.defineProperty(convert[model], 'channels', {value: channels}); - Object.defineProperty(convert[model], 'labels', {value: labels}); - } +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = __webpack_require__(6); +const moment_1 = tslib_1.__importDefault(__webpack_require__(10)); +const Rx = tslib_1.__importStar(__webpack_require__(140)); +const operators_1 = __webpack_require__(241); +const exit_hook_1 = tslib_1.__importDefault(__webpack_require__(339)); +const errors_1 = __webpack_require__(340); +const proc_1 = __webpack_require__(341); +const SECOND = 1000; +const MINUTE = 60 * SECOND; +const noop = () => { }; +/** + * Helper for starting and managing processes. In many ways it resembles the + * API from `grunt_run`, processes are named and can be started, waited for, + * backgrounded once they log something matching a RegExp... + * + * @class ProcRunner + */ +class ProcRunner { + constructor(log) { + this.log = log; + this.closing = false; + this.procs = []; + this.signalUnsubscribe = exit_hook_1.default(() => { + this.teardown().catch((error) => { + log.error(`ProcRunner teardown error: ${error.stack}`); + }); + }); + } + /** + * Start a process, tracking it by `name` + * @param {String} name + * @param {Object} options + * @property {String} options.cmd executable to run + * @property {Array?} options.args arguments to provide the executable + * @property {String?} options.cwd current working directory for the process + * @property {RegExp|Boolean} options.wait Should start() wait for some time? Use + * `true` will wait until the proc exits, + * a `RegExp` will wait until that log line + * is found + * @return {Promise} + */ + async run(name, options) { + const { cmd, args = [], cwd = process.cwd(), stdin = undefined, wait = false, waitTimeout = 15 * MINUTE, env = process.env, } = options; + if (this.closing) { + throw new Error('ProcRunner is closing'); + } + if (wait && !(wait instanceof RegExp) && wait !== true) { + throw new TypeError('wait param should either be a RegExp or `true`'); + } + if (!!this.getProc(name)) { + throw new Error(`Process with name "${name}" already running`); + } + const proc = this.startProc(name, { + cmd, + args, + cwd, + env, + stdin, + }); + try { + if (wait instanceof RegExp) { + // wait for process to log matching line + await Rx.race(proc.lines$.pipe(operators_1.filter((line) => wait.test(line)), operators_1.first(), operators_1.catchError((err) => { + if (err.name !== 'EmptyError') { + throw errors_1.createCliError(`[${name}] exited without matching pattern: ${wait}`); + } + else { + throw err; + } + })), waitTimeout === false + ? Rx.NEVER + : Rx.timer(waitTimeout).pipe(operators_1.map(() => { + const sec = waitTimeout / SECOND; + throw errors_1.createCliError(`[${name}] failed to match pattern within ${sec} seconds [pattern=${wait}]`); + }))).toPromise(); + } + if (wait === true) { + // wait for process to complete + await proc.outcomePromise; + } + } + finally { + // while the procRunner closes promises will resolve/reject because + // processes and stopping, but consumers of run() shouldn't have to + // prepare for that, so just return a never-resolving promise + if (this.closing) { + await new Promise(noop); + } + } + } + /** + * Stop a named proc + */ + async stop(name, signal = 'SIGTERM') { + const proc = this.getProc(name); + if (proc) { + await proc.stop(signal); + } + else { + this.log.warning('[%s] already stopped', name); + } + } + /** + * Wait for all running processes to stop naturally + * @return {Promise} + */ + async waitForAllToStop() { + await Promise.all(this.procs.map((proc) => proc.outcomePromise)); + } + /** + * Close the ProcRunner and stop all running + * processes with `signal` + * + * @param {String} [signal=undefined] + * @return {Promise} + */ + async teardown(signal = 'exit') { + if (this.closing) { + return; + } + this.closing = true; + this.signalUnsubscribe(); + if (!signal && this.procs.length > 0) { + this.log.warning('%d processes left running, stop them with procs.stop(name):', this.procs.length, this.procs.map((proc) => proc.name)); + } + await Promise.all(this.procs.map(async (proc) => { + await proc.stop(signal === 'exit' ? 'SIGKILL' : signal); + })); + } + getProc(name) { + return this.procs.find((proc) => { + return proc.name === name; + }); + } + startProc(name, options) { + const startMs = Date.now(); + const proc = proc_1.startProc(name, options, this.log); + this.procs.push(proc); + const remove = () => { + this.procs.splice(this.procs.indexOf(proc), 1); + }; + // tie into proc outcome$, remove from _procs on compete + proc.outcome$.subscribe({ + next: (code) => { + const duration = moment_1.default.duration(Date.now() - startMs); + this.log.info('[%s] exited with %s after %s', name, code, duration.humanize()); + }, + complete: () => { + remove(); + }, + error: (error) => { + if (this.closing) { + this.log.error(error); + } + remove(); + }, + }); + return proc; + } } +exports.ProcRunner = ProcRunner; -convert.rgb.hsl = function (rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; - var min = Math.min(r, g, b); - var max = Math.max(r, g, b); - var delta = max - min; - var h; - var s; - var l; - - if (max === min) { - h = 0; - } else if (r === max) { - h = (g - b) / delta; - } else if (g === max) { - h = 2 + (b - r) / delta; - } else if (b === max) { - h = 4 + (r - g) / delta; - } - - h = Math.min(h * 60, 360); - - if (h < 0) { - h += 360; - } - l = (min + max) / 2; +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { - if (max === min) { - s = 0; - } else if (l <= 0.5) { - s = delta / (max + min); - } else { - s = delta / (2 - max - min); - } +/* WEBPACK VAR INJECTION */(function(module) {var require;//! moment.js - return [h, s * 100, l * 100]; -}; +;(function (global, factory) { + true ? module.exports = factory() : + undefined +}(this, (function () { 'use strict'; -convert.rgb.hsv = function (rgb) { - var r = rgb[0]; - var g = rgb[1]; - var b = rgb[2]; - var min = Math.min(r, g, b); - var max = Math.max(r, g, b); - var delta = max - min; - var h; - var s; - var v; + var hookCallback; - if (max === 0) { - s = 0; - } else { - s = (delta / max * 1000) / 10; - } + function hooks () { + return hookCallback.apply(null, arguments); + } - if (max === min) { - h = 0; - } else if (r === max) { - h = (g - b) / delta; - } else if (g === max) { - h = 2 + (b - r) / delta; - } else if (b === max) { - h = 4 + (r - g) / delta; - } + // This is done to register the method called with moment() + // without creating circular dependencies. + function setHookCallback (callback) { + hookCallback = callback; + } - h = Math.min(h * 60, 360); + function isArray(input) { + return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]'; + } - if (h < 0) { - h += 360; - } + function isObject(input) { + // IE8 will treat undefined and null as object if it wasn't for + // input != null + return input != null && Object.prototype.toString.call(input) === '[object Object]'; + } - v = ((max / 255) * 1000) / 10; + function isObjectEmpty(obj) { + if (Object.getOwnPropertyNames) { + return (Object.getOwnPropertyNames(obj).length === 0); + } else { + var k; + for (k in obj) { + if (obj.hasOwnProperty(k)) { + return false; + } + } + return true; + } + } - return [h, s, v]; -}; + function isUndefined(input) { + return input === void 0; + } -convert.rgb.hwb = function (rgb) { - var r = rgb[0]; - var g = rgb[1]; - var b = rgb[2]; - var h = convert.rgb.hsl(rgb)[0]; - var w = 1 / 255 * Math.min(r, Math.min(g, b)); + function isNumber(input) { + return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]'; + } - b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + function isDate(input) { + return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]'; + } - return [h, w * 100, b * 100]; -}; + function map(arr, fn) { + var res = [], i; + for (i = 0; i < arr.length; ++i) { + res.push(fn(arr[i], i)); + } + return res; + } -convert.rgb.cmyk = function (rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; - var c; - var m; - var y; - var k; + function hasOwnProp(a, b) { + return Object.prototype.hasOwnProperty.call(a, b); + } - k = Math.min(1 - r, 1 - g, 1 - b); - c = (1 - r - k) / (1 - k) || 0; - m = (1 - g - k) / (1 - k) || 0; - y = (1 - b - k) / (1 - k) || 0; + function extend(a, b) { + for (var i in b) { + if (hasOwnProp(b, i)) { + a[i] = b[i]; + } + } - return [c * 100, m * 100, y * 100, k * 100]; -}; + if (hasOwnProp(b, 'toString')) { + a.toString = b.toString; + } -/** - * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance - * */ -function comparativeDistance(x, y) { - return ( - Math.pow(x[0] - y[0], 2) + - Math.pow(x[1] - y[1], 2) + - Math.pow(x[2] - y[2], 2) - ); -} + if (hasOwnProp(b, 'valueOf')) { + a.valueOf = b.valueOf; + } -convert.rgb.keyword = function (rgb) { - var reversed = reverseKeywords[rgb]; - if (reversed) { - return reversed; - } + return a; + } - var currentClosestDistance = Infinity; - var currentClosestKeyword; + function createUTC (input, format, locale, strict) { + return createLocalOrUTC(input, format, locale, strict, true).utc(); + } - for (var keyword in cssKeywords) { - if (cssKeywords.hasOwnProperty(keyword)) { - var value = cssKeywords[keyword]; + function defaultParsingFlags() { + // We need to deep clone this object. + return { + empty : false, + unusedTokens : [], + unusedInput : [], + overflow : -2, + charsLeftOver : 0, + nullInput : false, + invalidMonth : null, + invalidFormat : false, + userInvalidated : false, + iso : false, + parsedDateParts : [], + meridiem : null, + rfc2822 : false, + weekdayMismatch : false + }; + } - // Compute comparative distance - var distance = comparativeDistance(rgb, value); + function getParsingFlags(m) { + if (m._pf == null) { + m._pf = defaultParsingFlags(); + } + return m._pf; + } - // Check if its less, if so set as closest - if (distance < currentClosestDistance) { - currentClosestDistance = distance; - currentClosestKeyword = keyword; - } - } - } + var some; + if (Array.prototype.some) { + some = Array.prototype.some; + } else { + some = function (fun) { + var t = Object(this); + var len = t.length >>> 0; - return currentClosestKeyword; -}; + for (var i = 0; i < len; i++) { + if (i in t && fun.call(this, t[i], i, t)) { + return true; + } + } -convert.keyword.rgb = function (keyword) { - return cssKeywords[keyword]; -}; + return false; + }; + } -convert.rgb.xyz = function (rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; + function isValid(m) { + if (m._isValid == null) { + var flags = getParsingFlags(m); + var parsedParts = some.call(flags.parsedDateParts, function (i) { + return i != null; + }); + var isNowValid = !isNaN(m._d.getTime()) && + flags.overflow < 0 && + !flags.empty && + !flags.invalidMonth && + !flags.invalidWeekday && + !flags.weekdayMismatch && + !flags.nullInput && + !flags.invalidFormat && + !flags.userInvalidated && + (!flags.meridiem || (flags.meridiem && parsedParts)); - // assume sRGB - r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); - g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); - b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); + if (m._strict) { + isNowValid = isNowValid && + flags.charsLeftOver === 0 && + flags.unusedTokens.length === 0 && + flags.bigHour === undefined; + } - var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); - var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); - var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + if (Object.isFrozen == null || !Object.isFrozen(m)) { + m._isValid = isNowValid; + } + else { + return isNowValid; + } + } + return m._isValid; + } - return [x * 100, y * 100, z * 100]; -}; + function createInvalid (flags) { + var m = createUTC(NaN); + if (flags != null) { + extend(getParsingFlags(m), flags); + } + else { + getParsingFlags(m).userInvalidated = true; + } -convert.rgb.lab = function (rgb) { - var xyz = convert.rgb.xyz(rgb); - var x = xyz[0]; - var y = xyz[1]; - var z = xyz[2]; - var l; - var a; - var b; + return m; + } - x /= 95.047; - y /= 100; - z /= 108.883; + // Plugins that add properties should also add the key here (null value), + // so we can properly clone ourselves. + var momentProperties = hooks.momentProperties = []; - x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + function copyConfig(to, from) { + var i, prop, val; - l = (116 * y) - 16; - a = 500 * (x - y); - b = 200 * (y - z); - - return [l, a, b]; -}; + if (!isUndefined(from._isAMomentObject)) { + to._isAMomentObject = from._isAMomentObject; + } + if (!isUndefined(from._i)) { + to._i = from._i; + } + if (!isUndefined(from._f)) { + to._f = from._f; + } + if (!isUndefined(from._l)) { + to._l = from._l; + } + if (!isUndefined(from._strict)) { + to._strict = from._strict; + } + if (!isUndefined(from._tzm)) { + to._tzm = from._tzm; + } + if (!isUndefined(from._isUTC)) { + to._isUTC = from._isUTC; + } + if (!isUndefined(from._offset)) { + to._offset = from._offset; + } + if (!isUndefined(from._pf)) { + to._pf = getParsingFlags(from); + } + if (!isUndefined(from._locale)) { + to._locale = from._locale; + } -convert.hsl.rgb = function (hsl) { - var h = hsl[0] / 360; - var s = hsl[1] / 100; - var l = hsl[2] / 100; - var t1; - var t2; - var t3; - var rgb; - var val; + if (momentProperties.length > 0) { + for (i = 0; i < momentProperties.length; i++) { + prop = momentProperties[i]; + val = from[prop]; + if (!isUndefined(val)) { + to[prop] = val; + } + } + } - if (s === 0) { - val = l * 255; - return [val, val, val]; - } + return to; + } - if (l < 0.5) { - t2 = l * (1 + s); - } else { - t2 = l + s - l * s; - } + var updateInProgress = false; - t1 = 2 * l - t2; + // Moment prototype object + function Moment(config) { + copyConfig(this, config); + this._d = new Date(config._d != null ? config._d.getTime() : NaN); + if (!this.isValid()) { + this._d = new Date(NaN); + } + // Prevent infinite loop in case updateOffset creates new moment + // objects. + if (updateInProgress === false) { + updateInProgress = true; + hooks.updateOffset(this); + updateInProgress = false; + } + } - rgb = [0, 0, 0]; - for (var i = 0; i < 3; i++) { - t3 = h + 1 / 3 * -(i - 1); - if (t3 < 0) { - t3++; - } - if (t3 > 1) { - t3--; - } + function isMoment (obj) { + return obj instanceof Moment || (obj != null && obj._isAMomentObject != null); + } - if (6 * t3 < 1) { - val = t1 + (t2 - t1) * 6 * t3; - } else if (2 * t3 < 1) { - val = t2; - } else if (3 * t3 < 2) { - val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; - } else { - val = t1; - } + function absFloor (number) { + if (number < 0) { + // -0 -> 0 + return Math.ceil(number) || 0; + } else { + return Math.floor(number); + } + } - rgb[i] = val * 255; - } + function toInt(argumentForCoercion) { + var coercedNumber = +argumentForCoercion, + value = 0; - return rgb; -}; + if (coercedNumber !== 0 && isFinite(coercedNumber)) { + value = absFloor(coercedNumber); + } -convert.hsl.hsv = function (hsl) { - var h = hsl[0]; - var s = hsl[1] / 100; - var l = hsl[2] / 100; - var smin = s; - var lmin = Math.max(l, 0.01); - var sv; - var v; + return value; + } - l *= 2; - s *= (l <= 1) ? l : 2 - l; - smin *= lmin <= 1 ? lmin : 2 - lmin; - v = (l + s) / 2; - sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); + // compare two arrays, return the number of differences + function compareArrays(array1, array2, dontConvert) { + var len = Math.min(array1.length, array2.length), + lengthDiff = Math.abs(array1.length - array2.length), + diffs = 0, + i; + for (i = 0; i < len; i++) { + if ((dontConvert && array1[i] !== array2[i]) || + (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { + diffs++; + } + } + return diffs + lengthDiff; + } - return [h, sv * 100, v * 100]; -}; + function warn(msg) { + if (hooks.suppressDeprecationWarnings === false && + (typeof console !== 'undefined') && console.warn) { + console.warn('Deprecation warning: ' + msg); + } + } -convert.hsv.rgb = function (hsv) { - var h = hsv[0] / 60; - var s = hsv[1] / 100; - var v = hsv[2] / 100; - var hi = Math.floor(h) % 6; + function deprecate(msg, fn) { + var firstTime = true; - var f = h - Math.floor(h); - var p = 255 * v * (1 - s); - var q = 255 * v * (1 - (s * f)); - var t = 255 * v * (1 - (s * (1 - f))); - v *= 255; + return extend(function () { + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(null, msg); + } + if (firstTime) { + var args = []; + var arg; + for (var i = 0; i < arguments.length; i++) { + arg = ''; + if (typeof arguments[i] === 'object') { + arg += '\n[' + i + '] '; + for (var key in arguments[0]) { + arg += key + ': ' + arguments[0][key] + ', '; + } + arg = arg.slice(0, -2); // Remove trailing comma and space + } else { + arg = arguments[i]; + } + args.push(arg); + } + warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack); + firstTime = false; + } + return fn.apply(this, arguments); + }, fn); + } - switch (hi) { - case 0: - return [v, t, p]; - case 1: - return [q, v, p]; - case 2: - return [p, v, t]; - case 3: - return [p, q, v]; - case 4: - return [t, p, v]; - case 5: - return [v, p, q]; - } -}; + var deprecations = {}; -convert.hsv.hsl = function (hsv) { - var h = hsv[0]; - var s = hsv[1] / 100; - var v = hsv[2] / 100; - var vmin = Math.max(v, 0.01); - var lmin; - var sl; - var l; + function deprecateSimple(name, msg) { + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(name, msg); + } + if (!deprecations[name]) { + warn(msg); + deprecations[name] = true; + } + } - l = (2 - s) * v; - lmin = (2 - s) * vmin; - sl = s * vmin; - sl /= (lmin <= 1) ? lmin : 2 - lmin; - sl = sl || 0; - l /= 2; + hooks.suppressDeprecationWarnings = false; + hooks.deprecationHandler = null; - return [h, sl * 100, l * 100]; -}; + function isFunction(input) { + return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]'; + } -// http://dev.w3.org/csswg/css-color/#hwb-to-rgb -convert.hwb.rgb = function (hwb) { - var h = hwb[0] / 360; - var wh = hwb[1] / 100; - var bl = hwb[2] / 100; - var ratio = wh + bl; - var i; - var v; - var f; - var n; + function set (config) { + var prop, i; + for (i in config) { + prop = config[i]; + if (isFunction(prop)) { + this[i] = prop; + } else { + this['_' + i] = prop; + } + } + this._config = config; + // Lenient ordinal parsing accepts just a number in addition to + // number + (possibly) stuff coming from _dayOfMonthOrdinalParse. + // TODO: Remove "ordinalParse" fallback in next major release. + this._dayOfMonthOrdinalParseLenient = new RegExp( + (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + + '|' + (/\d{1,2}/).source); + } - // wh + bl cant be > 1 - if (ratio > 1) { - wh /= ratio; - bl /= ratio; - } + function mergeConfigs(parentConfig, childConfig) { + var res = extend({}, parentConfig), prop; + for (prop in childConfig) { + if (hasOwnProp(childConfig, prop)) { + if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) { + res[prop] = {}; + extend(res[prop], parentConfig[prop]); + extend(res[prop], childConfig[prop]); + } else if (childConfig[prop] != null) { + res[prop] = childConfig[prop]; + } else { + delete res[prop]; + } + } + } + for (prop in parentConfig) { + if (hasOwnProp(parentConfig, prop) && + !hasOwnProp(childConfig, prop) && + isObject(parentConfig[prop])) { + // make sure changes to properties don't modify parent config + res[prop] = extend({}, res[prop]); + } + } + return res; + } - i = Math.floor(6 * h); - v = 1 - bl; - f = 6 * h - i; + function Locale(config) { + if (config != null) { + this.set(config); + } + } - if ((i & 0x01) !== 0) { - f = 1 - f; - } + var keys; - n = wh + f * (v - wh); // linear interpolation + if (Object.keys) { + keys = Object.keys; + } else { + keys = function (obj) { + var i, res = []; + for (i in obj) { + if (hasOwnProp(obj, i)) { + res.push(i); + } + } + return res; + }; + } - var r; - var g; - var b; - switch (i) { - default: - case 6: - case 0: r = v; g = n; b = wh; break; - case 1: r = n; g = v; b = wh; break; - case 2: r = wh; g = v; b = n; break; - case 3: r = wh; g = n; b = v; break; - case 4: r = n; g = wh; b = v; break; - case 5: r = v; g = wh; b = n; break; - } + var defaultCalendar = { + sameDay : '[Today at] LT', + nextDay : '[Tomorrow at] LT', + nextWeek : 'dddd [at] LT', + lastDay : '[Yesterday at] LT', + lastWeek : '[Last] dddd [at] LT', + sameElse : 'L' + }; - return [r * 255, g * 255, b * 255]; -}; + function calendar (key, mom, now) { + var output = this._calendar[key] || this._calendar['sameElse']; + return isFunction(output) ? output.call(mom, now) : output; + } -convert.cmyk.rgb = function (cmyk) { - var c = cmyk[0] / 100; - var m = cmyk[1] / 100; - var y = cmyk[2] / 100; - var k = cmyk[3] / 100; - var r; - var g; - var b; + var defaultLongDateFormat = { + LTS : 'h:mm:ss A', + LT : 'h:mm A', + L : 'MM/DD/YYYY', + LL : 'MMMM D, YYYY', + LLL : 'MMMM D, YYYY h:mm A', + LLLL : 'dddd, MMMM D, YYYY h:mm A' + }; - r = 1 - Math.min(1, c * (1 - k) + k); - g = 1 - Math.min(1, m * (1 - k) + k); - b = 1 - Math.min(1, y * (1 - k) + k); + function longDateFormat (key) { + var format = this._longDateFormat[key], + formatUpper = this._longDateFormat[key.toUpperCase()]; - return [r * 255, g * 255, b * 255]; -}; + if (format || !formatUpper) { + return format; + } -convert.xyz.rgb = function (xyz) { - var x = xyz[0] / 100; - var y = xyz[1] / 100; - var z = xyz[2] / 100; - var r; - var g; - var b; + this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) { + return val.slice(1); + }); - r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); - g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); - b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + return this._longDateFormat[key]; + } - // assume sRGB - r = r > 0.0031308 - ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) - : r * 12.92; + var defaultInvalidDate = 'Invalid date'; - g = g > 0.0031308 - ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) - : g * 12.92; + function invalidDate () { + return this._invalidDate; + } - b = b > 0.0031308 - ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) - : b * 12.92; + var defaultOrdinal = '%d'; + var defaultDayOfMonthOrdinalParse = /\d{1,2}/; - r = Math.min(Math.max(0, r), 1); - g = Math.min(Math.max(0, g), 1); - b = Math.min(Math.max(0, b), 1); + function ordinal (number) { + return this._ordinal.replace('%d', number); + } - return [r * 255, g * 255, b * 255]; -}; + var defaultRelativeTime = { + future : 'in %s', + past : '%s ago', + s : 'a few seconds', + ss : '%d seconds', + m : 'a minute', + mm : '%d minutes', + h : 'an hour', + hh : '%d hours', + d : 'a day', + dd : '%d days', + M : 'a month', + MM : '%d months', + y : 'a year', + yy : '%d years' + }; -convert.xyz.lab = function (xyz) { - var x = xyz[0]; - var y = xyz[1]; - var z = xyz[2]; - var l; - var a; - var b; + function relativeTime (number, withoutSuffix, string, isFuture) { + var output = this._relativeTime[string]; + return (isFunction(output)) ? + output(number, withoutSuffix, string, isFuture) : + output.replace(/%d/i, number); + } - x /= 95.047; - y /= 100; - z /= 108.883; + function pastFuture (diff, output) { + var format = this._relativeTime[diff > 0 ? 'future' : 'past']; + return isFunction(format) ? format(output) : format.replace(/%s/i, output); + } - x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + var aliases = {}; - l = (116 * y) - 16; - a = 500 * (x - y); - b = 200 * (y - z); + function addUnitAlias (unit, shorthand) { + var lowerCase = unit.toLowerCase(); + aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; + } - return [l, a, b]; -}; + function normalizeUnits(units) { + return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined; + } -convert.lab.xyz = function (lab) { - var l = lab[0]; - var a = lab[1]; - var b = lab[2]; - var x; - var y; - var z; + function normalizeObjectUnits(inputObject) { + var normalizedInput = {}, + normalizedProp, + prop; - y = (l + 16) / 116; - x = a / 500 + y; - z = y - b / 200; + for (prop in inputObject) { + if (hasOwnProp(inputObject, prop)) { + normalizedProp = normalizeUnits(prop); + if (normalizedProp) { + normalizedInput[normalizedProp] = inputObject[prop]; + } + } + } - var y2 = Math.pow(y, 3); - var x2 = Math.pow(x, 3); - var z2 = Math.pow(z, 3); - y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; - x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; - z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + return normalizedInput; + } - x *= 95.047; - y *= 100; - z *= 108.883; + var priorities = {}; - return [x, y, z]; -}; + function addUnitPriority(unit, priority) { + priorities[unit] = priority; + } -convert.lab.lch = function (lab) { - var l = lab[0]; - var a = lab[1]; - var b = lab[2]; - var hr; - var h; - var c; - - hr = Math.atan2(b, a); - h = hr * 360 / 2 / Math.PI; + function getPrioritizedUnits(unitsObj) { + var units = []; + for (var u in unitsObj) { + units.push({unit: u, priority: priorities[u]}); + } + units.sort(function (a, b) { + return a.priority - b.priority; + }); + return units; + } - if (h < 0) { - h += 360; - } + function zeroFill(number, targetLength, forceSign) { + var absNumber = '' + Math.abs(number), + zerosToFill = targetLength - absNumber.length, + sign = number >= 0; + return (sign ? (forceSign ? '+' : '') : '-') + + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber; + } - c = Math.sqrt(a * a + b * b); + var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g; - return [l, c, h]; -}; + var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; -convert.lch.lab = function (lch) { - var l = lch[0]; - var c = lch[1]; - var h = lch[2]; - var a; - var b; - var hr; + var formatFunctions = {}; - hr = h / 360 * 2 * Math.PI; - a = c * Math.cos(hr); - b = c * Math.sin(hr); + var formatTokenFunctions = {}; - return [l, a, b]; -}; + // token: 'M' + // padded: ['MM', 2] + // ordinal: 'Mo' + // callback: function () { this.month() + 1 } + function addFormatToken (token, padded, ordinal, callback) { + var func = callback; + if (typeof callback === 'string') { + func = function () { + return this[callback](); + }; + } + if (token) { + formatTokenFunctions[token] = func; + } + if (padded) { + formatTokenFunctions[padded[0]] = function () { + return zeroFill(func.apply(this, arguments), padded[1], padded[2]); + }; + } + if (ordinal) { + formatTokenFunctions[ordinal] = function () { + return this.localeData().ordinal(func.apply(this, arguments), token); + }; + } + } -convert.rgb.ansi16 = function (args) { - var r = args[0]; - var g = args[1]; - var b = args[2]; - var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization + function removeFormattingTokens(input) { + if (input.match(/\[[\s\S]/)) { + return input.replace(/^\[|\]$/g, ''); + } + return input.replace(/\\/g, ''); + } - value = Math.round(value / 50); + function makeFormatFunction(format) { + var array = format.match(formattingTokens), i, length; - if (value === 0) { - return 30; - } + for (i = 0, length = array.length; i < length; i++) { + if (formatTokenFunctions[array[i]]) { + array[i] = formatTokenFunctions[array[i]]; + } else { + array[i] = removeFormattingTokens(array[i]); + } + } - var ansi = 30 - + ((Math.round(b / 255) << 2) - | (Math.round(g / 255) << 1) - | Math.round(r / 255)); + return function (mom) { + var output = '', i; + for (i = 0; i < length; i++) { + output += isFunction(array[i]) ? array[i].call(mom, format) : array[i]; + } + return output; + }; + } - if (value === 2) { - ansi += 60; - } + // format date using native date object + function formatMoment(m, format) { + if (!m.isValid()) { + return m.localeData().invalidDate(); + } - return ansi; -}; + format = expandFormat(format, m.localeData()); + formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format); -convert.hsv.ansi16 = function (args) { - // optimization here; we already know the value and don't need to get - // it converted for us. - return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); -}; + return formatFunctions[format](m); + } -convert.rgb.ansi256 = function (args) { - var r = args[0]; - var g = args[1]; - var b = args[2]; + function expandFormat(format, locale) { + var i = 5; - // we use the extended greyscale palette here, with the exception of - // black and white. normal palette only has 4 greyscale shades. - if (r === g && g === b) { - if (r < 8) { - return 16; - } + function replaceLongDateFormatTokens(input) { + return locale.longDateFormat(input) || input; + } - if (r > 248) { - return 231; - } + localFormattingTokens.lastIndex = 0; + while (i >= 0 && localFormattingTokens.test(format)) { + format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); + localFormattingTokens.lastIndex = 0; + i -= 1; + } - return Math.round(((r - 8) / 247) * 24) + 232; - } + return format; + } - var ansi = 16 - + (36 * Math.round(r / 255 * 5)) - + (6 * Math.round(g / 255 * 5)) - + Math.round(b / 255 * 5); + var match1 = /\d/; // 0 - 9 + var match2 = /\d\d/; // 00 - 99 + var match3 = /\d{3}/; // 000 - 999 + var match4 = /\d{4}/; // 0000 - 9999 + var match6 = /[+-]?\d{6}/; // -999999 - 999999 + var match1to2 = /\d\d?/; // 0 - 99 + var match3to4 = /\d\d\d\d?/; // 999 - 9999 + var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999 + var match1to3 = /\d{1,3}/; // 0 - 999 + var match1to4 = /\d{1,4}/; // 0 - 9999 + var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999 - return ansi; -}; + var matchUnsigned = /\d+/; // 0 - inf + var matchSigned = /[+-]?\d+/; // -inf - inf -convert.ansi16.rgb = function (args) { - var color = args % 10; + var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z + var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z - // handle greyscale - if (color === 0 || color === 7) { - if (args > 50) { - color += 3.5; - } + var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123 - color = color / 10.5 * 255; + // any word (or two) characters or numbers including two/three word month in arabic. + // includes scottish gaelic two word and hyphenated months + var matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i; - return [color, color, color]; - } + var regexes = {}; - var mult = (~~(args > 50) + 1) * 0.5; - var r = ((color & 1) * mult) * 255; - var g = (((color >> 1) & 1) * mult) * 255; - var b = (((color >> 2) & 1) * mult) * 255; + function addRegexToken (token, regex, strictRegex) { + regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) { + return (isStrict && strictRegex) ? strictRegex : regex; + }; + } - return [r, g, b]; -}; + function getParseRegexForToken (token, config) { + if (!hasOwnProp(regexes, token)) { + return new RegExp(unescapeFormat(token)); + } -convert.ansi256.rgb = function (args) { - // handle greyscale - if (args >= 232) { - var c = (args - 232) * 10 + 8; - return [c, c, c]; - } + return regexes[token](config._strict, config._locale); + } - args -= 16; + // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript + function unescapeFormat(s) { + return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { + return p1 || p2 || p3 || p4; + })); + } - var rem; - var r = Math.floor(args / 36) / 5 * 255; - var g = Math.floor((rem = args % 36) / 6) / 5 * 255; - var b = (rem % 6) / 5 * 255; + function regexEscape(s) { + return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); + } - return [r, g, b]; -}; + var tokens = {}; -convert.rgb.hex = function (args) { - var integer = ((Math.round(args[0]) & 0xFF) << 16) - + ((Math.round(args[1]) & 0xFF) << 8) - + (Math.round(args[2]) & 0xFF); + function addParseToken (token, callback) { + var i, func = callback; + if (typeof token === 'string') { + token = [token]; + } + if (isNumber(callback)) { + func = function (input, array) { + array[callback] = toInt(input); + }; + } + for (i = 0; i < token.length; i++) { + tokens[token[i]] = func; + } + } - var string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; -}; + function addWeekParseToken (token, callback) { + addParseToken(token, function (input, array, config, token) { + config._w = config._w || {}; + callback(input, config._w, config, token); + }); + } -convert.hex.rgb = function (args) { - var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); - if (!match) { - return [0, 0, 0]; - } + function addTimeToArrayFromToken(token, input, config) { + if (input != null && hasOwnProp(tokens, token)) { + tokens[token](input, config._a, config, token); + } + } - var colorString = match[0]; + var YEAR = 0; + var MONTH = 1; + var DATE = 2; + var HOUR = 3; + var MINUTE = 4; + var SECOND = 5; + var MILLISECOND = 6; + var WEEK = 7; + var WEEKDAY = 8; - if (match[0].length === 3) { - colorString = colorString.split('').map(function (char) { - return char + char; - }).join(''); - } + // FORMATTING - var integer = parseInt(colorString, 16); - var r = (integer >> 16) & 0xFF; - var g = (integer >> 8) & 0xFF; - var b = integer & 0xFF; + addFormatToken('Y', 0, 0, function () { + var y = this.year(); + return y <= 9999 ? '' + y : '+' + y; + }); - return [r, g, b]; -}; + addFormatToken(0, ['YY', 2], 0, function () { + return this.year() % 100; + }); -convert.rgb.hcg = function (rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; - var max = Math.max(Math.max(r, g), b); - var min = Math.min(Math.min(r, g), b); - var chroma = (max - min); - var grayscale; - var hue; + addFormatToken(0, ['YYYY', 4], 0, 'year'); + addFormatToken(0, ['YYYYY', 5], 0, 'year'); + addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); - if (chroma < 1) { - grayscale = min / (1 - chroma); - } else { - grayscale = 0; - } + // ALIASES - if (chroma <= 0) { - hue = 0; - } else - if (max === r) { - hue = ((g - b) / chroma) % 6; - } else - if (max === g) { - hue = 2 + (b - r) / chroma; - } else { - hue = 4 + (r - g) / chroma + 4; - } + addUnitAlias('year', 'y'); - hue /= 6; - hue %= 1; + // PRIORITIES - return [hue * 360, chroma * 100, grayscale * 100]; -}; + addUnitPriority('year', 1); -convert.hsl.hcg = function (hsl) { - var s = hsl[1] / 100; - var l = hsl[2] / 100; - var c = 1; - var f = 0; + // PARSING - if (l < 0.5) { - c = 2.0 * s * l; - } else { - c = 2.0 * s * (1.0 - l); - } + addRegexToken('Y', matchSigned); + addRegexToken('YY', match1to2, match2); + addRegexToken('YYYY', match1to4, match4); + addRegexToken('YYYYY', match1to6, match6); + addRegexToken('YYYYYY', match1to6, match6); - if (c < 1.0) { - f = (l - 0.5 * c) / (1.0 - c); - } + addParseToken(['YYYYY', 'YYYYYY'], YEAR); + addParseToken('YYYY', function (input, array) { + array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); + }); + addParseToken('YY', function (input, array) { + array[YEAR] = hooks.parseTwoDigitYear(input); + }); + addParseToken('Y', function (input, array) { + array[YEAR] = parseInt(input, 10); + }); - return [hsl[0], c * 100, f * 100]; -}; + // HELPERS -convert.hsv.hcg = function (hsv) { - var s = hsv[1] / 100; - var v = hsv[2] / 100; + function daysInYear(year) { + return isLeapYear(year) ? 366 : 365; + } - var c = s * v; - var f = 0; + function isLeapYear(year) { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; + } - if (c < 1.0) { - f = (v - c) / (1 - c); - } + // HOOKS - return [hsv[0], c * 100, f * 100]; -}; + hooks.parseTwoDigitYear = function (input) { + return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); + }; -convert.hcg.rgb = function (hcg) { - var h = hcg[0] / 360; - var c = hcg[1] / 100; - var g = hcg[2] / 100; + // MOMENTS - if (c === 0.0) { - return [g * 255, g * 255, g * 255]; - } + var getSetYear = makeGetSet('FullYear', true); - var pure = [0, 0, 0]; - var hi = (h % 1) * 6; - var v = hi % 1; - var w = 1 - v; - var mg = 0; + function getIsLeapYear () { + return isLeapYear(this.year()); + } - switch (Math.floor(hi)) { - case 0: - pure[0] = 1; pure[1] = v; pure[2] = 0; break; - case 1: - pure[0] = w; pure[1] = 1; pure[2] = 0; break; - case 2: - pure[0] = 0; pure[1] = 1; pure[2] = v; break; - case 3: - pure[0] = 0; pure[1] = w; pure[2] = 1; break; - case 4: - pure[0] = v; pure[1] = 0; pure[2] = 1; break; - default: - pure[0] = 1; pure[1] = 0; pure[2] = w; - } + function makeGetSet (unit, keepTime) { + return function (value) { + if (value != null) { + set$1(this, unit, value); + hooks.updateOffset(this, keepTime); + return this; + } else { + return get(this, unit); + } + }; + } - mg = (1.0 - c) * g; + function get (mom, unit) { + return mom.isValid() ? + mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN; + } - return [ - (c * pure[0] + mg) * 255, - (c * pure[1] + mg) * 255, - (c * pure[2] + mg) * 255 - ]; -}; + function set$1 (mom, unit, value) { + if (mom.isValid() && !isNaN(value)) { + if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) { + mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month())); + } + else { + mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); + } + } + } -convert.hcg.hsv = function (hcg) { - var c = hcg[1] / 100; - var g = hcg[2] / 100; + // MOMENTS - var v = c + g * (1.0 - c); - var f = 0; + function stringGet (units) { + units = normalizeUnits(units); + if (isFunction(this[units])) { + return this[units](); + } + return this; + } - if (v > 0.0) { - f = c / v; - } - return [hcg[0], f * 100, v * 100]; -}; + function stringSet (units, value) { + if (typeof units === 'object') { + units = normalizeObjectUnits(units); + var prioritized = getPrioritizedUnits(units); + for (var i = 0; i < prioritized.length; i++) { + this[prioritized[i].unit](units[prioritized[i].unit]); + } + } else { + units = normalizeUnits(units); + if (isFunction(this[units])) { + return this[units](value); + } + } + return this; + } -convert.hcg.hsl = function (hcg) { - var c = hcg[1] / 100; - var g = hcg[2] / 100; + function mod(n, x) { + return ((n % x) + x) % x; + } - var l = g * (1.0 - c) + 0.5 * c; - var s = 0; + var indexOf; - if (l > 0.0 && l < 0.5) { - s = c / (2 * l); - } else - if (l >= 0.5 && l < 1.0) { - s = c / (2 * (1 - l)); - } + if (Array.prototype.indexOf) { + indexOf = Array.prototype.indexOf; + } else { + indexOf = function (o) { + // I know + var i; + for (i = 0; i < this.length; ++i) { + if (this[i] === o) { + return i; + } + } + return -1; + }; + } - return [hcg[0], s * 100, l * 100]; -}; + function daysInMonth(year, month) { + if (isNaN(year) || isNaN(month)) { + return NaN; + } + var modMonth = mod(month, 12); + year += (month - modMonth) / 12; + return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2); + } -convert.hcg.hwb = function (hcg) { - var c = hcg[1] / 100; - var g = hcg[2] / 100; - var v = c + g * (1.0 - c); - return [hcg[0], (v - c) * 100, (1 - v) * 100]; -}; + // FORMATTING -convert.hwb.hcg = function (hwb) { - var w = hwb[1] / 100; - var b = hwb[2] / 100; - var v = 1 - b; - var c = v - w; - var g = 0; + addFormatToken('M', ['MM', 2], 'Mo', function () { + return this.month() + 1; + }); - if (c < 1) { - g = (v - c) / (1 - c); - } + addFormatToken('MMM', 0, 0, function (format) { + return this.localeData().monthsShort(this, format); + }); - return [hwb[0], c * 100, g * 100]; -}; + addFormatToken('MMMM', 0, 0, function (format) { + return this.localeData().months(this, format); + }); -convert.apple.rgb = function (apple) { - return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; -}; + // ALIASES -convert.rgb.apple = function (rgb) { - return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; -}; + addUnitAlias('month', 'M'); -convert.gray.rgb = function (args) { - return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; -}; + // PRIORITY -convert.gray.hsl = convert.gray.hsv = function (args) { - return [0, 0, args[0]]; -}; + addUnitPriority('month', 8); -convert.gray.hwb = function (gray) { - return [0, 100, gray[0]]; -}; + // PARSING -convert.gray.cmyk = function (gray) { - return [0, 0, 0, gray[0]]; -}; + addRegexToken('M', match1to2); + addRegexToken('MM', match1to2, match2); + addRegexToken('MMM', function (isStrict, locale) { + return locale.monthsShortRegex(isStrict); + }); + addRegexToken('MMMM', function (isStrict, locale) { + return locale.monthsRegex(isStrict); + }); -convert.gray.lab = function (gray) { - return [gray[0], 0, 0]; -}; + addParseToken(['M', 'MM'], function (input, array) { + array[MONTH] = toInt(input) - 1; + }); -convert.gray.hex = function (gray) { - var val = Math.round(gray[0] / 100 * 255) & 0xFF; - var integer = (val << 16) + (val << 8) + val; + addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { + var month = config._locale.monthsParse(input, token, config._strict); + // if we didn't find a month name, mark the date as invalid. + if (month != null) { + array[MONTH] = month; + } else { + getParsingFlags(config).invalidMonth = input; + } + }); - var string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; -}; + // LOCALES -convert.rgb.gray = function (rgb) { - var val = (rgb[0] + rgb[1] + rgb[2]) / 3; - return [val / 255 * 100]; -}; + var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/; + var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'); + function localeMonths (m, format) { + if (!m) { + return isArray(this._months) ? this._months : + this._months['standalone']; + } + return isArray(this._months) ? this._months[m.month()] : + this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()]; + } + var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'); + function localeMonthsShort (m, format) { + if (!m) { + return isArray(this._monthsShort) ? this._monthsShort : + this._monthsShort['standalone']; + } + return isArray(this._monthsShort) ? this._monthsShort[m.month()] : + this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()]; + } -/***/ }), -/* 8 */ -/***/ (function(module, exports, __webpack_require__) { + function handleStrictParse(monthName, format, strict) { + var i, ii, mom, llc = monthName.toLocaleLowerCase(); + if (!this._monthsParse) { + // this is not used + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + for (i = 0; i < 12; ++i) { + mom = createUTC([2000, i]); + this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase(); + this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase(); + } + } -"use strict"; - - -module.exports = { - "aliceblue": [240, 248, 255], - "antiquewhite": [250, 235, 215], - "aqua": [0, 255, 255], - "aquamarine": [127, 255, 212], - "azure": [240, 255, 255], - "beige": [245, 245, 220], - "bisque": [255, 228, 196], - "black": [0, 0, 0], - "blanchedalmond": [255, 235, 205], - "blue": [0, 0, 255], - "blueviolet": [138, 43, 226], - "brown": [165, 42, 42], - "burlywood": [222, 184, 135], - "cadetblue": [95, 158, 160], - "chartreuse": [127, 255, 0], - "chocolate": [210, 105, 30], - "coral": [255, 127, 80], - "cornflowerblue": [100, 149, 237], - "cornsilk": [255, 248, 220], - "crimson": [220, 20, 60], - "cyan": [0, 255, 255], - "darkblue": [0, 0, 139], - "darkcyan": [0, 139, 139], - "darkgoldenrod": [184, 134, 11], - "darkgray": [169, 169, 169], - "darkgreen": [0, 100, 0], - "darkgrey": [169, 169, 169], - "darkkhaki": [189, 183, 107], - "darkmagenta": [139, 0, 139], - "darkolivegreen": [85, 107, 47], - "darkorange": [255, 140, 0], - "darkorchid": [153, 50, 204], - "darkred": [139, 0, 0], - "darksalmon": [233, 150, 122], - "darkseagreen": [143, 188, 143], - "darkslateblue": [72, 61, 139], - "darkslategray": [47, 79, 79], - "darkslategrey": [47, 79, 79], - "darkturquoise": [0, 206, 209], - "darkviolet": [148, 0, 211], - "deeppink": [255, 20, 147], - "deepskyblue": [0, 191, 255], - "dimgray": [105, 105, 105], - "dimgrey": [105, 105, 105], - "dodgerblue": [30, 144, 255], - "firebrick": [178, 34, 34], - "floralwhite": [255, 250, 240], - "forestgreen": [34, 139, 34], - "fuchsia": [255, 0, 255], - "gainsboro": [220, 220, 220], - "ghostwhite": [248, 248, 255], - "gold": [255, 215, 0], - "goldenrod": [218, 165, 32], - "gray": [128, 128, 128], - "green": [0, 128, 0], - "greenyellow": [173, 255, 47], - "grey": [128, 128, 128], - "honeydew": [240, 255, 240], - "hotpink": [255, 105, 180], - "indianred": [205, 92, 92], - "indigo": [75, 0, 130], - "ivory": [255, 255, 240], - "khaki": [240, 230, 140], - "lavender": [230, 230, 250], - "lavenderblush": [255, 240, 245], - "lawngreen": [124, 252, 0], - "lemonchiffon": [255, 250, 205], - "lightblue": [173, 216, 230], - "lightcoral": [240, 128, 128], - "lightcyan": [224, 255, 255], - "lightgoldenrodyellow": [250, 250, 210], - "lightgray": [211, 211, 211], - "lightgreen": [144, 238, 144], - "lightgrey": [211, 211, 211], - "lightpink": [255, 182, 193], - "lightsalmon": [255, 160, 122], - "lightseagreen": [32, 178, 170], - "lightskyblue": [135, 206, 250], - "lightslategray": [119, 136, 153], - "lightslategrey": [119, 136, 153], - "lightsteelblue": [176, 196, 222], - "lightyellow": [255, 255, 224], - "lime": [0, 255, 0], - "limegreen": [50, 205, 50], - "linen": [250, 240, 230], - "magenta": [255, 0, 255], - "maroon": [128, 0, 0], - "mediumaquamarine": [102, 205, 170], - "mediumblue": [0, 0, 205], - "mediumorchid": [186, 85, 211], - "mediumpurple": [147, 112, 219], - "mediumseagreen": [60, 179, 113], - "mediumslateblue": [123, 104, 238], - "mediumspringgreen": [0, 250, 154], - "mediumturquoise": [72, 209, 204], - "mediumvioletred": [199, 21, 133], - "midnightblue": [25, 25, 112], - "mintcream": [245, 255, 250], - "mistyrose": [255, 228, 225], - "moccasin": [255, 228, 181], - "navajowhite": [255, 222, 173], - "navy": [0, 0, 128], - "oldlace": [253, 245, 230], - "olive": [128, 128, 0], - "olivedrab": [107, 142, 35], - "orange": [255, 165, 0], - "orangered": [255, 69, 0], - "orchid": [218, 112, 214], - "palegoldenrod": [238, 232, 170], - "palegreen": [152, 251, 152], - "paleturquoise": [175, 238, 238], - "palevioletred": [219, 112, 147], - "papayawhip": [255, 239, 213], - "peachpuff": [255, 218, 185], - "peru": [205, 133, 63], - "pink": [255, 192, 203], - "plum": [221, 160, 221], - "powderblue": [176, 224, 230], - "purple": [128, 0, 128], - "rebeccapurple": [102, 51, 153], - "red": [255, 0, 0], - "rosybrown": [188, 143, 143], - "royalblue": [65, 105, 225], - "saddlebrown": [139, 69, 19], - "salmon": [250, 128, 114], - "sandybrown": [244, 164, 96], - "seagreen": [46, 139, 87], - "seashell": [255, 245, 238], - "sienna": [160, 82, 45], - "silver": [192, 192, 192], - "skyblue": [135, 206, 235], - "slateblue": [106, 90, 205], - "slategray": [112, 128, 144], - "slategrey": [112, 128, 144], - "snow": [255, 250, 250], - "springgreen": [0, 255, 127], - "steelblue": [70, 130, 180], - "tan": [210, 180, 140], - "teal": [0, 128, 128], - "thistle": [216, 191, 216], - "tomato": [255, 99, 71], - "turquoise": [64, 224, 208], - "violet": [238, 130, 238], - "wheat": [245, 222, 179], - "white": [255, 255, 255], - "whitesmoke": [245, 245, 245], - "yellow": [255, 255, 0], - "yellowgreen": [154, 205, 50] -}; + if (strict) { + if (format === 'MMM') { + ii = indexOf.call(this._shortMonthsParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._longMonthsParse, llc); + return ii !== -1 ? ii : null; + } + } else { + if (format === 'MMM') { + ii = indexOf.call(this._shortMonthsParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._longMonthsParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._longMonthsParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortMonthsParse, llc); + return ii !== -1 ? ii : null; + } + } + } + function localeMonthsParse (monthName, format, strict) { + var i, mom, regex; -/***/ }), -/* 9 */ -/***/ (function(module, exports, __webpack_require__) { + if (this._monthsParseExact) { + return handleStrictParse.call(this, monthName, format, strict); + } -var conversions = __webpack_require__(7); + if (!this._monthsParse) { + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + } -/* - this function routes a model to all other models. + // TODO: add sorting + // Sorting makes sure if one month (or abbr) is a prefix of another + // see sorting in computeMonthsParse + for (i = 0; i < 12; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, i]); + if (strict && !this._longMonthsParse[i]) { + this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'); + this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i'); + } + if (!strict && !this._monthsParse[i]) { + regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); + this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); + } + // test the regex + if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) { + return i; + } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) { + return i; + } else if (!strict && this._monthsParse[i].test(monthName)) { + return i; + } + } + } - all functions that are routed have a property `.conversion` attached - to the returned synthetic function. This property is an array - of strings, each with the steps in between the 'from' and 'to' - color models (inclusive). + // MOMENTS - conversions that are not possible simply are not included. -*/ + function setMonth (mom, value) { + var dayOfMonth; -function buildGraph() { - var graph = {}; - // https://jsperf.com/object-keys-vs-for-in-with-closure/3 - var models = Object.keys(conversions); + if (!mom.isValid()) { + // No op + return mom; + } - for (var len = models.length, i = 0; i < len; i++) { - graph[models[i]] = { - // http://jsperf.com/1-vs-infinity - // micro-opt, but this is simple. - distance: -1, - parent: null - }; - } + if (typeof value === 'string') { + if (/^\d+$/.test(value)) { + value = toInt(value); + } else { + value = mom.localeData().monthsParse(value); + // TODO: Another silent failure? + if (!isNumber(value)) { + return mom; + } + } + } - return graph; -} + dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); + mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); + return mom; + } -// https://en.wikipedia.org/wiki/Breadth-first_search -function deriveBFS(fromModel) { - var graph = buildGraph(); - var queue = [fromModel]; // unshift -> queue -> pop + function getSetMonth (value) { + if (value != null) { + setMonth(this, value); + hooks.updateOffset(this, true); + return this; + } else { + return get(this, 'Month'); + } + } - graph[fromModel].distance = 0; + function getDaysInMonth () { + return daysInMonth(this.year(), this.month()); + } - while (queue.length) { - var current = queue.pop(); - var adjacents = Object.keys(conversions[current]); + var defaultMonthsShortRegex = matchWord; + function monthsShortRegex (isStrict) { + if (this._monthsParseExact) { + if (!hasOwnProp(this, '_monthsRegex')) { + computeMonthsParse.call(this); + } + if (isStrict) { + return this._monthsShortStrictRegex; + } else { + return this._monthsShortRegex; + } + } else { + if (!hasOwnProp(this, '_monthsShortRegex')) { + this._monthsShortRegex = defaultMonthsShortRegex; + } + return this._monthsShortStrictRegex && isStrict ? + this._monthsShortStrictRegex : this._monthsShortRegex; + } + } - for (var len = adjacents.length, i = 0; i < len; i++) { - var adjacent = adjacents[i]; - var node = graph[adjacent]; + var defaultMonthsRegex = matchWord; + function monthsRegex (isStrict) { + if (this._monthsParseExact) { + if (!hasOwnProp(this, '_monthsRegex')) { + computeMonthsParse.call(this); + } + if (isStrict) { + return this._monthsStrictRegex; + } else { + return this._monthsRegex; + } + } else { + if (!hasOwnProp(this, '_monthsRegex')) { + this._monthsRegex = defaultMonthsRegex; + } + return this._monthsStrictRegex && isStrict ? + this._monthsStrictRegex : this._monthsRegex; + } + } - if (node.distance === -1) { - node.distance = graph[current].distance + 1; - node.parent = current; - queue.unshift(adjacent); - } - } - } + function computeMonthsParse () { + function cmpLenRev(a, b) { + return b.length - a.length; + } - return graph; -} + var shortPieces = [], longPieces = [], mixedPieces = [], + i, mom; + for (i = 0; i < 12; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, i]); + shortPieces.push(this.monthsShort(mom, '')); + longPieces.push(this.months(mom, '')); + mixedPieces.push(this.months(mom, '')); + mixedPieces.push(this.monthsShort(mom, '')); + } + // Sorting makes sure if one month (or abbr) is a prefix of another it + // will match the longer piece. + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); + for (i = 0; i < 12; i++) { + shortPieces[i] = regexEscape(shortPieces[i]); + longPieces[i] = regexEscape(longPieces[i]); + } + for (i = 0; i < 24; i++) { + mixedPieces[i] = regexEscape(mixedPieces[i]); + } -function link(from, to) { - return function (args) { - return to(from(args)); - }; -} + this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); + this._monthsShortRegex = this._monthsRegex; + this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); + this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); + } -function wrapConversion(toModel, graph) { - var path = [graph[toModel].parent, toModel]; - var fn = conversions[graph[toModel].parent][toModel]; + function createDate (y, m, d, h, M, s, ms) { + // can't just apply() to create a date: + // https://stackoverflow.com/q/181348 + var date; + // the date constructor remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + // preserve leap years using a full 400 year cycle, then reset + date = new Date(y + 400, m, d, h, M, s, ms); + if (isFinite(date.getFullYear())) { + date.setFullYear(y); + } + } else { + date = new Date(y, m, d, h, M, s, ms); + } - var cur = graph[toModel].parent; - while (graph[cur].parent) { - path.unshift(graph[cur].parent); - fn = link(conversions[graph[cur].parent][cur], fn); - cur = graph[cur].parent; - } - - fn.conversion = path; - return fn; -} - -module.exports = function (fromModel) { - var graph = deriveBFS(fromModel); - var conversion = {}; - - var models = Object.keys(graph); - for (var len = models.length, i = 0; i < len; i++) { - var toModel = models[i]; - var node = graph[toModel]; + return date; + } - if (node.parent === null) { - // no possible conversion, or this node is the source model. - continue; - } + function createUTCDate (y) { + var date; + // the Date.UTC function remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + var args = Array.prototype.slice.call(arguments); + // preserve leap years using a full 400 year cycle, then reset + args[0] = y + 400; + date = new Date(Date.UTC.apply(null, args)); + if (isFinite(date.getUTCFullYear())) { + date.setUTCFullYear(y); + } + } else { + date = new Date(Date.UTC.apply(null, arguments)); + } - conversion[toModel] = wrapConversion(toModel, graph); - } + return date; + } - return conversion; -}; + // start-of-first-week - start-of-year + function firstWeekOffset(year, dow, doy) { + var // first-week day -- which january is always in the first week (4 for iso, 1 for other) + fwd = 7 + dow - doy, + // first-week day local weekday -- which local weekday is fwd + fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; + return -fwdlw + fwd - 1; + } + // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday + function dayOfYearFromWeeks(year, week, weekday, dow, doy) { + var localWeekday = (7 + weekday - dow) % 7, + weekOffset = firstWeekOffset(year, dow, doy), + dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, + resYear, resDayOfYear; -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { + if (dayOfYear <= 0) { + resYear = year - 1; + resDayOfYear = daysInYear(resYear) + dayOfYear; + } else if (dayOfYear > daysInYear(year)) { + resYear = year + 1; + resDayOfYear = dayOfYear - daysInYear(year); + } else { + resYear = year; + resDayOfYear = dayOfYear; + } -"use strict"; + return { + year: resYear, + dayOfYear: resDayOfYear + }; + } -const os = __webpack_require__(11); -const hasFlag = __webpack_require__(12); + function weekOfYear(mom, dow, doy) { + var weekOffset = firstWeekOffset(mom.year(), dow, doy), + week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, + resWeek, resYear; -const env = process.env; + if (week < 1) { + resYear = mom.year() - 1; + resWeek = week + weeksInYear(resYear, dow, doy); + } else if (week > weeksInYear(mom.year(), dow, doy)) { + resWeek = week - weeksInYear(mom.year(), dow, doy); + resYear = mom.year() + 1; + } else { + resYear = mom.year(); + resWeek = week; + } -let forceColor; -if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false')) { - forceColor = false; -} else if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - forceColor = true; -} -if ('FORCE_COLOR' in env) { - forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; -} + return { + week: resWeek, + year: resYear + }; + } -function translateLevel(level) { - if (level === 0) { - return false; - } + function weeksInYear(year, dow, doy) { + var weekOffset = firstWeekOffset(year, dow, doy), + weekOffsetNext = firstWeekOffset(year + 1, dow, doy); + return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; + } - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; -} + // FORMATTING -function supportsColor(stream) { - if (forceColor === false) { - return 0; - } + addFormatToken('w', ['ww', 2], 'wo', 'week'); + addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; - } + // ALIASES - if (hasFlag('color=256')) { - return 2; - } + addUnitAlias('week', 'w'); + addUnitAlias('isoWeek', 'W'); - if (stream && !stream.isTTY && forceColor !== true) { - // VS code debugger doesn't have isTTY set - if (env.VSCODE_PID) { - return 1; - } - return 0; - } + // PRIORITIES - const min = forceColor ? 1 : 0; + addUnitPriority('week', 5); + addUnitPriority('isoWeek', 5); - if (process.platform === 'win32') { - // Node.js 7.5.0 is the first version of Node.js to include a patch to - // libuv that enables 256 color output on Windows. Anything earlier and it - // won't work. However, here we target Node.js 8 at minimum as it is an LTS - // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows - // release that supports 256 colors. Windows 10 build 14931 is the first release - // that supports 16m/TrueColor. - const osRelease = os.release().split('.'); - if ( - Number(process.versions.node.split('.')[0]) >= 8 && - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } + // PARSING - return 1; - } + addRegexToken('w', match1to2); + addRegexToken('ww', match1to2, match2); + addRegexToken('W', match1to2); + addRegexToken('WW', match1to2, match2); - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } + addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) { + week[token.substr(0, 1)] = toInt(input); + }); - return min; - } + // HELPERS - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } + // LOCALES - if (env.COLORTERM === 'truecolor') { - return 3; - } + function localeWeek (mom) { + return weekOfYear(mom, this._week.dow, this._week.doy).week; + } - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + var defaultLocaleWeek = { + dow : 0, // Sunday is the first day of the week. + doy : 6 // The week that contains Jan 6th is the first week of the year. + }; - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default - } - } + function localeFirstDayOfWeek () { + return this._week.dow; + } - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } + function localeFirstDayOfYear () { + return this._week.doy; + } - if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } + // MOMENTS - if ('COLORTERM' in env) { - return 1; - } + function getSetWeek (input) { + var week = this.localeData().week(this); + return input == null ? week : this.add((input - week) * 7, 'd'); + } - if (env.TERM === 'dumb') { - return min; - } + function getSetISOWeek (input) { + var week = weekOfYear(this, 1, 4).week; + return input == null ? week : this.add((input - week) * 7, 'd'); + } - return min; -} + // FORMATTING -function getSupportLevel(stream) { - const level = supportsColor(stream); - return translateLevel(level); -} + addFormatToken('d', 0, 'do', 'day'); -module.exports = { - supportsColor: getSupportLevel, - stdout: getSupportLevel(process.stdout), - stderr: getSupportLevel(process.stderr) -}; + addFormatToken('dd', 0, 0, function (format) { + return this.localeData().weekdaysMin(this, format); + }); + addFormatToken('ddd', 0, 0, function (format) { + return this.localeData().weekdaysShort(this, format); + }); -/***/ }), -/* 11 */ -/***/ (function(module, exports) { + addFormatToken('dddd', 0, 0, function (format) { + return this.localeData().weekdays(this, format); + }); -module.exports = require("os"); + addFormatToken('e', 0, 0, 'weekday'); + addFormatToken('E', 0, 0, 'isoWeekday'); -/***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { + // ALIASES -"use strict"; + addUnitAlias('day', 'd'); + addUnitAlias('weekday', 'e'); + addUnitAlias('isoWeekday', 'E'); -module.exports = (flag, argv) => { - argv = argv || process.argv; - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const pos = argv.indexOf(prefix + flag); - const terminatorPos = argv.indexOf('--'); - return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); -}; + // PRIORITY + addUnitPriority('day', 11); + addUnitPriority('weekday', 11); + addUnitPriority('isoWeekday', 11); + // PARSING -/***/ }), -/* 13 */ -/***/ (function(module, exports, __webpack_require__) { + addRegexToken('d', match1to2); + addRegexToken('e', match1to2); + addRegexToken('E', match1to2); + addRegexToken('dd', function (isStrict, locale) { + return locale.weekdaysMinRegex(isStrict); + }); + addRegexToken('ddd', function (isStrict, locale) { + return locale.weekdaysShortRegex(isStrict); + }); + addRegexToken('dddd', function (isStrict, locale) { + return locale.weekdaysRegex(isStrict); + }); -"use strict"; + addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { + var weekday = config._locale.weekdaysParse(input, token, config._strict); + // if we didn't get a weekday name, mark the date as invalid + if (weekday != null) { + week.d = weekday; + } else { + getParsingFlags(config).invalidWeekday = input; + } + }); -const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; -const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; -const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; -const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; + addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { + week[token] = toInt(input); + }); -const ESCAPES = new Map([ - ['n', '\n'], - ['r', '\r'], - ['t', '\t'], - ['b', '\b'], - ['f', '\f'], - ['v', '\v'], - ['0', '\0'], - ['\\', '\\'], - ['e', '\u001B'], - ['a', '\u0007'] -]); + // HELPERS -function unescape(c) { - if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { - return String.fromCharCode(parseInt(c.slice(1), 16)); - } + function parseWeekday(input, locale) { + if (typeof input !== 'string') { + return input; + } - return ESCAPES.get(c) || c; -} + if (!isNaN(input)) { + return parseInt(input, 10); + } -function parseArguments(name, args) { - const results = []; - const chunks = args.trim().split(/\s*,\s*/g); - let matches; + input = locale.weekdaysParse(input); + if (typeof input === 'number') { + return input; + } - for (const chunk of chunks) { - if (!isNaN(chunk)) { - results.push(Number(chunk)); - } else if ((matches = chunk.match(STRING_REGEX))) { - results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); - } else { - throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); - } - } + return null; + } - return results; -} + function parseIsoWeekday(input, locale) { + if (typeof input === 'string') { + return locale.weekdaysParse(input) % 7 || 7; + } + return isNaN(input) ? null : input; + } -function parseStyle(style) { - STYLE_REGEX.lastIndex = 0; + // LOCALES + function shiftWeekdays (ws, n) { + return ws.slice(n, 7).concat(ws.slice(0, n)); + } - const results = []; - let matches; + var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); + function localeWeekdays (m, format) { + var weekdays = isArray(this._weekdays) ? this._weekdays : + this._weekdays[(m && m !== true && this._weekdays.isFormat.test(format)) ? 'format' : 'standalone']; + return (m === true) ? shiftWeekdays(weekdays, this._week.dow) + : (m) ? weekdays[m.day()] : weekdays; + } - while ((matches = STYLE_REGEX.exec(style)) !== null) { - const name = matches[1]; + var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); + function localeWeekdaysShort (m) { + return (m === true) ? shiftWeekdays(this._weekdaysShort, this._week.dow) + : (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort; + } - if (matches[2]) { - const args = parseArguments(name, matches[2]); - results.push([name].concat(args)); - } else { - results.push([name]); - } - } + var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); + function localeWeekdaysMin (m) { + return (m === true) ? shiftWeekdays(this._weekdaysMin, this._week.dow) + : (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin; + } - return results; -} + function handleStrictParse$1(weekdayName, format, strict) { + var i, ii, mom, llc = weekdayName.toLocaleLowerCase(); + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._shortWeekdaysParse = []; + this._minWeekdaysParse = []; -function buildStyle(chalk, styles) { - const enabled = {}; + for (i = 0; i < 7; ++i) { + mom = createUTC([2000, 1]).day(i); + this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase(); + this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase(); + this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase(); + } + } - for (const layer of styles) { - for (const style of layer.styles) { - enabled[style[0]] = layer.inverse ? null : style.slice(1); - } - } + if (strict) { + if (format === 'dddd') { + ii = indexOf.call(this._weekdaysParse, llc); + return ii !== -1 ? ii : null; + } else if (format === 'ddd') { + ii = indexOf.call(this._shortWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } + } else { + if (format === 'dddd') { + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else if (format === 'ddd') { + ii = indexOf.call(this._shortWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._minWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } + } + } - let current = chalk; - for (const styleName of Object.keys(enabled)) { - if (Array.isArray(enabled[styleName])) { - if (!(styleName in current)) { - throw new Error(`Unknown Chalk style: ${styleName}`); - } + function localeWeekdaysParse (weekdayName, format, strict) { + var i, mom, regex; - if (enabled[styleName].length > 0) { - current = current[styleName].apply(current, enabled[styleName]); - } else { - current = current[styleName]; - } - } - } + if (this._weekdaysParseExact) { + return handleStrictParse$1.call(this, weekdayName, format, strict); + } - return current; -} + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._minWeekdaysParse = []; + this._shortWeekdaysParse = []; + this._fullWeekdaysParse = []; + } -module.exports = (chalk, tmp) => { - const styles = []; - const chunks = []; - let chunk = []; + for (i = 0; i < 7; i++) { + // make the regex if we don't have it already - // eslint-disable-next-line max-params - tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { - if (escapeChar) { - chunk.push(unescape(escapeChar)); - } else if (style) { - const str = chunk.join(''); - chunk = []; - chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); - styles.push({inverse, styles: parseStyle(style)}); - } else if (close) { - if (styles.length === 0) { - throw new Error('Found extraneous } in Chalk template literal'); - } + mom = createUTC([2000, 1]).day(i); + if (strict && !this._fullWeekdaysParse[i]) { + this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', 'i'); + this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', 'i'); + this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', 'i'); + } + if (!this._weekdaysParse[i]) { + regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); + this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); + } + // test the regex + if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) { + return i; + } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) { + return i; + } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) { + return i; + } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { + return i; + } + } + } - chunks.push(buildStyle(chalk, styles)(chunk.join(''))); - chunk = []; - styles.pop(); - } else { - chunk.push(chr); - } - }); + // MOMENTS - chunks.push(chunk.join('')); + function getSetDayOfWeek (input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); + if (input != null) { + input = parseWeekday(input, this.localeData()); + return this.add(input - day, 'd'); + } else { + return day; + } + } - if (styles.length > 0) { - const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; - throw new Error(errMsg); - } + function getSetLocaleDayOfWeek (input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; + return input == null ? weekday : this.add(input - weekday, 'd'); + } - return chunks.join(''); -}; + function getSetISODayOfWeek (input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + // behaves the same as moment#day except + // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) + // as a setter, sunday should belong to the previous week. -/***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { + if (input != null) { + var weekday = parseIsoWeekday(input, this.localeData()); + return this.day(this.day() % 7 ? weekday : weekday - 7); + } else { + return this.day() || 7; + } + } -"use strict"; + var defaultWeekdaysRegex = matchWord; + function weekdaysRegex (isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysStrictRegex; + } else { + return this._weekdaysRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysRegex')) { + this._weekdaysRegex = defaultWeekdaysRegex; + } + return this._weekdaysStrictRegex && isStrict ? + this._weekdaysStrictRegex : this._weekdaysRegex; + } + } + var defaultWeekdaysShortRegex = matchWord; + function weekdaysShortRegex (isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysShortStrictRegex; + } else { + return this._weekdaysShortRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysShortRegex')) { + this._weekdaysShortRegex = defaultWeekdaysShortRegex; + } + return this._weekdaysShortStrictRegex && isStrict ? + this._weekdaysShortStrictRegex : this._weekdaysShortRegex; + } + } -function dedent(strings) { + var defaultWeekdaysMinRegex = matchWord; + function weekdaysMinRegex (isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysMinStrictRegex; + } else { + return this._weekdaysMinRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysMinRegex')) { + this._weekdaysMinRegex = defaultWeekdaysMinRegex; + } + return this._weekdaysMinStrictRegex && isStrict ? + this._weekdaysMinStrictRegex : this._weekdaysMinRegex; + } + } - var raw = void 0; - if (typeof strings === "string") { - // dedent can be used as a plain function - raw = [strings]; - } else { - raw = strings.raw; - } - // first, perform interpolation - var result = ""; - for (var i = 0; i < raw.length; i++) { - result += raw[i]. - // join lines when there is a suppressed newline - replace(/\\\n[ \t]*/g, ""). + function computeWeekdaysParse () { + function cmpLenRev(a, b) { + return b.length - a.length; + } - // handle escaped backticks - replace(/\\`/g, "`"); + var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], + i, mom, minp, shortp, longp; + for (i = 0; i < 7; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, 1]).day(i); + minp = this.weekdaysMin(mom, ''); + shortp = this.weekdaysShort(mom, ''); + longp = this.weekdays(mom, ''); + minPieces.push(minp); + shortPieces.push(shortp); + longPieces.push(longp); + mixedPieces.push(minp); + mixedPieces.push(shortp); + mixedPieces.push(longp); + } + // Sorting makes sure if one weekday (or abbr) is a prefix of another it + // will match the longer piece. + minPieces.sort(cmpLenRev); + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); + for (i = 0; i < 7; i++) { + shortPieces[i] = regexEscape(shortPieces[i]); + longPieces[i] = regexEscape(longPieces[i]); + mixedPieces[i] = regexEscape(mixedPieces[i]); + } - if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) { - result += arguments.length <= i + 1 ? undefined : arguments[i + 1]; - } - } + this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); + this._weekdaysShortRegex = this._weekdaysRegex; + this._weekdaysMinRegex = this._weekdaysRegex; - // now strip indentation - var lines = result.split("\n"); - var mindent = null; - lines.forEach(function (l) { - var m = l.match(/^(\s+)\S+/); - if (m) { - var indent = m[1].length; - if (!mindent) { - // this is the first indented line - mindent = indent; - } else { - mindent = Math.min(mindent, indent); - } + this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); + this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); + this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i'); } - }); - if (mindent !== null) { - result = lines.map(function (l) { - return l[0] === " " ? l.slice(mindent) : l; - }).join("\n"); - } + // FORMATTING - // dedent eats leading and trailing whitespace too - result = result.trim(); + function hFormat() { + return this.hours() % 12 || 12; + } - // handle escaped newlines at the end to ensure they don't get stripped too - return result.replace(/\\n/g, "\n"); -} + function kFormat() { + return this.hours() || 24; + } -if (true) { - module.exports = dedent; -} + addFormatToken('H', ['HH', 2], 0, 'hour'); + addFormatToken('h', ['hh', 2], 0, hFormat); + addFormatToken('k', ['kk', 2], 0, kFormat); + addFormatToken('hmm', 0, 0, function () { + return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2); + }); -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { + addFormatToken('hmmss', 0, 0, function () { + return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + + zeroFill(this.seconds(), 2); + }); -"use strict"; + addFormatToken('Hmm', 0, 0, function () { + return '' + this.hours() + zeroFill(this.minutes(), 2); + }); + addFormatToken('Hmmss', 0, 0, function () { + return '' + this.hours() + zeroFill(this.minutes(), 2) + + zeroFill(this.seconds(), 2); + }); -const EMPTYARR = [] -const SHORTSPLIT = /$|[!-@[-`{-~][\s\S]*/g -const isArray = Array.isArray + function meridiem (token, lowercase) { + addFormatToken(token, 0, 0, function () { + return this.localeData().meridiem(this.hours(), this.minutes(), lowercase); + }); + } -const parseValue = function(any) { - if (any === "") return "" - if (any === "false") return false - const maybe = Number(any) - return maybe * 0 === 0 ? maybe : any -} + meridiem('a', true); + meridiem('A', false); -const parseAlias = function(aliases) { - let out = {}, - key, - alias, - prev, - len, - any, - i, - k + // ALIASES - for (key in aliases) { - any = aliases[key] - alias = out[key] = isArray(any) ? any : [any] + addUnitAlias('hour', 'h'); - for (i = 0, len = alias.length; i < len; i++) { - prev = out[alias[i]] = [key] + // PRIORITY + addUnitPriority('hour', 13); - for (k = 0; k < len; k++) { - if (i !== k) prev.push(alias[k]) - } + // PARSING + + function matchMeridiem (isStrict, locale) { + return locale._meridiemParse; } - } - return out -} + addRegexToken('a', matchMeridiem); + addRegexToken('A', matchMeridiem); + addRegexToken('H', match1to2); + addRegexToken('h', match1to2); + addRegexToken('k', match1to2); + addRegexToken('HH', match1to2, match2); + addRegexToken('hh', match1to2, match2); + addRegexToken('kk', match1to2, match2); -const parseDefault = function(aliases, defaults) { - let out = {}, - key, - alias, - value, - len, - i + addRegexToken('hmm', match3to4); + addRegexToken('hmmss', match5to6); + addRegexToken('Hmm', match3to4); + addRegexToken('Hmmss', match5to6); - for (key in defaults) { - value = defaults[key] - alias = aliases[key] + addParseToken(['H', 'HH'], HOUR); + addParseToken(['k', 'kk'], function (input, array, config) { + var kInput = toInt(input); + array[HOUR] = kInput === 24 ? 0 : kInput; + }); + addParseToken(['a', 'A'], function (input, array, config) { + config._isPm = config._locale.isPM(input); + config._meridiem = input; + }); + addParseToken(['h', 'hh'], function (input, array, config) { + array[HOUR] = toInt(input); + getParsingFlags(config).bigHour = true; + }); + addParseToken('hmm', function (input, array, config) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); + getParsingFlags(config).bigHour = true; + }); + addParseToken('hmmss', function (input, array, config) { + var pos1 = input.length - 4; + var pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); + getParsingFlags(config).bigHour = true; + }); + addParseToken('Hmm', function (input, array, config) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); + }); + addParseToken('Hmmss', function (input, array, config) { + var pos1 = input.length - 4; + var pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); + }); - out[key] = value + // LOCALES - if (alias === undefined) { - aliases[key] = EMPTYARR - } else { - for (i = 0, len = alias.length; i < len; i++) { - out[alias[i]] = value - } + function localeIsPM (input) { + // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays + // Using charAt should be more compatible. + return ((input + '').toLowerCase().charAt(0) === 'p'); } - } - return out -} + var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i; + function localeMeridiem (hours, minutes, isLower) { + if (hours > 11) { + return isLower ? 'pm' : 'PM'; + } else { + return isLower ? 'am' : 'AM'; + } + } -const parseOptions = function(aliases, options, value) { - let out = {}, - key, - alias, - len, - end, - i, - k - if (options !== undefined) { - for (i = 0, len = options.length; i < len; i++) { - key = options[i] - alias = aliases[key] + // MOMENTS - out[key] = value + // Setting the hour should keep the time, because the user explicitly + // specified which hour they want. So trying to maintain the same hour (in + // a new timezone) makes sense. Adding/subtracting hours does not follow + // this rule. + var getSetHour = makeGetSet('Hours', true); - if (alias === undefined) { - aliases[key] = EMPTYARR - } else { - for (k = 0, end = alias.length; k < end; k++) { - out[alias[k]] = value - } - } - } - } + var baseConfig = { + calendar: defaultCalendar, + longDateFormat: defaultLongDateFormat, + invalidDate: defaultInvalidDate, + ordinal: defaultOrdinal, + dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, + relativeTime: defaultRelativeTime, - return out -} + months: defaultLocaleMonths, + monthsShort: defaultLocaleMonthsShort, -const write = function(out, key, value, aliases, unknown) { - let i, - prev, - alias = aliases[key], - len = alias === undefined ? -1 : alias.length + week: defaultLocaleWeek, - if (len >= 0 || unknown === undefined || unknown(key)) { - prev = out[key] + weekdays: defaultLocaleWeekdays, + weekdaysMin: defaultLocaleWeekdaysMin, + weekdaysShort: defaultLocaleWeekdaysShort, - if (prev === undefined) { - out[key] = value - } else { - if (isArray(prev)) { - prev.push(value) - } else { - out[key] = [prev, value] - } - } + meridiemParse: defaultLocaleMeridiemParse + }; - for (i = 0; i < len; i++) { - out[alias[i]] = out[key] + // internal storage for locale config files + var locales = {}; + var localeFamilies = {}; + var globalLocale; + + function normalizeLocale(key) { + return key ? key.toLowerCase().replace('_', '-') : key; } - } -} -const getopts = function(argv, opts) { - let unknown = (opts = opts || {}).unknown, - aliases = parseAlias(opts.alias), - strings = parseOptions(aliases, opts.string, ""), - values = parseDefault(aliases, opts.default), - bools = parseOptions(aliases, opts.boolean, false), - stopEarly = opts.stopEarly, - _ = [], - out = { _ }, - i = 0, - k = 0, - len = argv.length, - key, - arg, - end, - match, - value + // pick the locale from the array + // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each + // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root + function chooseLocale(names) { + var i = 0, j, next, locale, split; - for (; i < len; i++) { - arg = argv[i] + while (i < names.length) { + split = normalizeLocale(names[i]).split('-'); + j = split.length; + next = normalizeLocale(names[i + 1]); + next = next ? next.split('-') : null; + while (j > 0) { + locale = loadLocale(split.slice(0, j).join('-')); + if (locale) { + return locale; + } + if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { + //the next array item is better than a shallower substring of this one + break; + } + j--; + } + i++; + } + return globalLocale; + } - if (arg[0] !== "-" || arg === "-") { - if (stopEarly) while (i < len) _.push(argv[i++]) - else _.push(arg) - } else if (arg === "--") { - while (++i < len) _.push(argv[i]) - } else if (arg[1] === "-") { - end = arg.indexOf("=", 2) - if (arg[2] === "n" && arg[3] === "o" && arg[4] === "-") { - key = arg.slice(5, end >= 0 ? end : undefined) - value = false - } else if (end >= 0) { - key = arg.slice(2, end) - value = - bools[key] !== undefined || - (strings[key] === undefined - ? parseValue(arg.slice(end + 1)) - : arg.slice(end + 1)) - } else { - key = arg.slice(2) - value = - bools[key] !== undefined || - (len === i + 1 || argv[i + 1][0] === "-" - ? strings[key] === undefined - ? true - : "" - : strings[key] === undefined - ? parseValue(argv[++i]) - : argv[++i]) - } - write(out, key, value, aliases, unknown) - } else { - SHORTSPLIT.lastIndex = 2 - match = SHORTSPLIT.exec(arg) - end = match.index - value = match[0] - - for (k = 1; k < end; k++) { - write( - out, - (key = arg[k]), - k + 1 < end - ? strings[key] === undefined || - arg.substring(k + 1, (k = end)) + value - : value === "" - ? len === i + 1 || argv[i + 1][0] === "-" - ? strings[key] === undefined || "" - : bools[key] !== undefined || - (strings[key] === undefined ? parseValue(argv[++i]) : argv[++i]) - : bools[key] !== undefined || - (strings[key] === undefined ? parseValue(value) : value), - aliases, - unknown - ) - } + function loadLocale(name) { + var oldLocale = null; + // TODO: Find a better way to register and load all the locales in Node + if (!locales[name] && (typeof module !== 'undefined') && + module && module.exports) { + try { + oldLocale = globalLocale._abbr; + var aliasedRequire = require; + __webpack_require__(12)("./" + name); + getSetGlobalLocale(oldLocale); + } catch (e) {} + } + return locales[name]; } - } - - for (key in values) if (out[key] === undefined) out[key] = values[key] - for (key in bools) if (out[key] === undefined) out[key] = false - for (key in strings) if (out[key] === undefined) out[key] = "" - return out -} + // This function will load locale and then set the global locale. If + // no arguments are passed in, it will simply return the current global + // locale key. + function getSetGlobalLocale (key, values) { + var data; + if (key) { + if (isUndefined(values)) { + data = getLocale(key); + } + else { + data = defineLocale(key, values); + } -module.exports = getopts + if (data) { + // moment.duration._locale = moment._locale = data; + globalLocale = data; + } + else { + if ((typeof console !== 'undefined') && console.warn) { + //warn user if arguments are passed but the locale could not be set + console.warn('Locale ' + key + ' not found. Did you forget to load it?'); + } + } + } + return globalLocale._abbr; + } -/***/ }), -/* 16 */ -/***/ (function(module, exports) { + function defineLocale (name, config) { + if (config !== null) { + var locale, parentConfig = baseConfig; + config.abbr = name; + if (locales[name] != null) { + deprecateSimple('defineLocaleOverride', + 'use moment.updateLocale(localeName, config) to change ' + + 'an existing locale. moment.defineLocale(localeName, ' + + 'config) should only be used for creating a new locale ' + + 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'); + parentConfig = locales[name]._config; + } else if (config.parentLocale != null) { + if (locales[config.parentLocale] != null) { + parentConfig = locales[config.parentLocale]._config; + } else { + locale = loadLocale(config.parentLocale); + if (locale != null) { + parentConfig = locale._config; + } else { + if (!localeFamilies[config.parentLocale]) { + localeFamilies[config.parentLocale] = []; + } + localeFamilies[config.parentLocale].push({ + name: name, + config: config + }); + return null; + } + } + } + locales[name] = new Locale(mergeConfigs(parentConfig, config)); -module.exports = require("path"); + if (localeFamilies[name]) { + localeFamilies[name].forEach(function (x) { + defineLocale(x.name, x.config); + }); + } -/***/ }), -/* 17 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + // backwards compat for now: also set the locale + // make sure we set the locale AFTER all child locales have been + // created, so we won't end up with the child locale set. + getSetGlobalLocale(name); -"use strict"; -__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__(18); -/* harmony import */ var _clean__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(586); -/* harmony import */ var _run__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(686); -/* harmony import */ var _watch__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(687); -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ + return locales[name]; + } else { + // useful for testing + delete locales[name]; + return null; + } + } + function updateLocale(name, config) { + if (config != null) { + var locale, tmpLocale, parentConfig = baseConfig; + // MERGE + tmpLocale = loadLocale(name); + if (tmpLocale != null) { + parentConfig = tmpLocale._config; + } + config = mergeConfigs(parentConfig, config); + locale = new Locale(config); + locale.parentLocale = locales[name]; + locales[name] = locale; + // backwards compat for now: also set the locale + getSetGlobalLocale(name); + } else { + // pass null for config to unupdate, useful for tests + if (locales[name] != null) { + if (locales[name].parentLocale != null) { + locales[name] = locales[name].parentLocale; + } else if (locales[name] != null) { + delete locales[name]; + } + } + } + return locales[name]; + } -const commands = { - bootstrap: _bootstrap__WEBPACK_IMPORTED_MODULE_0__["BootstrapCommand"], - clean: _clean__WEBPACK_IMPORTED_MODULE_1__["CleanCommand"], - run: _run__WEBPACK_IMPORTED_MODULE_2__["RunCommand"], - watch: _watch__WEBPACK_IMPORTED_MODULE_3__["WatchCommand"] -}; + // returns locale data + function getLocale (key) { + var locale; -/***/ }), -/* 18 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + if (key && key._locale && key._locale._abbr) { + key = key._locale._abbr; + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BootstrapCommand", function() { return BootstrapCommand; }); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(chalk__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _utils_link_project_executables__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(19); -/* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(34); -/* harmony import */ var _utils_parallelize__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(501); -/* harmony import */ var _utils_projects__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(502); -/* harmony import */ var _utils_project_checksums__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(580); -/* harmony import */ var _utils_bootstrap_cache_file__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(585); -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ + if (!key) { + return globalLocale; + } + if (!isArray(key)) { + //short-circuit everything else + locale = loadLocale(key); + if (locale) { + return locale; + } + key = [key]; + } + return chooseLocale(key); + } + function listLocales() { + return keys(locales); + } + function checkOverflow (m) { + var overflow; + var a = m._a; + if (a && getParsingFlags(m).overflow === -2) { + overflow = + a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : + a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : + a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR : + a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : + a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : + a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : + -1; + if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { + overflow = DATE; + } + if (getParsingFlags(m)._overflowWeeks && overflow === -1) { + overflow = WEEK; + } + if (getParsingFlags(m)._overflowWeekday && overflow === -1) { + overflow = WEEKDAY; + } -const BootstrapCommand = { - description: 'Install dependencies and crosslink projects', - name: 'bootstrap', + getParsingFlags(m).overflow = overflow; + } - async run(projects, projectGraph, { - options, - kbn - }) { - const batchedProjectsByWorkspace = Object(_utils_projects__WEBPACK_IMPORTED_MODULE_4__["topologicallyBatchProjects"])(projects, projectGraph, { - batchByWorkspace: true - }); - const batchedProjects = Object(_utils_projects__WEBPACK_IMPORTED_MODULE_4__["topologicallyBatchProjects"])(projects, projectGraph); - const extraArgs = [...(options['frozen-lockfile'] === true ? ['--frozen-lockfile'] : []), ...(options['prefer-offline'] === true ? ['--prefer-offline'] : [])]; - _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.bold('\nRunning installs in topological order:')); + return m; + } - for (const batch of batchedProjectsByWorkspace) { - for (const project of batch) { - if (project.isWorkspaceProject) { - _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"].write(`Skipping workspace project: ${project.name}`); - continue; + // Pick the first defined of two or three arguments. + function defaults(a, b, c) { + if (a != null) { + return a; } - - if (project.hasDependencies()) { - await project.installDependencies({ - extraArgs - }); + if (b != null) { + return b; } - } + return c; } - _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.bold('\nInstalls completed, linking package executables:\n')); - await Object(_utils_link_project_executables__WEBPACK_IMPORTED_MODULE_1__["linkProjectExecutables"])(projects, projectGraph); - /** - * At the end of the bootstrapping process we call all `kbn:bootstrap` scripts - * in the list of projects. We do this because some projects need to be - * transpiled before they can be used. Ideally we shouldn't do this unless we - * have to, as it will slow down the bootstrapping process. - */ + function currentDateArray(config) { + // hooks is actually the exported moment object + var nowValue = new Date(hooks.now()); + if (config._useUTC) { + return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()]; + } + return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; + } - _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.bold('\nLinking executables completed, running `kbn:bootstrap` scripts\n')); - const checksums = options.cache ? await Object(_utils_project_checksums__WEBPACK_IMPORTED_MODULE_5__["getAllChecksums"])(kbn, _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"]) : false; - await Object(_utils_parallelize__WEBPACK_IMPORTED_MODULE_3__["parallelizeBatches"])(batchedProjects, async project => { - if (project.hasScript('kbn:bootstrap')) { - const cacheFile = new _utils_bootstrap_cache_file__WEBPACK_IMPORTED_MODULE_6__["BootstrapCacheFile"](kbn, project, checksums); + // convert an array to a date. + // the array should mirror the parameters below + // note: all values past the year are optional and will default to the lowest possible value. + // [year, month, day , hour, minute, second, millisecond] + function configFromArray (config) { + var i, date, input = [], currentDate, expectedWeekday, yearToUse; - if (cacheFile.isValid()) { - _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"].success(`[${project.name}] cache up to date`); - } else { - cacheFile.delete(); - await project.runScriptStreaming('kbn:bootstrap'); - cacheFile.write(); + if (config._d) { + return; } - } - }); - _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.green.bold('\nBootstrapping completed!\n')); - } -}; - -/***/ }), -/* 19 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + currentDate = currentDateArray(config); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "linkProjectExecutables", function() { return linkProjectExecutables; }); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(16); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(chalk__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var _fs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(20); -/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(34); -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ + //compute day of the year from weeks and weekdays + if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { + dayOfYearFromWeekInfo(config); + } + //if the day of the year is set, figure out what it is + if (config._dayOfYear != null) { + yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); + if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) { + getParsingFlags(config)._overflowDayOfYear = true; + } + date = createUTCDate(yearToUse, 0, config._dayOfYear); + config._a[MONTH] = date.getUTCMonth(); + config._a[DATE] = date.getUTCDate(); + } + // Default to current date. + // * if no year, month, day of month are given, default to today + // * if day of month is given, default month and year + // * if month is given, default only year + // * if year is given, don't default anything + for (i = 0; i < 3 && config._a[i] == null; ++i) { + config._a[i] = input[i] = currentDate[i]; + } -/** - * Yarn does not link the executables from dependencies that are installed - * using `link:` https://github.com/yarnpkg/yarn/pull/5046 - * - * We simulate this functionality by walking through each project's project - * dependencies, and manually linking their executables if defined. The logic - * for linking was mostly adapted from lerna: https://github.com/lerna/lerna/blob/1d7eb9eeff65d5a7de64dea73613b1bf6bfa8d57/src/PackageUtilities.js#L348 - */ -async function linkProjectExecutables(projectsByName, projectGraph) { - for (const [projectName, projectDeps] of projectGraph) { - const project = projectsByName.get(projectName); - const binsDir = Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(project.nodeModulesLocation, '.bin'); + // Zero out whatever was not defaulted, including time + for (; i < 7; i++) { + config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; + } - for (const projectDep of projectDeps) { - const executables = projectDep.getExecutables(); + // Check for 24:00:00.000 + if (config._a[HOUR] === 24 && + config._a[MINUTE] === 0 && + config._a[SECOND] === 0 && + config._a[MILLISECOND] === 0) { + config._nextDay = true; + config._a[HOUR] = 0; + } - for (const name of Object.keys(executables)) { - const srcPath = executables[name]; // existing logic from lerna -- ensure that the bin we are going to - // point to exists or ignore it + config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input); + expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay(); - if (!(await Object(_fs__WEBPACK_IMPORTED_MODULE_2__["isFile"])(srcPath))) { - continue; + // Apply timezone offset from input. The actual utcOffset can be changed + // with parseZone. + if (config._tzm != null) { + config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); } - const dest = Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(binsDir, name); // Get relative project path with normalized path separators. + if (config._nextDay) { + config._a[HOUR] = 24; + } - const projectRelativePath = Object(path__WEBPACK_IMPORTED_MODULE_0__["relative"])(project.path, srcPath).split(path__WEBPACK_IMPORTED_MODULE_0__["sep"]).join('/'); - _log__WEBPACK_IMPORTED_MODULE_3__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_1___default.a`{dim [${project.name}]} ${name} -> {dim ${projectRelativePath}}`); - await Object(_fs__WEBPACK_IMPORTED_MODULE_2__["mkdirp"])(Object(path__WEBPACK_IMPORTED_MODULE_0__["dirname"])(dest)); - await Object(_fs__WEBPACK_IMPORTED_MODULE_2__["createSymlink"])(srcPath, dest, 'exec'); - await Object(_fs__WEBPACK_IMPORTED_MODULE_2__["chmod"])(dest, '755'); - } + // check for mismatching day of week + if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) { + getParsingFlags(config).weekdayMismatch = true; + } } - } -} - -/***/ }), -/* 20 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readFile", function() { return readFile; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "chmod", function() { return chmod; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mkdirp", function() { return mkdirp; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unlink", function() { return unlink; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "copyDirectory", function() { return copyDirectory; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSymlink", function() { return isSymlink; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDirectory", function() { return isDirectory; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFile", function() { return isFile; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createSymlink", function() { return createSymlink; }); -/* harmony import */ var cmd_shim__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21); -/* harmony import */ var cmd_shim__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(cmd_shim__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(23); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var ncp__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(33); -/* harmony import */ var ncp__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(ncp__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(16); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(29); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_4__); -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - - + function dayOfYearFromWeekInfo(config) { + var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow; -const lstat = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.lstat); -const readFile = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.readFile); -const symlink = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.symlink); -const chmod = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.chmod); -const cmdShim = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(cmd_shim__WEBPACK_IMPORTED_MODULE_0___default.a); -const mkdir = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.mkdir); -const mkdirp = async path => await mkdir(path, { - recursive: true -}); -const unlink = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.unlink); -const copyDirectory = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(ncp__WEBPACK_IMPORTED_MODULE_2__["ncp"]); + w = config._w; + if (w.GG != null || w.W != null || w.E != null) { + dow = 1; + doy = 4; -async function statTest(path, block) { - try { - return block((await lstat(path))); - } catch (e) { - if (e.code === 'ENOENT') { - return false; - } + // TODO: We need to take the current isoWeekYear, but that depends on + // how we interpret now (local, utc, fixed offset). So create + // a now version of current config (take local/utc/offset flags, and + // create now). + weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year); + week = defaults(w.W, 1); + weekday = defaults(w.E, 1); + if (weekday < 1 || weekday > 7) { + weekdayOverflow = true; + } + } else { + dow = config._locale._week.dow; + doy = config._locale._week.doy; - throw e; - } -} -/** - * Test if a path points to a symlink. - * @param path - */ + var curWeek = weekOfYear(createLocal(), dow, doy); + weekYear = defaults(w.gg, config._a[YEAR], curWeek.year); -async function isSymlink(path) { - return await statTest(path, stats => stats.isSymbolicLink()); -} -/** - * Test if a path points to a directory. - * @param path - */ + // Default to current week. + week = defaults(w.w, curWeek.week); -async function isDirectory(path) { - return await statTest(path, stats => stats.isDirectory()); -} -/** - * Test if a path points to a regular file. - * @param path - */ - -async function isFile(path) { - return await statTest(path, stats => stats.isFile()); -} -/** - * Create a symlink at dest that points to src. Adapted from - * https://github.com/lerna/lerna/blob/2f1b87d9e2295f587e4ac74269f714271d8ed428/src/FileSystemUtilities.js#L103. - * - * @param src - * @param dest - * @param type 'dir', 'file', 'junction', or 'exec'. 'exec' on - * windows will use the `cmd-shim` module since symlinks can't be used - * for executable files on windows. - */ - -async function createSymlink(src, dest, type) { - if (process.platform === 'win32') { - if (type === 'exec') { - await cmdShim(src, dest); - } else { - await forceCreate(src, dest, type); + if (w.d != null) { + // weekday -- low day numbers are considered next week + weekday = w.d; + if (weekday < 0 || weekday > 6) { + weekdayOverflow = true; + } + } else if (w.e != null) { + // local weekday -- counting starts from beginning of week + weekday = w.e + dow; + if (w.e < 0 || w.e > 6) { + weekdayOverflow = true; + } + } else { + // default to beginning of week + weekday = dow; + } + } + if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { + getParsingFlags(config)._overflowWeeks = true; + } else if (weekdayOverflow != null) { + getParsingFlags(config)._overflowWeekday = true; + } else { + temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); + config._a[YEAR] = temp.year; + config._dayOfYear = temp.dayOfYear; + } } - } else { - const posixType = type === 'exec' ? 'file' : type; - const relativeSource = Object(path__WEBPACK_IMPORTED_MODULE_3__["relative"])(Object(path__WEBPACK_IMPORTED_MODULE_3__["dirname"])(dest), src); - await forceCreate(relativeSource, dest, posixType); - } -} -async function forceCreate(src, dest, type) { - try { - // If something exists at `dest` we need to remove it first. - await unlink(dest); - } catch (error) { - if (error.code !== 'ENOENT') { - throw error; - } - } + // iso 8601 regex + // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) + var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; + var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; - await symlink(src, dest, type); -} + var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/; -/***/ }), -/* 21 */ -/***/ (function(module, exports, __webpack_require__) { + var isoDates = [ + ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], + ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], + ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], + ['GGGG-[W]WW', /\d{4}-W\d\d/, false], + ['YYYY-DDD', /\d{4}-\d{3}/], + ['YYYY-MM', /\d{4}-\d\d/, false], + ['YYYYYYMMDD', /[+-]\d{10}/], + ['YYYYMMDD', /\d{8}/], + // YYYYMM is NOT allowed by the standard + ['GGGG[W]WWE', /\d{4}W\d{3}/], + ['GGGG[W]WW', /\d{4}W\d{2}/, false], + ['YYYYDDD', /\d{7}/] + ]; -// On windows, create a .cmd file. -// Read the #! in the file to see what it uses. The vast majority -// of the time, this will be either: -// "#!/usr/bin/env " -// or: -// "#! " -// -// Write a binroot/pkg.bin + ".cmd" file that has this line in it: -// @ %~dp0 %* + // iso time formats and regexes + var isoTimes = [ + ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], + ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], + ['HH:mm:ss', /\d\d:\d\d:\d\d/], + ['HH:mm', /\d\d:\d\d/], + ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], + ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], + ['HHmmss', /\d\d\d\d\d\d/], + ['HHmm', /\d\d\d\d/], + ['HH', /\d\d/] + ]; -module.exports = cmdShim -cmdShim.ifExists = cmdShimIfExists + var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; -var fs = __webpack_require__(22) + // date from iso format + function configFromISO(config) { + var i, l, + string = config._i, + match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), + allowTime, dateFormat, timeFormat, tzFormat; -var mkdir = __webpack_require__(31) - , path = __webpack_require__(16) - , toBatchSyntax = __webpack_require__(32) - , shebangExpr = /^#\!\s*(?:\/usr\/bin\/env)?\s*([^ \t]+=[^ \t]+\s+)*\s*([^ \t]+)(.*)$/ + if (match) { + getParsingFlags(config).iso = true; -function cmdShimIfExists (from, to, cb) { - fs.stat(from, function (er) { - if (er) return cb() - cmdShim(from, to, cb) - }) -} + for (i = 0, l = isoDates.length; i < l; i++) { + if (isoDates[i][1].exec(match[1])) { + dateFormat = isoDates[i][0]; + allowTime = isoDates[i][2] !== false; + break; + } + } + if (dateFormat == null) { + config._isValid = false; + return; + } + if (match[3]) { + for (i = 0, l = isoTimes.length; i < l; i++) { + if (isoTimes[i][1].exec(match[3])) { + // match[2] should be 'T' or space + timeFormat = (match[2] || ' ') + isoTimes[i][0]; + break; + } + } + if (timeFormat == null) { + config._isValid = false; + return; + } + } + if (!allowTime && timeFormat != null) { + config._isValid = false; + return; + } + if (match[4]) { + if (tzRegex.exec(match[4])) { + tzFormat = 'Z'; + } else { + config._isValid = false; + return; + } + } + config._f = dateFormat + (timeFormat || '') + (tzFormat || ''); + configFromStringAndFormat(config); + } else { + config._isValid = false; + } + } -// Try to unlink, but ignore errors. -// Any problems will surface later. -function rm (path, cb) { - fs.unlink(path, function(er) { - cb() - }) -} + // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3 + var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/; -function cmdShim (from, to, cb) { - fs.stat(from, function (er, stat) { - if (er) - return cb(er) + function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { + var result = [ + untruncateYear(yearStr), + defaultLocaleMonthsShort.indexOf(monthStr), + parseInt(dayStr, 10), + parseInt(hourStr, 10), + parseInt(minuteStr, 10) + ]; - cmdShim_(from, to, cb) - }) -} + if (secondStr) { + result.push(parseInt(secondStr, 10)); + } -function cmdShim_ (from, to, cb) { - var then = times(2, next, cb) - rm(to, then) - rm(to + ".cmd", then) + return result; + } - function next(er) { - writeShim(from, to, cb) - } -} + function untruncateYear(yearStr) { + var year = parseInt(yearStr, 10); + if (year <= 49) { + return 2000 + year; + } else if (year <= 999) { + return 1900 + year; + } + return year; + } -function writeShim (from, to, cb) { - // make a cmd file and a sh script - // First, check if the bin is a #! of some sort. - // If not, then assume it's something that'll be compiled, or some other - // sort of script, and just call it directly. - mkdir(path.dirname(to), function (er) { - if (er) - return cb(er) - fs.readFile(from, "utf8", function (er, data) { - if (er) return writeShim_(from, to, null, null, cb) - var firstLine = data.trim().split(/\r*\n/)[0] - , shebang = firstLine.match(shebangExpr) - if (!shebang) return writeShim_(from, to, null, null, null, cb) - var vars = shebang[1] || "" - , prog = shebang[2] - , args = shebang[3] || "" - return writeShim_(from, to, prog, args, vars, cb) - }) - }) -} + function preprocessRFC2822(s) { + // Remove comments and folding whitespace and replace multiple-spaces with a single space + return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, ''); + } + + function checkWeekday(weekdayStr, parsedInput, config) { + if (weekdayStr) { + // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check. + var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), + weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay(); + if (weekdayProvided !== weekdayActual) { + getParsingFlags(config).weekdayMismatch = true; + config._isValid = false; + return false; + } + } + return true; + } + var obsOffsets = { + UT: 0, + GMT: 0, + EDT: -4 * 60, + EST: -5 * 60, + CDT: -5 * 60, + CST: -6 * 60, + MDT: -6 * 60, + MST: -7 * 60, + PDT: -7 * 60, + PST: -8 * 60 + }; -function writeShim_ (from, to, prog, args, variables, cb) { - var shTarget = path.relative(path.dirname(to), from) - , target = shTarget.split("/").join("\\") - , longProg - , shProg = prog && prog.split("\\").join("/") - , shLongProg - , pwshProg = shProg && "\"" + shProg + "$exe\"" - , pwshLongProg - shTarget = shTarget.split("\\").join("/") - args = args || "" - variables = variables || "" - if (!prog) { - prog = "\"%~dp0\\" + target + "\"" - shProg = "\"$basedir/" + shTarget + "\"" - pwshProg = shProg - args = "" - target = "" - shTarget = "" - } else { - longProg = "\"%~dp0\\" + prog + ".exe\"" - shLongProg = "\"$basedir/" + prog + "\"" - pwshLongProg = "\"$basedir/" + prog + "$exe\"" - target = "\"%~dp0\\" + target + "\"" - shTarget = "\"$basedir/" + shTarget + "\"" - } + function calculateOffset(obsOffset, militaryOffset, numOffset) { + if (obsOffset) { + return obsOffsets[obsOffset]; + } else if (militaryOffset) { + // the only allowed military tz is Z + return 0; + } else { + var hm = parseInt(numOffset, 10); + var m = hm % 100, h = (hm - m) / 100; + return h * 60 + m; + } + } - // @SETLOCAL - // - // @IF EXIST "%~dp0\node.exe" ( - // @SET "_prog=%~dp0\node.exe" - // ) ELSE ( - // @SET "_prog=node" - // @SET PATHEXT=%PATHEXT:;.JS;=;% - // ) - // - // "%_prog%" "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* - // @ENDLOCAL - var cmd - if (longProg) { - shLongProg = shLongProg.trim(); - args = args.trim(); - var variableDeclarationsAsBatch = toBatchSyntax.convertToSetCommands(variables) - cmd = "@SETLOCAL\r\n" - + variableDeclarationsAsBatch - + "\r\n" - + "@IF EXIST " + longProg + " (\r\n" - + " @SET \"_prog=" + longProg.replace(/(^")|("$)/g, '') + "\"\r\n" - + ") ELSE (\r\n" - + " @SET \"_prog=" + prog.replace(/(^")|("$)/g, '') + "\"\r\n" - + " @SET PATHEXT=%PATHEXT:;.JS;=;%\r\n" - + ")\r\n" - + "\r\n" - + "\"%_prog%\" " + args + " " + target + " %*\r\n" - + '@ENDLOCAL\r\n' - } else { - cmd = "@" + prog + " " + args + " " + target + " %*\r\n" - } + // date and time from ref 2822 format + function configFromRFC2822(config) { + var match = rfc2822.exec(preprocessRFC2822(config._i)); + if (match) { + var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]); + if (!checkWeekday(match[1], parsedArray, config)) { + return; + } - // #!/bin/sh - // basedir=`dirname "$0"` - // - // case `uname` in - // *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; - // esac - // - // if [ -x "$basedir/node.exe" ]; then - // "$basedir/node.exe" "$basedir/node_modules/npm/bin/npm-cli.js" "$@" - // ret=$? - // else - // node "$basedir/node_modules/npm/bin/npm-cli.js" "$@" - // ret=$? - // fi - // exit $ret + config._a = parsedArray; + config._tzm = calculateOffset(match[8], match[9], match[10]); - var sh = "#!/bin/sh\n" + config._d = createUTCDate.apply(null, config._a); + config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); - sh = sh - + "basedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\")\n" - + "\n" - + "case `uname` in\n" - + " *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w \"$basedir\"`;;\n" - + "esac\n" - + "\n" + getParsingFlags(config).rfc2822 = true; + } else { + config._isValid = false; + } + } - if (shLongProg) { - sh = sh - + "if [ -x "+shLongProg+" ]; then\n" - + " " + variables + shLongProg + " " + args + " " + shTarget + " \"$@\"\n" - + " ret=$?\n" - + "else \n" - + " " + variables + shProg + " " + args + " " + shTarget + " \"$@\"\n" - + " ret=$?\n" - + "fi\n" - + "exit $ret\n" - } else { - sh = sh - + shProg + " " + args + " " + shTarget + " \"$@\"\n" - + "exit $?\n" - } + // date from iso format or fallback + function configFromString(config) { + var matched = aspNetJsonRegex.exec(config._i); - // #!/usr/bin/env pwsh - // $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent - // - // $ret=0 - // $exe = "" - // if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { - // # Fix case when both the Windows and Linux builds of Node - // # are installed in the same directory - // $exe = ".exe" - // } - // if (Test-Path "$basedir/node") { - // & "$basedir/node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args - // $ret=$LASTEXITCODE - // } else { - // & "node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args - // $ret=$LASTEXITCODE - // } - // exit $ret - var pwsh = "#!/usr/bin/env pwsh\n" - + "$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent\n" - + "\n" - + "$exe=\"\"\n" - + "if ($PSVersionTable.PSVersion -lt \"6.0\" -or $IsWindows) {\n" - + " # Fix case when both the Windows and Linux builds of Node\n" - + " # are installed in the same directory\n" - + " $exe=\".exe\"\n" - + "}\n" - if (shLongProg) { - pwsh = pwsh - + "$ret=0\n" - + "if (Test-Path " + pwshLongProg + ") {\n" - + " & " + pwshLongProg + " " + args + " " + shTarget + " $args\n" - + " $ret=$LASTEXITCODE\n" - + "} else {\n" - + " & " + pwshProg + " " + args + " " + shTarget + " $args\n" - + " $ret=$LASTEXITCODE\n" - + "}\n" - + "exit $ret\n" - } else { - pwsh = pwsh - + "& " + pwshProg + " " + args + " " + shTarget + " $args\n" - + "exit $LASTEXITCODE\n" - } + if (matched !== null) { + config._d = new Date(+matched[1]); + return; + } - var then = times(3, next, cb) - fs.writeFile(to + ".ps1", pwsh, "utf8", then) - fs.writeFile(to + ".cmd", cmd, "utf8", then) - fs.writeFile(to, sh, "utf8", then) - function next () { - chmodShim(to, cb) - } -} + configFromISO(config); + if (config._isValid === false) { + delete config._isValid; + } else { + return; + } -function chmodShim (to, cb) { - var then = times(2, cb, cb) - fs.chmod(to, "0755", then) - fs.chmod(to + ".cmd", "0755", then) - fs.chmod(to + ".ps1", "0755", then) -} + configFromRFC2822(config); + if (config._isValid === false) { + delete config._isValid; + } else { + return; + } -function times(n, ok, cb) { - var errState = null - return function(er) { - if (!errState) { - if (er) - cb(errState = er) - else if (--n === 0) - ok() + // Final attempt, use Input Fallback + hooks.createFromInputFallback(config); } - } -} + hooks.createFromInputFallback = deprecate( + 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' + + 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' + + 'discouraged and will be removed in an upcoming major release. Please refer to ' + + 'http://momentjs.com/guides/#/warnings/js-date/ for more info.', + function (config) { + config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); + } + ); -/***/ }), -/* 22 */ -/***/ (function(module, exports, __webpack_require__) { + // constant that refers to the ISO standard + hooks.ISO_8601 = function () {}; -var fs = __webpack_require__(23) -var polyfills = __webpack_require__(24) -var legacy = __webpack_require__(26) -var clone = __webpack_require__(28) + // constant that refers to the RFC 2822 form + hooks.RFC_2822 = function () {}; -var util = __webpack_require__(29) + // date from string and format string + function configFromStringAndFormat(config) { + // TODO: Move this to another part of the creation flow to prevent circular deps + if (config._f === hooks.ISO_8601) { + configFromISO(config); + return; + } + if (config._f === hooks.RFC_2822) { + configFromRFC2822(config); + return; + } + config._a = []; + getParsingFlags(config).empty = true; -/* istanbul ignore next - node 0.x polyfill */ -var gracefulQueue -var previousSymbol - -/* istanbul ignore else - node 0.x polyfill */ -if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { - gracefulQueue = Symbol.for('graceful-fs.queue') - // This is used in testing by future versions - previousSymbol = Symbol.for('graceful-fs.previous') -} else { - gracefulQueue = '___graceful-fs.queue' - previousSymbol = '___graceful-fs.previous' -} + // This array is used to make a Date, either with `new Date` or `Date.UTC` + var string = '' + config._i, + i, parsedInput, tokens, token, skipped, + stringLength = string.length, + totalParsedInputLength = 0; -function noop () {} + tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; -var debug = noop -if (util.debuglog) - debug = util.debuglog('gfs4') -else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) - debug = function() { - var m = util.format.apply(util, arguments) - m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') - console.error(m) - } + for (i = 0; i < tokens.length; i++) { + token = tokens[i]; + parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; + // console.log('token', token, 'parsedInput', parsedInput, + // 'regex', getParseRegexForToken(token, config)); + if (parsedInput) { + skipped = string.substr(0, string.indexOf(parsedInput)); + if (skipped.length > 0) { + getParsingFlags(config).unusedInput.push(skipped); + } + string = string.slice(string.indexOf(parsedInput) + parsedInput.length); + totalParsedInputLength += parsedInput.length; + } + // don't parse if it's not a known token + if (formatTokenFunctions[token]) { + if (parsedInput) { + getParsingFlags(config).empty = false; + } + else { + getParsingFlags(config).unusedTokens.push(token); + } + addTimeToArrayFromToken(token, parsedInput, config); + } + else if (config._strict && !parsedInput) { + getParsingFlags(config).unusedTokens.push(token); + } + } -// Once time initialization -if (!global[gracefulQueue]) { - // This queue can be shared by multiple loaded instances - var queue = [] - Object.defineProperty(global, gracefulQueue, { - get: function() { - return queue - } - }) + // add remaining unparsed input length to the string + getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength; + if (string.length > 0) { + getParsingFlags(config).unusedInput.push(string); + } - // Patch fs.close/closeSync to shared queue version, because we need - // to retry() whenever a close happens *anywhere* in the program. - // This is essential when multiple graceful-fs instances are - // in play at the same time. - fs.close = (function (fs$close) { - function close (fd, cb) { - return fs$close.call(fs, fd, function (err) { - // This function uses the graceful-fs shared queue - if (!err) { - retry() + // clear _12h flag if hour is <= 12 + if (config._a[HOUR] <= 12 && + getParsingFlags(config).bigHour === true && + config._a[HOUR] > 0) { + getParsingFlags(config).bigHour = undefined; } - if (typeof cb === 'function') - cb.apply(this, arguments) - }) + getParsingFlags(config).parsedDateParts = config._a.slice(0); + getParsingFlags(config).meridiem = config._meridiem; + // handle meridiem + config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem); + + configFromArray(config); + checkOverflow(config); } - Object.defineProperty(close, previousSymbol, { - value: fs$close - }) - return close - })(fs.close) - fs.closeSync = (function (fs$closeSync) { - function closeSync (fd) { - // This function uses the graceful-fs shared queue - fs$closeSync.apply(fs, arguments) - retry() + function meridiemFixWrap (locale, hour, meridiem) { + var isPm; + + if (meridiem == null) { + // nothing to do + return hour; + } + if (locale.meridiemHour != null) { + return locale.meridiemHour(hour, meridiem); + } else if (locale.isPM != null) { + // Fallback + isPm = locale.isPM(meridiem); + if (isPm && hour < 12) { + hour += 12; + } + if (!isPm && hour === 12) { + hour = 0; + } + return hour; + } else { + // this is not supposed to happen + return hour; + } } - Object.defineProperty(closeSync, previousSymbol, { - value: fs$closeSync - }) - return closeSync - })(fs.closeSync) + // date from string and array of format strings + function configFromStringAndArray(config) { + var tempConfig, + bestMoment, - if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug(global[gracefulQueue]) - __webpack_require__(30).equal(global[gracefulQueue].length, 0) - }) - } -} + scoreToBeat, + i, + currentScore; -module.exports = patch(clone(fs)) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { - module.exports = patch(fs) - fs.__patched = true; -} + if (config._f.length === 0) { + getParsingFlags(config).invalidFormat = true; + config._d = new Date(NaN); + return; + } -function patch (fs) { - // Everything that references the open() function needs to be in here - polyfills(fs) - fs.gracefulify = patch + for (i = 0; i < config._f.length; i++) { + currentScore = 0; + tempConfig = copyConfig({}, config); + if (config._useUTC != null) { + tempConfig._useUTC = config._useUTC; + } + tempConfig._f = config._f[i]; + configFromStringAndFormat(tempConfig); - fs.createReadStream = createReadStream - fs.createWriteStream = createWriteStream - var fs$readFile = fs.readFile - fs.readFile = readFile - function readFile (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null + if (!isValid(tempConfig)) { + continue; + } - return go$readFile(path, options, cb) + // if there is any input that was not parsed add a penalty for that format + currentScore += getParsingFlags(tempConfig).charsLeftOver; - function go$readFile (path, options, cb) { - return fs$readFile(path, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readFile, [path, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() + //or tokens + currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; + + getParsingFlags(tempConfig).score = currentScore; + + if (scoreToBeat == null || currentScore < scoreToBeat) { + scoreToBeat = currentScore; + bestMoment = tempConfig; + } } - }) + + extend(config, bestMoment || tempConfig); } - } - var fs$writeFile = fs.writeFile - fs.writeFile = writeFile - function writeFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null + function configFromObject(config) { + if (config._d) { + return; + } - return go$writeFile(path, data, options, cb) + var i = normalizeObjectUnits(config._i); + config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) { + return obj && parseInt(obj, 10); + }); - function go$writeFile (path, data, options, cb) { - return fs$writeFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$writeFile, [path, data, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() + configFromArray(config); + } + + function createFromConfig (config) { + var res = new Moment(checkOverflow(prepareConfig(config))); + if (res._nextDay) { + // Adding is smart enough around DST + res.add(1, 'd'); + res._nextDay = undefined; } - }) + + return res; } - } - var fs$appendFile = fs.appendFile - if (fs$appendFile) - fs.appendFile = appendFile - function appendFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null + function prepareConfig (config) { + var input = config._i, + format = config._f; - return go$appendFile(path, data, options, cb) + config._locale = config._locale || getLocale(config._l); - function go$appendFile (path, data, options, cb) { - return fs$appendFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$appendFile, [path, data, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() + if (input === null || (format === undefined && input === '')) { + return createInvalid({nullInput: true}); } - }) - } - } - - var fs$readdir = fs.readdir - fs.readdir = readdir - function readdir (path, options, cb) { - var args = [path] - if (typeof options !== 'function') { - args.push(options) - } else { - cb = options - } - args.push(go$readdir$cb) - return go$readdir(args) + if (typeof input === 'string') { + config._i = input = config._locale.preparse(input); + } - function go$readdir$cb (err, files) { - if (files && files.sort) - files.sort() + if (isMoment(input)) { + return new Moment(checkOverflow(input)); + } else if (isDate(input)) { + config._d = input; + } else if (isArray(format)) { + configFromStringAndArray(config); + } else if (format) { + configFromStringAndFormat(config); + } else { + configFromInput(config); + } - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readdir, [args]]) + if (!isValid(config)) { + config._d = null; + } - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } + return config; } - } - function go$readdir (args) { - return fs$readdir.apply(fs, args) - } + function configFromInput(config) { + var input = config._i; + if (isUndefined(input)) { + config._d = new Date(hooks.now()); + } else if (isDate(input)) { + config._d = new Date(input.valueOf()); + } else if (typeof input === 'string') { + configFromString(config); + } else if (isArray(input)) { + config._a = map(input.slice(0), function (obj) { + return parseInt(obj, 10); + }); + configFromArray(config); + } else if (isObject(input)) { + configFromObject(config); + } else if (isNumber(input)) { + // from milliseconds + config._d = new Date(input); + } else { + hooks.createFromInputFallback(config); + } + } - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs) - ReadStream = legStreams.ReadStream - WriteStream = legStreams.WriteStream - } + function createLocalOrUTC (input, format, locale, strict, isUTC) { + var c = {}; - var fs$ReadStream = fs.ReadStream - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open - } + if (locale === true || locale === false) { + strict = locale; + locale = undefined; + } - var fs$WriteStream = fs.WriteStream - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype) - WriteStream.prototype.open = WriteStream$open - } + if ((isObject(input) && isObjectEmpty(input)) || + (isArray(input) && input.length === 0)) { + input = undefined; + } + // object construction must be done this way. + // https://github.com/moment/moment/issues/1423 + c._isAMomentObject = true; + c._useUTC = c._isUTC = isUTC; + c._l = locale; + c._i = input; + c._f = format; + c._strict = strict; - Object.defineProperty(fs, 'ReadStream', { - get: function () { - return ReadStream - }, - set: function (val) { - ReadStream = val - }, - enumerable: true, - configurable: true - }) - Object.defineProperty(fs, 'WriteStream', { - get: function () { - return WriteStream - }, - set: function (val) { - WriteStream = val - }, - enumerable: true, - configurable: true - }) + return createFromConfig(c); + } - // legacy names - var FileReadStream = ReadStream - Object.defineProperty(fs, 'FileReadStream', { - get: function () { - return FileReadStream - }, - set: function (val) { - FileReadStream = val - }, - enumerable: true, - configurable: true - }) - var FileWriteStream = WriteStream - Object.defineProperty(fs, 'FileWriteStream', { - get: function () { - return FileWriteStream - }, - set: function (val) { - FileWriteStream = val - }, - enumerable: true, - configurable: true - }) + function createLocal (input, format, locale, strict) { + return createLocalOrUTC(input, format, locale, strict, false); + } - function ReadStream (path, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments) - } + var prototypeMin = deprecate( + 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', + function () { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other < this ? this : other; + } else { + return createInvalid(); + } + } + ); - function ReadStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - if (that.autoClose) - that.destroy() + var prototypeMax = deprecate( + 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', + function () { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other > this ? this : other; + } else { + return createInvalid(); + } + } + ); - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - that.read() - } - }) - } + // Pick a moment m from moments so that m[fn](other) is true for all + // other. This relies on the function fn to be transitive. + // + // moments should either be an array of moment objects or an array, whose + // first element is an array of moment objects. + function pickBy(fn, moments) { + var res, i; + if (moments.length === 1 && isArray(moments[0])) { + moments = moments[0]; + } + if (!moments.length) { + return createLocal(); + } + res = moments[0]; + for (i = 1; i < moments.length; ++i) { + if (!moments[i].isValid() || moments[i][fn](res)) { + res = moments[i]; + } + } + return res; + } - function WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } + // TODO: Use [].sort instead? + function min () { + var args = [].slice.call(arguments, 0); - function WriteStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - that.destroy() - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - } - }) - } + return pickBy('isBefore', args); + } - function createReadStream (path, options) { - return new fs.ReadStream(path, options) - } + function max () { + var args = [].slice.call(arguments, 0); - function createWriteStream (path, options) { - return new fs.WriteStream(path, options) - } + return pickBy('isAfter', args); + } - var fs$open = fs.open - fs.open = open - function open (path, flags, mode, cb) { - if (typeof mode === 'function') - cb = mode, mode = null + var now = function () { + return Date.now ? Date.now() : +(new Date()); + }; - return go$open(path, flags, mode, cb) + var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond']; - function go$open (path, flags, mode, cb) { - return fs$open(path, flags, mode, function (err, fd) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$open, [path, flags, mode, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() + function isDurationValid(m) { + for (var key in m) { + if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) { + return false; + } } - }) - } - } - return fs -} + var unitHasDecimal = false; + for (var i = 0; i < ordering.length; ++i) { + if (m[ordering[i]]) { + if (unitHasDecimal) { + return false; // only allow non-integers for smallest unit + } + if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) { + unitHasDecimal = true; + } + } + } -function enqueue (elem) { - debug('ENQUEUE', elem[0].name, elem[1]) - global[gracefulQueue].push(elem) -} + return true; + } -function retry () { - var elem = global[gracefulQueue].shift() - if (elem) { - debug('RETRY', elem[0].name, elem[1]) - elem[0].apply(null, elem[1]) - } -} + function isValid$1() { + return this._isValid; + } + function createInvalid$1() { + return createDuration(NaN); + } -/***/ }), -/* 23 */ -/***/ (function(module, exports) { + function Duration (duration) { + var normalizedInput = normalizeObjectUnits(duration), + years = normalizedInput.year || 0, + quarters = normalizedInput.quarter || 0, + months = normalizedInput.month || 0, + weeks = normalizedInput.week || normalizedInput.isoWeek || 0, + days = normalizedInput.day || 0, + hours = normalizedInput.hour || 0, + minutes = normalizedInput.minute || 0, + seconds = normalizedInput.second || 0, + milliseconds = normalizedInput.millisecond || 0; -module.exports = require("fs"); + this._isValid = isDurationValid(normalizedInput); -/***/ }), -/* 24 */ -/***/ (function(module, exports, __webpack_require__) { + // representation for dateAddRemove + this._milliseconds = +milliseconds + + seconds * 1e3 + // 1000 + minutes * 6e4 + // 1000 * 60 + hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978 + // Because of dateAddRemove treats 24 hours as different from a + // day when working around DST, we need to store them separately + this._days = +days + + weeks * 7; + // It is impossible to translate months into days without knowing + // which months you are are talking about, so we have to store + // it separately. + this._months = +months + + quarters * 3 + + years * 12; -var constants = __webpack_require__(25) + this._data = {}; -var origCwd = process.cwd -var cwd = null + this._locale = getLocale(); -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform + this._bubble(); + } -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd -} -try { - process.cwd() -} catch (er) {} + function isDuration (obj) { + return obj instanceof Duration; + } -var chdir = process.chdir -process.chdir = function(d) { - cwd = null - chdir.call(process, d) -} + function absRound (number) { + if (number < 0) { + return Math.round(-1 * number) * -1; + } else { + return Math.round(number); + } + } -module.exports = patch + // FORMATTING -function patch (fs) { - // (re-)implement some things that are known busted or missing. + function offset (token, separator) { + addFormatToken(token, 0, 0, function () { + var offset = this.utcOffset(); + var sign = '+'; + if (offset < 0) { + offset = -offset; + sign = '-'; + } + return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2); + }); + } - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs) - } + offset('Z', ':'); + offset('ZZ', ''); - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) - } + // PARSING - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. + addRegexToken('Z', matchShortOffset); + addRegexToken('ZZ', matchShortOffset); + addParseToken(['Z', 'ZZ'], function (input, array, config) { + config._useUTC = true; + config._tzm = offsetFromString(matchShortOffset, input); + }); - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) + // HELPERS - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) + // timezone chunker + // '+10:00' > ['10', '00'] + // '-1530' > ['-15', '30'] + var chunkOffset = /([\+\-]|\d\d)/gi; - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) + function offsetFromString(matcher, string) { + var matches = (string || '').match(matcher); - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) + if (matches === null) { + return null; + } - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) + var chunk = matches[matches.length - 1] || []; + var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; + var minutes = +(parts[1] * 60) + toInt(parts[2]); - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) + return minutes === 0 ? + 0 : + parts[0] === '+' ? minutes : -minutes; + } - // if lchmod/lchown do not exist, then make them no-ops - if (!fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb) + // Return a moment from input, that is local/utc/zone equivalent to model. + function cloneWithOffset(input, model) { + var res, diff; + if (model._isUTC) { + res = model.clone(); + diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(); + // Use low-level api, because this fn is low-level api. + res._d.setTime(res._d.valueOf() + diff); + hooks.updateOffset(res, false); + return res; + } else { + return createLocal(input).local(); + } } - fs.lchmodSync = function () {} - } - if (!fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) + + function getDateOffset (m) { + // On Firefox.24 Date#getTimezoneOffset returns a floating point. + // https://github.com/moment/moment/pull/1871 + return -Math.round(m._d.getTimezoneOffset() / 15) * 15; } - fs.lchownSync = function () {} - } - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. + // HOOKS - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform === "win32") { - fs.rename = (function (fs$rename) { return function (from, to, cb) { - var start = Date.now() - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er) - }) - }, backoff) - if (backoff < 100) - backoff += 10; - return; - } - if (cb) cb(er) - }) - }})(fs.rename) - } + // This function will be called whenever a moment is mutated. + // It is intended to keep the offset in sync with the timezone. + hooks.updateOffset = function () {}; - // if read() returns EAGAIN, then just try it again. - fs.read = (function (fs$read) { - function read (fd, buffer, offset, length, position, callback_) { - var callback - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0 - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - callback_.apply(this, arguments) + // MOMENTS + + // keepLocalTime = true means only change the timezone, without + // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> + // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset + // +0200, so we adjust the time as needed, to be valid. + // + // Keeping the time actually adds/subtracts (one hour) + // from the actual represented time. That is why we call updateOffset + // a second time. In case it wants us to change the offset again + // _changeInProgress == true case, then we have to adjust, because + // there is no such time in the given timezone. + function getSetOffset (input, keepLocalTime, keepMinutes) { + var offset = this._offset || 0, + localAdjust; + if (!this.isValid()) { + return input != null ? this : NaN; + } + if (input != null) { + if (typeof input === 'string') { + input = offsetFromString(matchShortOffset, input); + if (input === null) { + return this; + } + } else if (Math.abs(input) < 16 && !keepMinutes) { + input = input * 60; + } + if (!this._isUTC && keepLocalTime) { + localAdjust = getDateOffset(this); + } + this._offset = input; + this._isUTC = true; + if (localAdjust != null) { + this.add(localAdjust, 'm'); + } + if (offset !== input) { + if (!keepLocalTime || this._changeInProgress) { + addSubtract(this, createDuration(input - offset, 'm'), 1, false); + } else if (!this._changeInProgress) { + this._changeInProgress = true; + hooks.updateOffset(this, true); + this._changeInProgress = null; + } + } + return this; + } else { + return this._isUTC ? offset : getDateOffset(this); } - } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) } - // This ensures `util.promisify` works as it does for native `fs.read`. - read.__proto__ = fs$read - return read - })(fs.read) + function getSetZone (input, keepLocalTime) { + if (input != null) { + if (typeof input !== 'string') { + input = -input; + } - fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0 - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - continue + this.utcOffset(input, keepLocalTime); + + return this; + } else { + return -this.utcOffset(); } - throw er - } } - }})(fs.readSync) - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return - } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) + function setOffsetToUTC (keepLocalTime) { + return this.utcOffset(0, keepLocalTime); } - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + function setOffsetToLocal (keepLocalTime) { + if (this._isUTC) { + this.utcOffset(0, keepLocalTime); + this._isUTC = false; - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) + if (keepLocalTime) { + this.subtract(getDateOffset(this), 'm'); + } } - } - return ret + return this; } - } - function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK")) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) - }) - }) - }) - } + function setOffsetToParsedOffset () { + if (this._tzm != null) { + this.utcOffset(this._tzm, false, true); + } else if (typeof this._i === 'string') { + var tZone = offsetFromString(matchOffset, this._i); + if (tZone != null) { + this.utcOffset(tZone); + } + else { + this.utcOffset(0, true); + } + } + return this; + } - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret - var threw = true - try { - ret = fs.futimesSync(fd, at, mt) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } + function hasAlignedHourOffset (input) { + if (!this.isValid()) { + return false; } - return ret - } + input = input ? createLocal(input).utcOffset() : 0; - } else { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} + return (this.utcOffset() - input) % 60 === 0; } - } - function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) + function isDaylightSavingTime () { + return ( + this.utcOffset() > this.clone().month(0).utcOffset() || + this.utcOffset() > this.clone().month(5).utcOffset() + ); } - } - function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er - } + function isDaylightSavingTimeShifted () { + if (!isUndefined(this._isDSTShifted)) { + return this._isDSTShifted; + } + + var c = {}; + + copyConfig(c, this); + c = prepareConfig(c); + + if (c._a) { + var other = c._isUTC ? createUTC(c._a) : createLocal(c._a); + this._isDSTShifted = this.isValid() && + compareArrays(c._a, other.toArray()) > 0; + } else { + this._isDSTShifted = false; + } + + return this._isDSTShifted; } - } + function isLocal () { + return this.isValid() ? !this._isUTC : false; + } - function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) + function isUtcOffset () { + return this.isValid() ? this._isUTC : false; } - } - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er - } + function isUtc () { + return this.isValid() ? this._isUTC && this._offset === 0 : false; } - } - function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } - function callback (er, stats) { - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - if (cb) cb.apply(this, arguments) - } - return options ? orig.call(fs, target, options, callback) - : orig.call(fs, target, callback) - } - } - - function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options) { - var stats = options ? orig.call(fs, target, options) - : orig.call(fs, target) - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - return stats; - } - } + // ASP.NET json date format regex + var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/; - // ENOSYS means that the fs doesn't support the op. Just ignore - // that, because it doesn't matter. - // - // if there's no getuid, or if getuid() is something other - // than 0, and the error is EINVAL or EPERM, then just ignore - // it. - // - // This specific case is a silent failure in cp, install, tar, - // and most other unix tools that manage permissions. - // - // When running as root, or if other types of errors are - // encountered, then it's strict. - function chownErOk (er) { - if (!er) - return true + // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html + // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere + // and further modified to allow for strings containing both week and day + var isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; - if (er.code === "ENOSYS") - return true + function createDuration (input, key) { + var duration = input, + // matching against regexp is expensive, do it on demand + match = null, + sign, + ret, + diffRes; - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true - } + if (isDuration(input)) { + duration = { + ms : input._milliseconds, + d : input._days, + M : input._months + }; + } else if (isNumber(input)) { + duration = {}; + if (key) { + duration[key] = input; + } else { + duration.milliseconds = input; + } + } else if (!!(match = aspNetRegex.exec(input))) { + sign = (match[1] === '-') ? -1 : 1; + duration = { + y : 0, + d : toInt(match[DATE]) * sign, + h : toInt(match[HOUR]) * sign, + m : toInt(match[MINUTE]) * sign, + s : toInt(match[SECOND]) * sign, + ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match + }; + } else if (!!(match = isoRegex.exec(input))) { + sign = (match[1] === '-') ? -1 : 1; + duration = { + y : parseIso(match[2], sign), + M : parseIso(match[3], sign), + w : parseIso(match[4], sign), + d : parseIso(match[5], sign), + h : parseIso(match[6], sign), + m : parseIso(match[7], sign), + s : parseIso(match[8], sign) + }; + } else if (duration == null) {// checks for null or undefined + duration = {}; + } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { + diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to)); - return false - } -} + duration = {}; + duration.ms = diffRes.milliseconds; + duration.M = diffRes.months; + } + ret = new Duration(duration); -/***/ }), -/* 25 */ -/***/ (function(module, exports) { + if (isDuration(input) && hasOwnProp(input, '_locale')) { + ret._locale = input._locale; + } -module.exports = require("constants"); + return ret; + } -/***/ }), -/* 26 */ -/***/ (function(module, exports, __webpack_require__) { + createDuration.fn = Duration.prototype; + createDuration.invalid = createInvalid$1; -var Stream = __webpack_require__(27).Stream + function parseIso (inp, sign) { + // We'd normally use ~~inp for this, but unfortunately it also + // converts floats to ints. + // inp may be undefined, so careful calling replace on it. + var res = inp && parseFloat(inp.replace(',', '.')); + // apply sign while we're at it + return (isNaN(res) ? 0 : res) * sign; + } -module.exports = legacy + function positiveMomentsDifference(base, other) { + var res = {}; -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream - } + res.months = other.month() - base.month() + + (other.year() - base.year()) * 12; + if (base.clone().add(res.months, 'M').isAfter(other)) { + --res.months; + } - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); + res.milliseconds = +other - +(base.clone().add(res.months, 'M')); - Stream.call(this); + return res; + } - var self = this; + function momentsDifference(base, other) { + var res; + if (!(base.isValid() && other.isValid())) { + return {milliseconds: 0, months: 0}; + } - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; + other = cloneWithOffset(other, base); + if (base.isBefore(other)) { + res = positiveMomentsDifference(base, other); + } else { + res = positiveMomentsDifference(other, base); + res.milliseconds = -res.milliseconds; + res.months = -res.months; + } - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; + return res; + } - options = options || {}; + // TODO: remove 'name' arg after deprecation is removed + function createAdder(direction, name) { + return function (val, period) { + var dur, tmp; + //invert the arguments, but complain about it + if (period !== null && !isNaN(+period)) { + deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' + + 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'); + tmp = val; val = period; period = tmp; + } - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; + val = typeof val === 'string' ? +val : val; + dur = createDuration(val, period); + addSubtract(this, dur, direction); + return this; + }; } - if (this.encoding) this.setEncoding(this.encoding); - - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); - } + function addSubtract (mom, duration, isAdding, updateOffset) { + var milliseconds = duration._milliseconds, + days = absRound(duration._days), + months = absRound(duration._months); - if (this.start > this.end) { - throw new Error('start must be <= end'); - } + if (!mom.isValid()) { + // No op + return; + } - this.pos = this.start; - } + updateOffset = updateOffset == null ? true : updateOffset; - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; + if (months) { + setMonth(mom, get(mom, 'Month') + months * isAdding); + } + if (days) { + set$1(mom, 'Date', get(mom, 'Date') + days * isAdding); + } + if (milliseconds) { + mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding); + } + if (updateOffset) { + hooks.updateOffset(mom, days || months); + } } - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; - } + var add = createAdder(1, 'add'); + var subtract = createAdder(-1, 'subtract'); - self.fd = fd; - self.emit('open', fd); - self._read(); - }) - } + function getCalendarFormat(myMoment, now) { + var diff = myMoment.diff(now, 'days', true); + return diff < -6 ? 'sameElse' : + diff < -1 ? 'lastWeek' : + diff < 0 ? 'lastDay' : + diff < 1 ? 'sameDay' : + diff < 2 ? 'nextDay' : + diff < 7 ? 'nextWeek' : 'sameElse'; + } - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); + function calendar$1 (time, formats) { + // We want to compare the start of today, vs this. + // Getting start-of-today depends on whether we're local/utc/offset or not. + var now = time || createLocal(), + sod = cloneWithOffset(now, this).startOf('day'), + format = hooks.calendarFormat(this, sod) || 'sameElse'; - Stream.call(this); + var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]); - this.path = path; - this.fd = null; - this.writable = true; + return this.format(output || this.localeData().calendar(format, this, createLocal(now))); + } - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; + function clone () { + return new Moment(this); + } - options = options || {}; + function isAfter (input, units) { + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || 'millisecond'; + if (units === 'millisecond') { + return this.valueOf() > localInput.valueOf(); + } else { + return localInput.valueOf() < this.clone().startOf(units).valueOf(); + } + } - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; + function isBefore (input, units) { + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || 'millisecond'; + if (units === 'millisecond') { + return this.valueOf() < localInput.valueOf(); + } else { + return this.clone().endOf(units).valueOf() < localInput.valueOf(); + } } - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } + function isBetween (from, to, units, inclusivity) { + var localFrom = isMoment(from) ? from : createLocal(from), + localTo = isMoment(to) ? to : createLocal(to); + if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) { + return false; + } + inclusivity = inclusivity || '()'; + return (inclusivity[0] === '(' ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && + (inclusivity[1] === ')' ? this.isBefore(localTo, units) : !this.isAfter(localTo, units)); + } - this.pos = this.start; + function isSame (input, units) { + var localInput = isMoment(input) ? input : createLocal(input), + inputMs; + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || 'millisecond'; + if (units === 'millisecond') { + return this.valueOf() === localInput.valueOf(); + } else { + inputMs = localInput.valueOf(); + return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf(); + } } - this.busy = false; - this._queue = []; + function isSameOrAfter (input, units) { + return this.isSame(input, units) || this.isAfter(input, units); + } - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); + function isSameOrBefore (input, units) { + return this.isSame(input, units) || this.isBefore(input, units); } - } -} + function diff (input, units, asFloat) { + var that, + zoneDelta, + output; -/***/ }), -/* 27 */ -/***/ (function(module, exports) { + if (!this.isValid()) { + return NaN; + } -module.exports = require("stream"); + that = cloneWithOffset(input, this); -/***/ }), -/* 28 */ -/***/ (function(module, exports, __webpack_require__) { + if (!that.isValid()) { + return NaN; + } -"use strict"; + zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; + units = normalizeUnits(units); -module.exports = clone + switch (units) { + case 'year': output = monthDiff(this, that) / 12; break; + case 'month': output = monthDiff(this, that); break; + case 'quarter': output = monthDiff(this, that) / 3; break; + case 'second': output = (this - that) / 1e3; break; // 1000 + case 'minute': output = (this - that) / 6e4; break; // 1000 * 60 + case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60 + case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst + case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst + default: output = this - that; + } -function clone (obj) { - if (obj === null || typeof obj !== 'object') - return obj + return asFloat ? output : absFloor(output); + } - if (obj instanceof Object) - var copy = { __proto__: obj.__proto__ } - else - var copy = Object.create(null) + function monthDiff (a, b) { + // difference in months + var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()), + // b is in (anchor - 1 month, anchor + 1 month) + anchor = a.clone().add(wholeMonthDiff, 'months'), + anchor2, adjust; - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) - }) + if (b - anchor < 0) { + anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); + // linear across the month + adjust = (b - anchor) / (anchor - anchor2); + } else { + anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); + // linear across the month + adjust = (b - anchor) / (anchor2 - anchor); + } - return copy -} + //check for negative zero, return zero if negative zero + return -(wholeMonthDiff + adjust) || 0; + } + hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; + hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]'; -/***/ }), -/* 29 */ -/***/ (function(module, exports) { + function toString () { + return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); + } -module.exports = require("util"); + function toISOString(keepOffset) { + if (!this.isValid()) { + return null; + } + var utc = keepOffset !== true; + var m = utc ? this.clone().utc() : this; + if (m.year() < 0 || m.year() > 9999) { + return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'); + } + if (isFunction(Date.prototype.toISOString)) { + // native implementation is ~50x faster, use it when we can + if (utc) { + return this.toDate().toISOString(); + } else { + return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z')); + } + } + return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'); + } -/***/ }), -/* 30 */ -/***/ (function(module, exports) { + /** + * Return a human readable representation of a moment that can + * also be evaluated to get a new moment which is the same + * + * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects + */ + function inspect () { + if (!this.isValid()) { + return 'moment.invalid(/* ' + this._i + ' */)'; + } + var func = 'moment'; + var zone = ''; + if (!this.isLocal()) { + func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone'; + zone = 'Z'; + } + var prefix = '[' + func + '("]'; + var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY'; + var datetime = '-MM-DD[T]HH:mm:ss.SSS'; + var suffix = zone + '[")]'; -module.exports = require("assert"); + return this.format(prefix + year + datetime + suffix); + } -/***/ }), -/* 31 */ -/***/ (function(module, exports, __webpack_require__) { + function format (inputString) { + if (!inputString) { + inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat; + } + var output = formatMoment(this, inputString); + return this.localeData().postformat(output); + } -var path = __webpack_require__(16); -var fs = __webpack_require__(23); -var _0777 = parseInt('0777', 8); + function from (time, withoutSuffix) { + if (this.isValid() && + ((isMoment(time) && time.isValid()) || + createLocal(time).isValid())) { + return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); + } else { + return this.localeData().invalidDate(); + } + } -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + function fromNow (withoutSuffix) { + return this.from(createLocal(), withoutSuffix); + } -function mkdirP (p, opts, f, made) { - if (typeof opts === 'function') { - f = opts; - opts = {}; + function to (time, withoutSuffix) { + if (this.isValid() && + ((isMoment(time) && time.isValid()) || + createLocal(time).isValid())) { + return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix); + } else { + return this.localeData().invalidDate(); + } } - else if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; + + function toNow (withoutSuffix) { + return this.to(createLocal(), withoutSuffix); } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 & (~process.umask()); - } - if (!made) made = null; - - var cb = f || function () {}; - p = path.resolve(p); - - xfs.mkdir(p, mode, function (er) { - if (!er) { - made = made || p; - return cb(null, made); + + // If passed a locale key, it will set the locale for this + // instance. Otherwise, it will return the locale configuration + // variables for this instance. + function locale (key) { + var newLocaleData; + + if (key === undefined) { + return this._locale._abbr; + } else { + newLocaleData = getLocale(key); + if (newLocaleData != null) { + this._locale = newLocaleData; + } + return this; } - switch (er.code) { - case 'ENOENT': - if (path.dirname(p) === p) return cb(er); - mkdirP(path.dirname(p), opts, function (er, made) { - if (er) cb(er, made); - else mkdirP(p, opts, cb, made); - }); - break; + } - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - xfs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) cb(er, made) - else cb(null, made); - }); - break; + var lang = deprecate( + 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', + function (key) { + if (key === undefined) { + return this.localeData(); + } else { + return this.locale(key); + } } - }); -} + ); -mkdirP.sync = function sync (p, opts, made) { - if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; + function localeData () { + return this._locale; } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 & (~process.umask()); + + var MS_PER_SECOND = 1000; + var MS_PER_MINUTE = 60 * MS_PER_SECOND; + var MS_PER_HOUR = 60 * MS_PER_MINUTE; + var MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR; + + // actual modulo - handles negative numbers (for dates before 1970): + function mod$1(dividend, divisor) { + return (dividend % divisor + divisor) % divisor; } - if (!made) made = null; - p = path.resolve(p); + function localStartOfDate(y, m, d) { + // the date constructor remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + // preserve leap years using a full 400 year cycle, then reset + return new Date(y + 400, m, d) - MS_PER_400_YEARS; + } else { + return new Date(y, m, d).valueOf(); + } + } - try { - xfs.mkdirSync(p, mode); - made = made || p; + function utcStartOfDate(y, m, d) { + // Date.UTC remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + // preserve leap years using a full 400 year cycle, then reset + return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS; + } else { + return Date.UTC(y, m, d); + } } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - made = sync(path.dirname(p), opts, made); - sync(p, opts, made); - break; - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - var stat; - try { - stat = xfs.statSync(p); - } - catch (err1) { - throw err0; - } - if (!stat.isDirectory()) throw err0; + function startOf (units) { + var time; + units = normalizeUnits(units); + if (units === undefined || units === 'millisecond' || !this.isValid()) { + return this; + } + + var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; + + switch (units) { + case 'year': + time = startOfDate(this.year(), 0, 1); + break; + case 'quarter': + time = startOfDate(this.year(), this.month() - this.month() % 3, 1); + break; + case 'month': + time = startOfDate(this.year(), this.month(), 1); + break; + case 'week': + time = startOfDate(this.year(), this.month(), this.date() - this.weekday()); + break; + case 'isoWeek': + time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1)); + break; + case 'day': + case 'date': + time = startOfDate(this.year(), this.month(), this.date()); + break; + case 'hour': + time = this._d.valueOf(); + time -= mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR); + break; + case 'minute': + time = this._d.valueOf(); + time -= mod$1(time, MS_PER_MINUTE); + break; + case 'second': + time = this._d.valueOf(); + time -= mod$1(time, MS_PER_SECOND); break; } + + this._d.setTime(time); + hooks.updateOffset(this, true); + return this; } - return made; -}; + function endOf (units) { + var time; + units = normalizeUnits(units); + if (units === undefined || units === 'millisecond' || !this.isValid()) { + return this; + } + var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; -/***/ }), -/* 32 */ -/***/ (function(module, exports) { + switch (units) { + case 'year': + time = startOfDate(this.year() + 1, 0, 1) - 1; + break; + case 'quarter': + time = startOfDate(this.year(), this.month() - this.month() % 3 + 3, 1) - 1; + break; + case 'month': + time = startOfDate(this.year(), this.month() + 1, 1) - 1; + break; + case 'week': + time = startOfDate(this.year(), this.month(), this.date() - this.weekday() + 7) - 1; + break; + case 'isoWeek': + time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7) - 1; + break; + case 'day': + case 'date': + time = startOfDate(this.year(), this.month(), this.date() + 1) - 1; + break; + case 'hour': + time = this._d.valueOf(); + time += MS_PER_HOUR - mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR) - 1; + break; + case 'minute': + time = this._d.valueOf(); + time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1; + break; + case 'second': + time = this._d.valueOf(); + time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1; + break; + } -exports.replaceDollarWithPercentPair = replaceDollarWithPercentPair -exports.convertToSetCommand = convertToSetCommand -exports.convertToSetCommands = convertToSetCommands - -function convertToSetCommand(key, value) { - var line = "" - key = key || "" - key = key.trim() - value = value || "" - value = value.trim() - if(key && value && value.length > 0) { - line = "@SET " + key + "=" + replaceDollarWithPercentPair(value) + "\r\n" - } - return line -} - -function extractVariableValuePairs(declarations) { - var pairs = {} - declarations.map(function(declaration) { - var split = declaration.split("=") - pairs[split[0]]=split[1] - }) - return pairs -} - -function convertToSetCommands(variableString) { - var variableValuePairs = extractVariableValuePairs(variableString.split(" ")) - var variableDeclarationsAsBatch = "" - Object.keys(variableValuePairs).forEach(function (key) { - variableDeclarationsAsBatch += convertToSetCommand(key, variableValuePairs[key]) - }) - return variableDeclarationsAsBatch -} - -function replaceDollarWithPercentPair(value) { - var dollarExpressions = /\$\{?([^\$@#\?\- \t{}:]+)\}?/g - var result = "" - var startIndex = 0 - value = value || "" - do { - var match = dollarExpressions.exec(value) - if(match) { - var betweenMatches = value.substring(startIndex, match.index) || "" - result += betweenMatches + "%" + match[1] + "%" - startIndex = dollarExpressions.lastIndex - } - } while (dollarExpressions.lastIndex > 0) - result += value.substr(startIndex) - return result -} - - + this._d.setTime(time); + hooks.updateOffset(this, true); + return this; + } + function valueOf () { + return this._d.valueOf() - ((this._offset || 0) * 60000); + } -/***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { + function unix () { + return Math.floor(this.valueOf() / 1000); + } -var fs = __webpack_require__(23), - path = __webpack_require__(16); + function toDate () { + return new Date(this.valueOf()); + } -module.exports = ncp; -ncp.ncp = ncp; + function toArray () { + var m = this; + return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()]; + } -function ncp (source, dest, options, callback) { - var cback = callback; + function toObject () { + var m = this; + return { + years: m.year(), + months: m.month(), + date: m.date(), + hours: m.hours(), + minutes: m.minutes(), + seconds: m.seconds(), + milliseconds: m.milliseconds() + }; + } - if (!callback) { - cback = options; - options = {}; - } + function toJSON () { + // new Date(NaN).toJSON() === null + return this.isValid() ? this.toISOString() : null; + } - var basePath = process.cwd(), - currentPath = path.resolve(basePath, source), - targetPath = path.resolve(basePath, dest), - filter = options.filter, - rename = options.rename, - transform = options.transform, - clobber = options.clobber !== false, - modified = options.modified, - dereference = options.dereference, - errs = null, - started = 0, - finished = 0, - running = 0, - limit = options.limit || ncp.limit || 16; + function isValid$2 () { + return isValid(this); + } - limit = (limit < 1) ? 1 : (limit > 512) ? 512 : limit; + function parsingFlags () { + return extend({}, getParsingFlags(this)); + } - startCopy(currentPath); - - function startCopy(source) { - started++; - if (filter) { - if (filter instanceof RegExp) { - if (!filter.test(source)) { - return cb(true); - } - } - else if (typeof filter === 'function') { - if (!filter(source)) { - return cb(true); - } - } + function invalidAt () { + return getParsingFlags(this).overflow; } - return getStats(source); - } - function getStats(source) { - var stat = dereference ? fs.stat : fs.lstat; - if (running >= limit) { - return setImmediate(function () { - getStats(source); - }); + function creationData() { + return { + input: this._i, + format: this._f, + locale: this._locale, + isUTC: this._isUTC, + strict: this._strict + }; } - running++; - stat(source, function (err, stats) { - var item = {}; - if (err) { - return onError(err); - } - // We need to get the mode from the stats object and preserve it. - item.name = source; - item.mode = stats.mode; - item.mtime = stats.mtime; //modified time - item.atime = stats.atime; //access time + // FORMATTING - if (stats.isDirectory()) { - return onDir(item); - } - else if (stats.isFile()) { - return onFile(item); - } - else if (stats.isSymbolicLink()) { - // Symlinks don't really need to know about the mode. - return onLink(source); - } + addFormatToken(0, ['gg', 2], 0, function () { + return this.weekYear() % 100; }); - } - function onFile(file) { - var target = file.name.replace(currentPath, targetPath); - if(rename) { - target = rename(target); - } - isWritable(target, function (writable) { - if (writable) { - return copyFile(file, target); - } - if(clobber) { - rmFile(target, function () { - copyFile(file, target); - }); - } - if (modified) { - var stat = dereference ? fs.stat : fs.lstat; - stat(target, function(err, stats) { - //if souce modified time greater to target modified time copy file - if (file.mtime.getTime()>stats.mtime.getTime()) - copyFile(file, target); - else return cb(); - }); - } - else { - return cb(); - } + addFormatToken(0, ['GG', 2], 0, function () { + return this.isoWeekYear() % 100; }); - } - function copyFile(file, target) { - var readStream = fs.createReadStream(file.name), - writeStream = fs.createWriteStream(target, { mode: file.mode }); - - readStream.on('error', onError); - writeStream.on('error', onError); - - if(transform) { - transform(readStream, writeStream, file); - } else { - writeStream.on('open', function() { - readStream.pipe(writeStream); - }); + function addWeekYearFormatToken (token, getter) { + addFormatToken(0, [token, token.length], 0, getter); } - writeStream.once('finish', function() { - if (modified) { - //target file modified date sync. - fs.utimesSync(target, file.atime, file.mtime); - cb(); - } - else cb(); - }); - } - function rmFile(file, done) { - fs.unlink(file, function (err) { - if (err) { - return onError(err); - } - return done(); - }); - } + addWeekYearFormatToken('gggg', 'weekYear'); + addWeekYearFormatToken('ggggg', 'weekYear'); + addWeekYearFormatToken('GGGG', 'isoWeekYear'); + addWeekYearFormatToken('GGGGG', 'isoWeekYear'); - function onDir(dir) { - var target = dir.name.replace(currentPath, targetPath); - isWritable(target, function (writable) { - if (writable) { - return mkDir(dir, target); - } - copyDir(dir.name); - }); - } + // ALIASES - function mkDir(dir, target) { - fs.mkdir(target, dir.mode, function (err) { - if (err) { - return onError(err); - } - copyDir(dir.name); - }); - } + addUnitAlias('weekYear', 'gg'); + addUnitAlias('isoWeekYear', 'GG'); - function copyDir(dir) { - fs.readdir(dir, function (err, items) { - if (err) { - return onError(err); - } - items.forEach(function (item) { - startCopy(path.join(dir, item)); - }); - return cb(); + // PRIORITY + + addUnitPriority('weekYear', 1); + addUnitPriority('isoWeekYear', 1); + + + // PARSING + + addRegexToken('G', matchSigned); + addRegexToken('g', matchSigned); + addRegexToken('GG', match1to2, match2); + addRegexToken('gg', match1to2, match2); + addRegexToken('GGGG', match1to4, match4); + addRegexToken('gggg', match1to4, match4); + addRegexToken('GGGGG', match1to6, match6); + addRegexToken('ggggg', match1to6, match6); + + addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) { + week[token.substr(0, 2)] = toInt(input); }); - } - function onLink(link) { - var target = link.replace(currentPath, targetPath); - fs.readlink(link, function (err, resolvedPath) { - if (err) { - return onError(err); - } - checkLink(resolvedPath, target); + addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { + week[token] = hooks.parseTwoDigitYear(input); }); - } - function checkLink(resolvedPath, target) { - if (dereference) { - resolvedPath = path.resolve(basePath, resolvedPath); - } - isWritable(target, function (writable) { - if (writable) { - return makeLink(resolvedPath, target); - } - fs.readlink(target, function (err, targetDest) { - if (err) { - return onError(err); - } - if (dereference) { - targetDest = path.resolve(basePath, targetDest); - } - if (targetDest === resolvedPath) { - return cb(); - } - return rmFile(target, function () { - makeLink(resolvedPath, target); - }); - }); - }); - } - - function makeLink(linkPath, target) { - fs.symlink(linkPath, target, function (err) { - if (err) { - return onError(err); - } - return cb(); - }); - } - - function isWritable(path, done) { - fs.lstat(path, function (err) { - if (err) { - if (err.code === 'ENOENT') return done(true); - return done(false); - } - return done(false); - }); - } + // MOMENTS - function onError(err) { - if (options.stopOnError) { - return cback(err); + function getSetWeekYear (input) { + return getSetWeekYearHelper.call(this, + input, + this.week(), + this.weekday(), + this.localeData()._week.dow, + this.localeData()._week.doy); } - else if (!errs && options.errs) { - errs = fs.createWriteStream(options.errs); + + function getSetISOWeekYear (input) { + return getSetWeekYearHelper.call(this, + input, this.isoWeek(), this.isoWeekday(), 1, 4); } - else if (!errs) { - errs = []; + + function getISOWeeksInYear () { + return weeksInYear(this.year(), 1, 4); } - if (typeof errs.write === 'undefined') { - errs.push(err); + + function getWeeksInYear () { + var weekInfo = this.localeData()._week; + return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); } - else { - errs.write(err.stack + '\n\n'); + + function getSetWeekYearHelper(input, week, weekday, dow, doy) { + var weeksTarget; + if (input == null) { + return weekOfYear(this, dow, doy).year; + } else { + weeksTarget = weeksInYear(input, dow, doy); + if (week > weeksTarget) { + week = weeksTarget; + } + return setWeekAll.call(this, input, week, weekday, dow, doy); + } } - return cb(); - } - function cb(skipped) { - if (!skipped) running--; - finished++; - if ((started === finished) && (running === 0)) { - if (cback !== undefined ) { - return errs ? cback(errs) : cback(null); - } + function setWeekAll(weekYear, week, weekday, dow, doy) { + var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), + date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); + + this.year(date.getUTCFullYear()); + this.month(date.getUTCMonth()); + this.date(date.getUTCDate()); + return this; } - } -} + // FORMATTING + addFormatToken('Q', 0, 'Qo', 'quarter'); + // ALIASES -/***/ }), -/* 34 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + addUnitAlias('quarter', 'Q'); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "log", function() { return log; }); -/* harmony import */ var _kbn_dev_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(35); -/* harmony import */ var _kbn_dev_utils__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_kbn_dev_utils__WEBPACK_IMPORTED_MODULE_0__); -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; } + // PRIORITY -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ + addUnitPriority('quarter', 7); + // PARSING -class Log extends _kbn_dev_utils__WEBPACK_IMPORTED_MODULE_0__["ToolingLog"] { - constructor() { - super({ - level: 'info', - writeTo: process.stdout + addRegexToken('Q', match1); + addParseToken('Q', function (input, array) { + array[MONTH] = (toInt(input) - 1) * 3; }); - _defineProperty(this, "testWriter", void 0); - } - /** - * Log something to the console. Ideally we would use a real logger in - * kbn-pm, but that's a pretty big change for now. - * @param ...args - */ - + // MOMENTS - write(...args) { - // eslint-disable-next-line no-console - console.log(...args); - } + function getSetQuarter (input) { + return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); + } -} + // FORMATTING -const log = new Log(); + addFormatToken('D', ['DD', 2], 'Do', 'date'); -/***/ }), -/* 35 */ -/***/ (function(module, exports, __webpack_require__) { + // ALIASES -"use strict"; + addUnitAlias('date', 'D'); -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(36); -var proc_runner_1 = __webpack_require__(37); -exports.withProcRunner = proc_runner_1.withProcRunner; -exports.ProcRunner = proc_runner_1.ProcRunner; -tslib_1.__exportStar(__webpack_require__(414), exports); -var serializers_1 = __webpack_require__(419); -exports.createAbsolutePathSerializer = serializers_1.createAbsolutePathSerializer; -var certs_1 = __webpack_require__(443); -exports.CA_CERT_PATH = certs_1.CA_CERT_PATH; -exports.ES_KEY_PATH = certs_1.ES_KEY_PATH; -exports.ES_CERT_PATH = certs_1.ES_CERT_PATH; -exports.ES_P12_PATH = certs_1.ES_P12_PATH; -exports.ES_P12_PASSWORD = certs_1.ES_P12_PASSWORD; -exports.ES_EMPTYPASSWORD_P12_PATH = certs_1.ES_EMPTYPASSWORD_P12_PATH; -exports.ES_NOPASSWORD_P12_PATH = certs_1.ES_NOPASSWORD_P12_PATH; -exports.KBN_KEY_PATH = certs_1.KBN_KEY_PATH; -exports.KBN_CERT_PATH = certs_1.KBN_CERT_PATH; -exports.KBN_P12_PATH = certs_1.KBN_P12_PATH; -exports.KBN_P12_PASSWORD = certs_1.KBN_P12_PASSWORD; -var run_1 = __webpack_require__(444); -exports.run = run_1.run; -exports.createFailError = run_1.createFailError; -exports.createFlagError = run_1.createFlagError; -exports.combineErrors = run_1.combineErrors; -exports.isFailError = run_1.isFailError; -var repo_root_1 = __webpack_require__(421); -exports.REPO_ROOT = repo_root_1.REPO_ROOT; -var kbn_client_1 = __webpack_require__(449); -exports.KbnClient = kbn_client_1.KbnClient; -tslib_1.__exportStar(__webpack_require__(492), exports); -tslib_1.__exportStar(__webpack_require__(499), exports); + // PRIORITY + addUnitPriority('date', 9); + // PARSING -/***/ }), -/* 36 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + addRegexToken('D', match1to2); + addRegexToken('DD', match1to2, match2); + addRegexToken('Do', function (isStrict, locale) { + // TODO: Remove "ordinalParse" fallback in next major release. + return isStrict ? + (locale._dayOfMonthOrdinalParse || locale._ordinalParse) : + locale._dayOfMonthOrdinalParseLenient; + }); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__extends", function() { return __extends; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__assign", function() { return __assign; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__rest", function() { return __rest; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__decorate", function() { return __decorate; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__param", function() { return __param; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__metadata", function() { return __metadata; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__awaiter", function() { return __awaiter; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__generator", function() { return __generator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__exportStar", function() { return __exportStar; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__values", function() { return __values; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__read", function() { return __read; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spread", function() { return __spread; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__await", function() { return __await; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncGenerator", function() { return __asyncGenerator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncDelegator", function() { return __asyncDelegator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncValues", function() { return __asyncValues; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__makeTemplateObject", function() { return __makeTemplateObject; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importStar", function() { return __importStar; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importDefault", function() { return __importDefault; }); -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ -/* global Reflect, Promise */ - -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); -}; - -function __extends(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -var __assign = function() { - __assign = Object.assign || function __assign(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); -} - -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) - t[p[i]] = s[p[i]]; - return t; -} - -function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} - -function __param(paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } -} - -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} - -function __awaiter(thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} - -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -function __exportStar(m, exports) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} - -function __values(o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; - if (m) return m.call(o); - return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; -} - -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -} - -function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; -} - -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} - -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } -} - -function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } -} - -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -} - -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; -}; - -function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result.default = mod; - return result; -} - -function __importDefault(mod) { - return (mod && mod.__esModule) ? mod : { default: mod }; -} + addParseToken(['D', 'DD'], DATE); + addParseToken('Do', function (input, array) { + array[DATE] = toInt(input.match(match1to2)[0]); + }); + // MOMENTS -/***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { + var getSetDayOfMonth = makeGetSet('Date', true); -"use strict"; + // FORMATTING -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -var with_proc_runner_1 = __webpack_require__(38); -exports.withProcRunner = with_proc_runner_1.withProcRunner; -var proc_runner_1 = __webpack_require__(39); -exports.ProcRunner = proc_runner_1.ProcRunner; + addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); + // ALIASES -/***/ }), -/* 38 */ -/***/ (function(module, exports, __webpack_require__) { + addUnitAlias('dayOfYear', 'DDD'); -"use strict"; + // PRIORITY + addUnitPriority('dayOfYear', 4); -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const proc_runner_1 = __webpack_require__(39); -/** - * Create a ProcRunner and pass it to an async function. When - * the async function finishes the ProcRunner is torn-down - * automatically - * - * @param {ToolingLog} log - * @param {async Function} fn - * @return {Promise} - */ -async function withProcRunner(log, fn) { - const procs = new proc_runner_1.ProcRunner(log); - try { - await fn(procs); - } - finally { - await procs.teardown(); - } -} -exports.withProcRunner = withProcRunner; + // PARSING + addRegexToken('DDD', match1to3); + addRegexToken('DDDD', match3); + addParseToken(['DDD', 'DDDD'], function (input, array, config) { + config._dayOfYear = toInt(input); + }); -/***/ }), -/* 39 */ -/***/ (function(module, exports, __webpack_require__) { + // HELPERS -"use strict"; + // MOMENTS -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(36); -const moment_1 = tslib_1.__importDefault(__webpack_require__(40)); -const Rx = tslib_1.__importStar(__webpack_require__(169)); -const operators_1 = __webpack_require__(270); -const exit_hook_1 = tslib_1.__importDefault(__webpack_require__(368)); -const errors_1 = __webpack_require__(369); -const proc_1 = __webpack_require__(370); -const SECOND = 1000; -const MINUTE = 60 * SECOND; -const noop = () => { }; -/** - * Helper for starting and managing processes. In many ways it resembles the - * API from `grunt_run`, processes are named and can be started, waited for, - * backgrounded once they log something matching a RegExp... - * - * @class ProcRunner - */ -class ProcRunner { - constructor(log) { - this.log = log; - this.closing = false; - this.procs = []; - this.signalUnsubscribe = exit_hook_1.default(() => { - this.teardown().catch((error) => { - log.error(`ProcRunner teardown error: ${error.stack}`); - }); - }); - } - /** - * Start a process, tracking it by `name` - * @param {String} name - * @param {Object} options - * @property {String} options.cmd executable to run - * @property {Array?} options.args arguments to provide the executable - * @property {String?} options.cwd current working directory for the process - * @property {RegExp|Boolean} options.wait Should start() wait for some time? Use - * `true` will wait until the proc exits, - * a `RegExp` will wait until that log line - * is found - * @return {Promise} - */ - async run(name, options) { - const { cmd, args = [], cwd = process.cwd(), stdin = undefined, wait = false, waitTimeout = 15 * MINUTE, env = process.env, } = options; - if (this.closing) { - throw new Error('ProcRunner is closing'); - } - if (wait && !(wait instanceof RegExp) && wait !== true) { - throw new TypeError('wait param should either be a RegExp or `true`'); - } - if (!!this.getProc(name)) { - throw new Error(`Process with name "${name}" already running`); - } - const proc = this.startProc(name, { - cmd, - args, - cwd, - env, - stdin, - }); - try { - if (wait instanceof RegExp) { - // wait for process to log matching line - await Rx.race(proc.lines$.pipe(operators_1.filter((line) => wait.test(line)), operators_1.first(), operators_1.catchError((err) => { - if (err.name !== 'EmptyError') { - throw errors_1.createCliError(`[${name}] exited without matching pattern: ${wait}`); - } - else { - throw err; - } - })), waitTimeout === false - ? Rx.NEVER - : Rx.timer(waitTimeout).pipe(operators_1.map(() => { - const sec = waitTimeout / SECOND; - throw errors_1.createCliError(`[${name}] failed to match pattern within ${sec} seconds [pattern=${wait}]`); - }))).toPromise(); - } - if (wait === true) { - // wait for process to complete - await proc.outcomePromise; - } - } - finally { - // while the procRunner closes promises will resolve/reject because - // processes and stopping, but consumers of run() shouldn't have to - // prepare for that, so just return a never-resolving promise - if (this.closing) { - await new Promise(noop); - } - } - } - /** - * Stop a named proc - */ - async stop(name, signal = 'SIGTERM') { - const proc = this.getProc(name); - if (proc) { - await proc.stop(signal); - } - else { - this.log.warning('[%s] already stopped', name); - } - } - /** - * Wait for all running processes to stop naturally - * @return {Promise} - */ - async waitForAllToStop() { - await Promise.all(this.procs.map((proc) => proc.outcomePromise)); - } - /** - * Close the ProcRunner and stop all running - * processes with `signal` - * - * @param {String} [signal=undefined] - * @return {Promise} - */ - async teardown(signal = 'exit') { - if (this.closing) { - return; - } - this.closing = true; - this.signalUnsubscribe(); - if (!signal && this.procs.length > 0) { - this.log.warning('%d processes left running, stop them with procs.stop(name):', this.procs.length, this.procs.map((proc) => proc.name)); - } - await Promise.all(this.procs.map(async (proc) => { - await proc.stop(signal === 'exit' ? 'SIGKILL' : signal); - })); - } - getProc(name) { - return this.procs.find((proc) => { - return proc.name === name; - }); - } - startProc(name, options) { - const startMs = Date.now(); - const proc = proc_1.startProc(name, options, this.log); - this.procs.push(proc); - const remove = () => { - this.procs.splice(this.procs.indexOf(proc), 1); - }; - // tie into proc outcome$, remove from _procs on compete - proc.outcome$.subscribe({ - next: (code) => { - const duration = moment_1.default.duration(Date.now() - startMs); - this.log.info('[%s] exited with %s after %s', name, code, duration.humanize()); - }, - complete: () => { - remove(); - }, - error: (error) => { - if (this.closing) { - this.log.error(error); - } - remove(); - }, - }); - return proc; + function getSetDayOfYear (input) { + var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1; + return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); } -} -exports.ProcRunner = ProcRunner; - - -/***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(module) {var require;//! moment.js -;(function (global, factory) { - true ? module.exports = factory() : - undefined -}(this, (function () { 'use strict'; + // FORMATTING - var hookCallback; + addFormatToken('m', ['mm', 2], 0, 'minute'); - function hooks () { - return hookCallback.apply(null, arguments); - } + // ALIASES - // This is done to register the method called with moment() - // without creating circular dependencies. - function setHookCallback (callback) { - hookCallback = callback; - } + addUnitAlias('minute', 'm'); - function isArray(input) { - return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]'; - } + // PRIORITY - function isObject(input) { - // IE8 will treat undefined and null as object if it wasn't for - // input != null - return input != null && Object.prototype.toString.call(input) === '[object Object]'; - } + addUnitPriority('minute', 14); - function isObjectEmpty(obj) { - if (Object.getOwnPropertyNames) { - return (Object.getOwnPropertyNames(obj).length === 0); - } else { - var k; - for (k in obj) { - if (obj.hasOwnProperty(k)) { - return false; - } - } - return true; - } - } + // PARSING - function isUndefined(input) { - return input === void 0; - } + addRegexToken('m', match1to2); + addRegexToken('mm', match1to2, match2); + addParseToken(['m', 'mm'], MINUTE); - function isNumber(input) { - return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]'; - } + // MOMENTS - function isDate(input) { - return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]'; - } + var getSetMinute = makeGetSet('Minutes', false); - function map(arr, fn) { - var res = [], i; - for (i = 0; i < arr.length; ++i) { - res.push(fn(arr[i], i)); - } - return res; - } + // FORMATTING - function hasOwnProp(a, b) { - return Object.prototype.hasOwnProperty.call(a, b); - } + addFormatToken('s', ['ss', 2], 0, 'second'); - function extend(a, b) { - for (var i in b) { - if (hasOwnProp(b, i)) { - a[i] = b[i]; - } - } + // ALIASES - if (hasOwnProp(b, 'toString')) { - a.toString = b.toString; - } + addUnitAlias('second', 's'); - if (hasOwnProp(b, 'valueOf')) { - a.valueOf = b.valueOf; - } + // PRIORITY - return a; - } + addUnitPriority('second', 15); - function createUTC (input, format, locale, strict) { - return createLocalOrUTC(input, format, locale, strict, true).utc(); - } + // PARSING - function defaultParsingFlags() { - // We need to deep clone this object. - return { - empty : false, - unusedTokens : [], - unusedInput : [], - overflow : -2, - charsLeftOver : 0, - nullInput : false, - invalidMonth : null, - invalidFormat : false, - userInvalidated : false, - iso : false, - parsedDateParts : [], - meridiem : null, - rfc2822 : false, - weekdayMismatch : false - }; - } + addRegexToken('s', match1to2); + addRegexToken('ss', match1to2, match2); + addParseToken(['s', 'ss'], SECOND); - function getParsingFlags(m) { - if (m._pf == null) { - m._pf = defaultParsingFlags(); - } - return m._pf; - } + // MOMENTS - var some; - if (Array.prototype.some) { - some = Array.prototype.some; - } else { - some = function (fun) { - var t = Object(this); - var len = t.length >>> 0; + var getSetSecond = makeGetSet('Seconds', false); - for (var i = 0; i < len; i++) { - if (i in t && fun.call(this, t[i], i, t)) { - return true; - } - } + // FORMATTING - return false; - }; - } + addFormatToken('S', 0, 0, function () { + return ~~(this.millisecond() / 100); + }); - function isValid(m) { - if (m._isValid == null) { - var flags = getParsingFlags(m); - var parsedParts = some.call(flags.parsedDateParts, function (i) { - return i != null; - }); - var isNowValid = !isNaN(m._d.getTime()) && - flags.overflow < 0 && - !flags.empty && - !flags.invalidMonth && - !flags.invalidWeekday && - !flags.weekdayMismatch && - !flags.nullInput && - !flags.invalidFormat && - !flags.userInvalidated && - (!flags.meridiem || (flags.meridiem && parsedParts)); + addFormatToken(0, ['SS', 2], 0, function () { + return ~~(this.millisecond() / 10); + }); - if (m._strict) { - isNowValid = isNowValid && - flags.charsLeftOver === 0 && - flags.unusedTokens.length === 0 && - flags.bigHour === undefined; - } + addFormatToken(0, ['SSS', 3], 0, 'millisecond'); + addFormatToken(0, ['SSSS', 4], 0, function () { + return this.millisecond() * 10; + }); + addFormatToken(0, ['SSSSS', 5], 0, function () { + return this.millisecond() * 100; + }); + addFormatToken(0, ['SSSSSS', 6], 0, function () { + return this.millisecond() * 1000; + }); + addFormatToken(0, ['SSSSSSS', 7], 0, function () { + return this.millisecond() * 10000; + }); + addFormatToken(0, ['SSSSSSSS', 8], 0, function () { + return this.millisecond() * 100000; + }); + addFormatToken(0, ['SSSSSSSSS', 9], 0, function () { + return this.millisecond() * 1000000; + }); - if (Object.isFrozen == null || !Object.isFrozen(m)) { - m._isValid = isNowValid; - } - else { - return isNowValid; - } - } - return m._isValid; - } - function createInvalid (flags) { - var m = createUTC(NaN); - if (flags != null) { - extend(getParsingFlags(m), flags); - } - else { - getParsingFlags(m).userInvalidated = true; - } + // ALIASES - return m; - } + addUnitAlias('millisecond', 'ms'); - // Plugins that add properties should also add the key here (null value), - // so we can properly clone ourselves. - var momentProperties = hooks.momentProperties = []; + // PRIORITY - function copyConfig(to, from) { - var i, prop, val; + addUnitPriority('millisecond', 16); - if (!isUndefined(from._isAMomentObject)) { - to._isAMomentObject = from._isAMomentObject; - } - if (!isUndefined(from._i)) { - to._i = from._i; - } - if (!isUndefined(from._f)) { - to._f = from._f; - } - if (!isUndefined(from._l)) { - to._l = from._l; - } - if (!isUndefined(from._strict)) { - to._strict = from._strict; - } - if (!isUndefined(from._tzm)) { - to._tzm = from._tzm; - } - if (!isUndefined(from._isUTC)) { - to._isUTC = from._isUTC; - } - if (!isUndefined(from._offset)) { - to._offset = from._offset; - } - if (!isUndefined(from._pf)) { - to._pf = getParsingFlags(from); - } - if (!isUndefined(from._locale)) { - to._locale = from._locale; - } + // PARSING - if (momentProperties.length > 0) { - for (i = 0; i < momentProperties.length; i++) { - prop = momentProperties[i]; - val = from[prop]; - if (!isUndefined(val)) { - to[prop] = val; - } - } - } + addRegexToken('S', match1to3, match1); + addRegexToken('SS', match1to3, match2); + addRegexToken('SSS', match1to3, match3); - return to; + var token; + for (token = 'SSSS'; token.length <= 9; token += 'S') { + addRegexToken(token, matchUnsigned); } - var updateInProgress = false; - - // Moment prototype object - function Moment(config) { - copyConfig(this, config); - this._d = new Date(config._d != null ? config._d.getTime() : NaN); - if (!this.isValid()) { - this._d = new Date(NaN); - } - // Prevent infinite loop in case updateOffset creates new moment - // objects. - if (updateInProgress === false) { - updateInProgress = true; - hooks.updateOffset(this); - updateInProgress = false; - } + function parseMs(input, array) { + array[MILLISECOND] = toInt(('0.' + input) * 1000); } - function isMoment (obj) { - return obj instanceof Moment || (obj != null && obj._isAMomentObject != null); + for (token = 'S'; token.length <= 9; token += 'S') { + addParseToken(token, parseMs); } + // MOMENTS - function absFloor (number) { - if (number < 0) { - // -0 -> 0 - return Math.ceil(number) || 0; - } else { - return Math.floor(number); - } - } + var getSetMillisecond = makeGetSet('Milliseconds', false); - function toInt(argumentForCoercion) { - var coercedNumber = +argumentForCoercion, - value = 0; + // FORMATTING - if (coercedNumber !== 0 && isFinite(coercedNumber)) { - value = absFloor(coercedNumber); - } + addFormatToken('z', 0, 0, 'zoneAbbr'); + addFormatToken('zz', 0, 0, 'zoneName'); - return value; - } + // MOMENTS - // compare two arrays, return the number of differences - function compareArrays(array1, array2, dontConvert) { - var len = Math.min(array1.length, array2.length), - lengthDiff = Math.abs(array1.length - array2.length), - diffs = 0, - i; - for (i = 0; i < len; i++) { - if ((dontConvert && array1[i] !== array2[i]) || - (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { - diffs++; - } - } - return diffs + lengthDiff; + function getZoneAbbr () { + return this._isUTC ? 'UTC' : ''; } - function warn(msg) { - if (hooks.suppressDeprecationWarnings === false && - (typeof console !== 'undefined') && console.warn) { - console.warn('Deprecation warning: ' + msg); - } + function getZoneName () { + return this._isUTC ? 'Coordinated Universal Time' : ''; } - function deprecate(msg, fn) { - var firstTime = true; + var proto = Moment.prototype; - return extend(function () { - if (hooks.deprecationHandler != null) { - hooks.deprecationHandler(null, msg); - } - if (firstTime) { - var args = []; - var arg; - for (var i = 0; i < arguments.length; i++) { - arg = ''; - if (typeof arguments[i] === 'object') { - arg += '\n[' + i + '] '; - for (var key in arguments[0]) { - arg += key + ': ' + arguments[0][key] + ', '; - } - arg = arg.slice(0, -2); // Remove trailing comma and space - } else { - arg = arguments[i]; - } - args.push(arg); - } - warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack); - firstTime = false; - } - return fn.apply(this, arguments); - }, fn); + proto.add = add; + proto.calendar = calendar$1; + proto.clone = clone; + proto.diff = diff; + proto.endOf = endOf; + proto.format = format; + proto.from = from; + proto.fromNow = fromNow; + proto.to = to; + proto.toNow = toNow; + proto.get = stringGet; + proto.invalidAt = invalidAt; + proto.isAfter = isAfter; + proto.isBefore = isBefore; + proto.isBetween = isBetween; + proto.isSame = isSame; + proto.isSameOrAfter = isSameOrAfter; + proto.isSameOrBefore = isSameOrBefore; + proto.isValid = isValid$2; + proto.lang = lang; + proto.locale = locale; + proto.localeData = localeData; + proto.max = prototypeMax; + proto.min = prototypeMin; + proto.parsingFlags = parsingFlags; + proto.set = stringSet; + proto.startOf = startOf; + proto.subtract = subtract; + proto.toArray = toArray; + proto.toObject = toObject; + proto.toDate = toDate; + proto.toISOString = toISOString; + proto.inspect = inspect; + proto.toJSON = toJSON; + proto.toString = toString; + proto.unix = unix; + proto.valueOf = valueOf; + proto.creationData = creationData; + proto.year = getSetYear; + proto.isLeapYear = getIsLeapYear; + proto.weekYear = getSetWeekYear; + proto.isoWeekYear = getSetISOWeekYear; + proto.quarter = proto.quarters = getSetQuarter; + proto.month = getSetMonth; + proto.daysInMonth = getDaysInMonth; + proto.week = proto.weeks = getSetWeek; + proto.isoWeek = proto.isoWeeks = getSetISOWeek; + proto.weeksInYear = getWeeksInYear; + proto.isoWeeksInYear = getISOWeeksInYear; + proto.date = getSetDayOfMonth; + proto.day = proto.days = getSetDayOfWeek; + proto.weekday = getSetLocaleDayOfWeek; + proto.isoWeekday = getSetISODayOfWeek; + proto.dayOfYear = getSetDayOfYear; + proto.hour = proto.hours = getSetHour; + proto.minute = proto.minutes = getSetMinute; + proto.second = proto.seconds = getSetSecond; + proto.millisecond = proto.milliseconds = getSetMillisecond; + proto.utcOffset = getSetOffset; + proto.utc = setOffsetToUTC; + proto.local = setOffsetToLocal; + proto.parseZone = setOffsetToParsedOffset; + proto.hasAlignedHourOffset = hasAlignedHourOffset; + proto.isDST = isDaylightSavingTime; + proto.isLocal = isLocal; + proto.isUtcOffset = isUtcOffset; + proto.isUtc = isUtc; + proto.isUTC = isUtc; + proto.zoneAbbr = getZoneAbbr; + proto.zoneName = getZoneName; + proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth); + proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth); + proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear); + proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone); + proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted); + + function createUnix (input) { + return createLocal(input * 1000); } - var deprecations = {}; + function createInZone () { + return createLocal.apply(null, arguments).parseZone(); + } - function deprecateSimple(name, msg) { - if (hooks.deprecationHandler != null) { - hooks.deprecationHandler(name, msg); - } - if (!deprecations[name]) { - warn(msg); - deprecations[name] = true; - } + function preParsePostFormat (string) { + return string; } - hooks.suppressDeprecationWarnings = false; - hooks.deprecationHandler = null; + var proto$1 = Locale.prototype; - function isFunction(input) { - return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]'; - } + proto$1.calendar = calendar; + proto$1.longDateFormat = longDateFormat; + proto$1.invalidDate = invalidDate; + proto$1.ordinal = ordinal; + proto$1.preparse = preParsePostFormat; + proto$1.postformat = preParsePostFormat; + proto$1.relativeTime = relativeTime; + proto$1.pastFuture = pastFuture; + proto$1.set = set; - function set (config) { - var prop, i; - for (i in config) { - prop = config[i]; - if (isFunction(prop)) { - this[i] = prop; - } else { - this['_' + i] = prop; - } - } - this._config = config; - // Lenient ordinal parsing accepts just a number in addition to - // number + (possibly) stuff coming from _dayOfMonthOrdinalParse. - // TODO: Remove "ordinalParse" fallback in next major release. - this._dayOfMonthOrdinalParseLenient = new RegExp( - (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + - '|' + (/\d{1,2}/).source); + proto$1.months = localeMonths; + proto$1.monthsShort = localeMonthsShort; + proto$1.monthsParse = localeMonthsParse; + proto$1.monthsRegex = monthsRegex; + proto$1.monthsShortRegex = monthsShortRegex; + proto$1.week = localeWeek; + proto$1.firstDayOfYear = localeFirstDayOfYear; + proto$1.firstDayOfWeek = localeFirstDayOfWeek; + + proto$1.weekdays = localeWeekdays; + proto$1.weekdaysMin = localeWeekdaysMin; + proto$1.weekdaysShort = localeWeekdaysShort; + proto$1.weekdaysParse = localeWeekdaysParse; + + proto$1.weekdaysRegex = weekdaysRegex; + proto$1.weekdaysShortRegex = weekdaysShortRegex; + proto$1.weekdaysMinRegex = weekdaysMinRegex; + + proto$1.isPM = localeIsPM; + proto$1.meridiem = localeMeridiem; + + function get$1 (format, index, field, setter) { + var locale = getLocale(); + var utc = createUTC().set(setter, index); + return locale[field](utc, format); } - function mergeConfigs(parentConfig, childConfig) { - var res = extend({}, parentConfig), prop; - for (prop in childConfig) { - if (hasOwnProp(childConfig, prop)) { - if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) { - res[prop] = {}; - extend(res[prop], parentConfig[prop]); - extend(res[prop], childConfig[prop]); - } else if (childConfig[prop] != null) { - res[prop] = childConfig[prop]; - } else { - delete res[prop]; - } - } + function listMonthsImpl (format, index, field) { + if (isNumber(format)) { + index = format; + format = undefined; } - for (prop in parentConfig) { - if (hasOwnProp(parentConfig, prop) && - !hasOwnProp(childConfig, prop) && - isObject(parentConfig[prop])) { - // make sure changes to properties don't modify parent config - res[prop] = extend({}, res[prop]); - } + + format = format || ''; + + if (index != null) { + return get$1(format, index, field, 'month'); } - return res; - } - function Locale(config) { - if (config != null) { - this.set(config); + var i; + var out = []; + for (i = 0; i < 12; i++) { + out[i] = get$1(format, i, field, 'month'); } + return out; } - var keys; - - if (Object.keys) { - keys = Object.keys; - } else { - keys = function (obj) { - var i, res = []; - for (i in obj) { - if (hasOwnProp(obj, i)) { - res.push(i); - } + // () + // (5) + // (fmt, 5) + // (fmt) + // (true) + // (true, 5) + // (true, fmt, 5) + // (true, fmt) + function listWeekdaysImpl (localeSorted, format, index, field) { + if (typeof localeSorted === 'boolean') { + if (isNumber(format)) { + index = format; + format = undefined; } - return res; - }; - } - var defaultCalendar = { - sameDay : '[Today at] LT', - nextDay : '[Tomorrow at] LT', - nextWeek : 'dddd [at] LT', - lastDay : '[Yesterday at] LT', - lastWeek : '[Last] dddd [at] LT', - sameElse : 'L' - }; + format = format || ''; + } else { + format = localeSorted; + index = format; + localeSorted = false; - function calendar (key, mom, now) { - var output = this._calendar[key] || this._calendar['sameElse']; - return isFunction(output) ? output.call(mom, now) : output; - } + if (isNumber(format)) { + index = format; + format = undefined; + } - var defaultLongDateFormat = { - LTS : 'h:mm:ss A', - LT : 'h:mm A', - L : 'MM/DD/YYYY', - LL : 'MMMM D, YYYY', - LLL : 'MMMM D, YYYY h:mm A', - LLLL : 'dddd, MMMM D, YYYY h:mm A' - }; + format = format || ''; + } - function longDateFormat (key) { - var format = this._longDateFormat[key], - formatUpper = this._longDateFormat[key.toUpperCase()]; + var locale = getLocale(), + shift = localeSorted ? locale._week.dow : 0; - if (format || !formatUpper) { - return format; + if (index != null) { + return get$1(format, (index + shift) % 7, field, 'day'); } - this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) { - return val.slice(1); - }); - - return this._longDateFormat[key]; + var i; + var out = []; + for (i = 0; i < 7; i++) { + out[i] = get$1(format, (i + shift) % 7, field, 'day'); + } + return out; } - var defaultInvalidDate = 'Invalid date'; - - function invalidDate () { - return this._invalidDate; + function listMonths (format, index) { + return listMonthsImpl(format, index, 'months'); } - var defaultOrdinal = '%d'; - var defaultDayOfMonthOrdinalParse = /\d{1,2}/; - - function ordinal (number) { - return this._ordinal.replace('%d', number); + function listMonthsShort (format, index) { + return listMonthsImpl(format, index, 'monthsShort'); } - var defaultRelativeTime = { - future : 'in %s', - past : '%s ago', - s : 'a few seconds', - ss : '%d seconds', - m : 'a minute', - mm : '%d minutes', - h : 'an hour', - hh : '%d hours', - d : 'a day', - dd : '%d days', - M : 'a month', - MM : '%d months', - y : 'a year', - yy : '%d years' - }; - - function relativeTime (number, withoutSuffix, string, isFuture) { - var output = this._relativeTime[string]; - return (isFunction(output)) ? - output(number, withoutSuffix, string, isFuture) : - output.replace(/%d/i, number); + function listWeekdays (localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdays'); } - function pastFuture (diff, output) { - var format = this._relativeTime[diff > 0 ? 'future' : 'past']; - return isFunction(format) ? format(output) : format.replace(/%s/i, output); + function listWeekdaysShort (localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort'); } - var aliases = {}; - - function addUnitAlias (unit, shorthand) { - var lowerCase = unit.toLowerCase(); - aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; + function listWeekdaysMin (localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin'); } - function normalizeUnits(units) { - return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined; - } + getSetGlobalLocale('en', { + dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, + ordinal : function (number) { + var b = number % 10, + output = (toInt(number % 100 / 10) === 1) ? 'th' : + (b === 1) ? 'st' : + (b === 2) ? 'nd' : + (b === 3) ? 'rd' : 'th'; + return number + output; + } + }); - function normalizeObjectUnits(inputObject) { - var normalizedInput = {}, - normalizedProp, - prop; + // Side effect imports - for (prop in inputObject) { - if (hasOwnProp(inputObject, prop)) { - normalizedProp = normalizeUnits(prop); - if (normalizedProp) { - normalizedInput[normalizedProp] = inputObject[prop]; - } - } - } + hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale); + hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale); - return normalizedInput; - } + var mathAbs = Math.abs; - var priorities = {}; + function abs () { + var data = this._data; - function addUnitPriority(unit, priority) { - priorities[unit] = priority; - } + this._milliseconds = mathAbs(this._milliseconds); + this._days = mathAbs(this._days); + this._months = mathAbs(this._months); - function getPrioritizedUnits(unitsObj) { - var units = []; - for (var u in unitsObj) { - units.push({unit: u, priority: priorities[u]}); - } - units.sort(function (a, b) { - return a.priority - b.priority; - }); - return units; - } + data.milliseconds = mathAbs(data.milliseconds); + data.seconds = mathAbs(data.seconds); + data.minutes = mathAbs(data.minutes); + data.hours = mathAbs(data.hours); + data.months = mathAbs(data.months); + data.years = mathAbs(data.years); - function zeroFill(number, targetLength, forceSign) { - var absNumber = '' + Math.abs(number), - zerosToFill = targetLength - absNumber.length, - sign = number >= 0; - return (sign ? (forceSign ? '+' : '') : '-') + - Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber; + return this; } - var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g; + function addSubtract$1 (duration, input, value, direction) { + var other = createDuration(input, value); - var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; + duration._milliseconds += direction * other._milliseconds; + duration._days += direction * other._days; + duration._months += direction * other._months; - var formatFunctions = {}; + return duration._bubble(); + } - var formatTokenFunctions = {}; + // supports only 2.0-style add(1, 's') or add(duration) + function add$1 (input, value) { + return addSubtract$1(this, input, value, 1); + } - // token: 'M' - // padded: ['MM', 2] - // ordinal: 'Mo' - // callback: function () { this.month() + 1 } - function addFormatToken (token, padded, ordinal, callback) { - var func = callback; - if (typeof callback === 'string') { - func = function () { - return this[callback](); - }; - } - if (token) { - formatTokenFunctions[token] = func; - } - if (padded) { - formatTokenFunctions[padded[0]] = function () { - return zeroFill(func.apply(this, arguments), padded[1], padded[2]); - }; - } - if (ordinal) { - formatTokenFunctions[ordinal] = function () { - return this.localeData().ordinal(func.apply(this, arguments), token); - }; - } + // supports only 2.0-style subtract(1, 's') or subtract(duration) + function subtract$1 (input, value) { + return addSubtract$1(this, input, value, -1); } - function removeFormattingTokens(input) { - if (input.match(/\[[\s\S]/)) { - return input.replace(/^\[|\]$/g, ''); + function absCeil (number) { + if (number < 0) { + return Math.floor(number); + } else { + return Math.ceil(number); } - return input.replace(/\\/g, ''); } - function makeFormatFunction(format) { - var array = format.match(formattingTokens), i, length; + function bubble () { + var milliseconds = this._milliseconds; + var days = this._days; + var months = this._months; + var data = this._data; + var seconds, minutes, hours, years, monthsFromDays; - for (i = 0, length = array.length; i < length; i++) { - if (formatTokenFunctions[array[i]]) { - array[i] = formatTokenFunctions[array[i]]; - } else { - array[i] = removeFormattingTokens(array[i]); - } + // if we have a mix of positive and negative values, bubble down first + // check: https://github.com/moment/moment/issues/2166 + if (!((milliseconds >= 0 && days >= 0 && months >= 0) || + (milliseconds <= 0 && days <= 0 && months <= 0))) { + milliseconds += absCeil(monthsToDays(months) + days) * 864e5; + days = 0; + months = 0; } - return function (mom) { - var output = '', i; - for (i = 0; i < length; i++) { - output += isFunction(array[i]) ? array[i].call(mom, format) : array[i]; - } - return output; - }; - } + // The following code bubbles up values, see the tests for + // examples of what that means. + data.milliseconds = milliseconds % 1000; - // format date using native date object - function formatMoment(m, format) { - if (!m.isValid()) { - return m.localeData().invalidDate(); - } + seconds = absFloor(milliseconds / 1000); + data.seconds = seconds % 60; - format = expandFormat(format, m.localeData()); - formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format); + minutes = absFloor(seconds / 60); + data.minutes = minutes % 60; - return formatFunctions[format](m); - } + hours = absFloor(minutes / 60); + data.hours = hours % 24; - function expandFormat(format, locale) { - var i = 5; + days += absFloor(hours / 24); - function replaceLongDateFormatTokens(input) { - return locale.longDateFormat(input) || input; - } + // convert days to months + monthsFromDays = absFloor(daysToMonths(days)); + months += monthsFromDays; + days -= absCeil(monthsToDays(monthsFromDays)); - localFormattingTokens.lastIndex = 0; - while (i >= 0 && localFormattingTokens.test(format)) { - format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); - localFormattingTokens.lastIndex = 0; - i -= 1; - } - - return format; - } - - var match1 = /\d/; // 0 - 9 - var match2 = /\d\d/; // 00 - 99 - var match3 = /\d{3}/; // 000 - 999 - var match4 = /\d{4}/; // 0000 - 9999 - var match6 = /[+-]?\d{6}/; // -999999 - 999999 - var match1to2 = /\d\d?/; // 0 - 99 - var match3to4 = /\d\d\d\d?/; // 999 - 9999 - var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999 - var match1to3 = /\d{1,3}/; // 0 - 999 - var match1to4 = /\d{1,4}/; // 0 - 9999 - var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999 - - var matchUnsigned = /\d+/; // 0 - inf - var matchSigned = /[+-]?\d+/; // -inf - inf - - var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z - var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z - - var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123 - - // any word (or two) characters or numbers including two/three word month in arabic. - // includes scottish gaelic two word and hyphenated months - var matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i; + // 12 months -> 1 year + years = absFloor(months / 12); + months %= 12; - var regexes = {}; + data.days = days; + data.months = months; + data.years = years; - function addRegexToken (token, regex, strictRegex) { - regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) { - return (isStrict && strictRegex) ? strictRegex : regex; - }; + return this; } - function getParseRegexForToken (token, config) { - if (!hasOwnProp(regexes, token)) { - return new RegExp(unescapeFormat(token)); - } - - return regexes[token](config._strict, config._locale); + function daysToMonths (days) { + // 400 years have 146097 days (taking into account leap year rules) + // 400 years have 12 months === 4800 + return days * 4800 / 146097; } - // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript - function unescapeFormat(s) { - return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { - return p1 || p2 || p3 || p4; - })); + function monthsToDays (months) { + // the reverse of daysToMonths + return months * 146097 / 4800; } - function regexEscape(s) { - return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); - } + function as (units) { + if (!this.isValid()) { + return NaN; + } + var days; + var months; + var milliseconds = this._milliseconds; - var tokens = {}; + units = normalizeUnits(units); - function addParseToken (token, callback) { - var i, func = callback; - if (typeof token === 'string') { - token = [token]; - } - if (isNumber(callback)) { - func = function (input, array) { - array[callback] = toInt(input); - }; - } - for (i = 0; i < token.length; i++) { - tokens[token[i]] = func; + if (units === 'month' || units === 'quarter' || units === 'year') { + days = this._days + milliseconds / 864e5; + months = this._months + daysToMonths(days); + switch (units) { + case 'month': return months; + case 'quarter': return months / 3; + case 'year': return months / 12; + } + } else { + // handle milliseconds separately because of floating point math errors (issue #1867) + days = this._days + Math.round(monthsToDays(this._months)); + switch (units) { + case 'week' : return days / 7 + milliseconds / 6048e5; + case 'day' : return days + milliseconds / 864e5; + case 'hour' : return days * 24 + milliseconds / 36e5; + case 'minute' : return days * 1440 + milliseconds / 6e4; + case 'second' : return days * 86400 + milliseconds / 1000; + // Math.floor prevents floating point math errors here + case 'millisecond': return Math.floor(days * 864e5) + milliseconds; + default: throw new Error('Unknown unit ' + units); + } } } - function addWeekParseToken (token, callback) { - addParseToken(token, function (input, array, config, token) { - config._w = config._w || {}; - callback(input, config._w, config, token); - }); - } - - function addTimeToArrayFromToken(token, input, config) { - if (input != null && hasOwnProp(tokens, token)) { - tokens[token](input, config._a, config, token); + // TODO: Use this.as('ms')? + function valueOf$1 () { + if (!this.isValid()) { + return NaN; } + return ( + this._milliseconds + + this._days * 864e5 + + (this._months % 12) * 2592e6 + + toInt(this._months / 12) * 31536e6 + ); } - var YEAR = 0; - var MONTH = 1; - var DATE = 2; - var HOUR = 3; - var MINUTE = 4; - var SECOND = 5; - var MILLISECOND = 6; - var WEEK = 7; - var WEEKDAY = 8; - - // FORMATTING - - addFormatToken('Y', 0, 0, function () { - var y = this.year(); - return y <= 9999 ? '' + y : '+' + y; - }); + function makeAs (alias) { + return function () { + return this.as(alias); + }; + } - addFormatToken(0, ['YY', 2], 0, function () { - return this.year() % 100; - }); + var asMilliseconds = makeAs('ms'); + var asSeconds = makeAs('s'); + var asMinutes = makeAs('m'); + var asHours = makeAs('h'); + var asDays = makeAs('d'); + var asWeeks = makeAs('w'); + var asMonths = makeAs('M'); + var asQuarters = makeAs('Q'); + var asYears = makeAs('y'); - addFormatToken(0, ['YYYY', 4], 0, 'year'); - addFormatToken(0, ['YYYYY', 5], 0, 'year'); - addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); + function clone$1 () { + return createDuration(this); + } - // ALIASES + function get$2 (units) { + units = normalizeUnits(units); + return this.isValid() ? this[units + 's']() : NaN; + } - addUnitAlias('year', 'y'); + function makeGetter(name) { + return function () { + return this.isValid() ? this._data[name] : NaN; + }; + } - // PRIORITIES + var milliseconds = makeGetter('milliseconds'); + var seconds = makeGetter('seconds'); + var minutes = makeGetter('minutes'); + var hours = makeGetter('hours'); + var days = makeGetter('days'); + var months = makeGetter('months'); + var years = makeGetter('years'); - addUnitPriority('year', 1); + function weeks () { + return absFloor(this.days() / 7); + } - // PARSING + var round = Math.round; + var thresholds = { + ss: 44, // a few seconds to seconds + s : 45, // seconds to minute + m : 45, // minutes to hour + h : 22, // hours to day + d : 26, // days to month + M : 11 // months to year + }; - addRegexToken('Y', matchSigned); - addRegexToken('YY', match1to2, match2); - addRegexToken('YYYY', match1to4, match4); - addRegexToken('YYYYY', match1to6, match6); - addRegexToken('YYYYYY', match1to6, match6); + // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize + function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { + return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); + } - addParseToken(['YYYYY', 'YYYYYY'], YEAR); - addParseToken('YYYY', function (input, array) { - array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); - }); - addParseToken('YY', function (input, array) { - array[YEAR] = hooks.parseTwoDigitYear(input); - }); - addParseToken('Y', function (input, array) { - array[YEAR] = parseInt(input, 10); - }); + function relativeTime$1 (posNegDuration, withoutSuffix, locale) { + var duration = createDuration(posNegDuration).abs(); + var seconds = round(duration.as('s')); + var minutes = round(duration.as('m')); + var hours = round(duration.as('h')); + var days = round(duration.as('d')); + var months = round(duration.as('M')); + var years = round(duration.as('y')); - // HELPERS + var a = seconds <= thresholds.ss && ['s', seconds] || + seconds < thresholds.s && ['ss', seconds] || + minutes <= 1 && ['m'] || + minutes < thresholds.m && ['mm', minutes] || + hours <= 1 && ['h'] || + hours < thresholds.h && ['hh', hours] || + days <= 1 && ['d'] || + days < thresholds.d && ['dd', days] || + months <= 1 && ['M'] || + months < thresholds.M && ['MM', months] || + years <= 1 && ['y'] || ['yy', years]; - function daysInYear(year) { - return isLeapYear(year) ? 366 : 365; + a[2] = withoutSuffix; + a[3] = +posNegDuration > 0; + a[4] = locale; + return substituteTimeAgo.apply(null, a); } - function isLeapYear(year) { - return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; + // This function allows you to set the rounding function for relative time strings + function getSetRelativeTimeRounding (roundingFunction) { + if (roundingFunction === undefined) { + return round; + } + if (typeof(roundingFunction) === 'function') { + round = roundingFunction; + return true; + } + return false; } - // HOOKS - - hooks.parseTwoDigitYear = function (input) { - return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); - }; + // This function allows you to set a threshold for relative time strings + function getSetRelativeTimeThreshold (threshold, limit) { + if (thresholds[threshold] === undefined) { + return false; + } + if (limit === undefined) { + return thresholds[threshold]; + } + thresholds[threshold] = limit; + if (threshold === 's') { + thresholds.ss = limit - 1; + } + return true; + } - // MOMENTS + function humanize (withSuffix) { + if (!this.isValid()) { + return this.localeData().invalidDate(); + } - var getSetYear = makeGetSet('FullYear', true); + var locale = this.localeData(); + var output = relativeTime$1(this, !withSuffix, locale); - function getIsLeapYear () { - return isLeapYear(this.year()); - } + if (withSuffix) { + output = locale.pastFuture(+this, output); + } - function makeGetSet (unit, keepTime) { - return function (value) { - if (value != null) { - set$1(this, unit, value); - hooks.updateOffset(this, keepTime); - return this; - } else { - return get(this, unit); - } - }; + return locale.postformat(output); } - function get (mom, unit) { - return mom.isValid() ? - mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN; - } + var abs$1 = Math.abs; - function set$1 (mom, unit, value) { - if (mom.isValid() && !isNaN(value)) { - if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) { - mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month())); - } - else { - mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); - } - } + function sign(x) { + return ((x > 0) - (x < 0)) || +x; } - // MOMENTS - - function stringGet (units) { - units = normalizeUnits(units); - if (isFunction(this[units])) { - return this[units](); + function toISOString$1() { + // for ISO strings we do not use the normal bubbling rules: + // * milliseconds bubble up until they become hours + // * days do not bubble at all + // * months bubble up until they become years + // This is because there is no context-free conversion between hours and days + // (think of clock changes) + // and also not between days and months (28-31 days per month) + if (!this.isValid()) { + return this.localeData().invalidDate(); } - return this; - } + var seconds = abs$1(this._milliseconds) / 1000; + var days = abs$1(this._days); + var months = abs$1(this._months); + var minutes, hours, years; - function stringSet (units, value) { - if (typeof units === 'object') { - units = normalizeObjectUnits(units); - var prioritized = getPrioritizedUnits(units); - for (var i = 0; i < prioritized.length; i++) { - this[prioritized[i].unit](units[prioritized[i].unit]); - } - } else { - units = normalizeUnits(units); - if (isFunction(this[units])) { - return this[units](value); - } - } - return this; - } + // 3600 seconds -> 60 minutes -> 1 hour + minutes = absFloor(seconds / 60); + hours = absFloor(minutes / 60); + seconds %= 60; + minutes %= 60; - function mod(n, x) { - return ((n % x) + x) % x; - } + // 12 months -> 1 year + years = absFloor(months / 12); + months %= 12; - var indexOf; - if (Array.prototype.indexOf) { - indexOf = Array.prototype.indexOf; - } else { - indexOf = function (o) { - // I know - var i; - for (i = 0; i < this.length; ++i) { - if (this[i] === o) { - return i; - } - } - return -1; - }; - } + // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js + var Y = years; + var M = months; + var D = days; + var h = hours; + var m = minutes; + var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : ''; + var total = this.asSeconds(); - function daysInMonth(year, month) { - if (isNaN(year) || isNaN(month)) { - return NaN; + if (!total) { + // this is the same as C#'s (Noda) and python (isodate)... + // but not other JS (goog.date) + return 'P0D'; } - var modMonth = mod(month, 12); - year += (month - modMonth) / 12; - return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2); - } - // FORMATTING + var totalSign = total < 0 ? '-' : ''; + var ymSign = sign(this._months) !== sign(total) ? '-' : ''; + var daysSign = sign(this._days) !== sign(total) ? '-' : ''; + var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : ''; - addFormatToken('M', ['MM', 2], 'Mo', function () { - return this.month() + 1; - }); + return totalSign + 'P' + + (Y ? ymSign + Y + 'Y' : '') + + (M ? ymSign + M + 'M' : '') + + (D ? daysSign + D + 'D' : '') + + ((h || m || s) ? 'T' : '') + + (h ? hmsSign + h + 'H' : '') + + (m ? hmsSign + m + 'M' : '') + + (s ? hmsSign + s + 'S' : ''); + } - addFormatToken('MMM', 0, 0, function (format) { - return this.localeData().monthsShort(this, format); - }); + var proto$2 = Duration.prototype; - addFormatToken('MMMM', 0, 0, function (format) { - return this.localeData().months(this, format); - }); + proto$2.isValid = isValid$1; + proto$2.abs = abs; + proto$2.add = add$1; + proto$2.subtract = subtract$1; + proto$2.as = as; + proto$2.asMilliseconds = asMilliseconds; + proto$2.asSeconds = asSeconds; + proto$2.asMinutes = asMinutes; + proto$2.asHours = asHours; + proto$2.asDays = asDays; + proto$2.asWeeks = asWeeks; + proto$2.asMonths = asMonths; + proto$2.asQuarters = asQuarters; + proto$2.asYears = asYears; + proto$2.valueOf = valueOf$1; + proto$2._bubble = bubble; + proto$2.clone = clone$1; + proto$2.get = get$2; + proto$2.milliseconds = milliseconds; + proto$2.seconds = seconds; + proto$2.minutes = minutes; + proto$2.hours = hours; + proto$2.days = days; + proto$2.weeks = weeks; + proto$2.months = months; + proto$2.years = years; + proto$2.humanize = humanize; + proto$2.toISOString = toISOString$1; + proto$2.toString = toISOString$1; + proto$2.toJSON = toISOString$1; + proto$2.locale = locale; + proto$2.localeData = localeData; - // ALIASES + proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1); + proto$2.lang = lang; - addUnitAlias('month', 'M'); + // Side effect imports - // PRIORITY + // FORMATTING - addUnitPriority('month', 8); + addFormatToken('X', 0, 0, 'unix'); + addFormatToken('x', 0, 0, 'valueOf'); // PARSING - addRegexToken('M', match1to2); - addRegexToken('MM', match1to2, match2); - addRegexToken('MMM', function (isStrict, locale) { - return locale.monthsShortRegex(isStrict); - }); - addRegexToken('MMMM', function (isStrict, locale) { - return locale.monthsRegex(isStrict); + addRegexToken('x', matchSigned); + addRegexToken('X', matchTimestamp); + addParseToken('X', function (input, array, config) { + config._d = new Date(parseFloat(input, 10) * 1000); }); - - addParseToken(['M', 'MM'], function (input, array) { - array[MONTH] = toInt(input) - 1; + addParseToken('x', function (input, array, config) { + config._d = new Date(toInt(input)); }); - addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { - var month = config._locale.monthsParse(input, token, config._strict); - // if we didn't find a month name, mark the date as invalid. - if (month != null) { - array[MONTH] = month; - } else { - getParsingFlags(config).invalidMonth = input; - } - }); + // Side effect imports - // LOCALES - var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/; - var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'); - function localeMonths (m, format) { - if (!m) { - return isArray(this._months) ? this._months : - this._months['standalone']; - } - return isArray(this._months) ? this._months[m.month()] : - this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()]; - } + hooks.version = '2.24.0'; - var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'); - function localeMonthsShort (m, format) { - if (!m) { - return isArray(this._monthsShort) ? this._monthsShort : - this._monthsShort['standalone']; - } - return isArray(this._monthsShort) ? this._monthsShort[m.month()] : - this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()]; - } + setHookCallback(createLocal); - function handleStrictParse(monthName, format, strict) { - var i, ii, mom, llc = monthName.toLocaleLowerCase(); - if (!this._monthsParse) { - // this is not used - this._monthsParse = []; - this._longMonthsParse = []; - this._shortMonthsParse = []; - for (i = 0; i < 12; ++i) { - mom = createUTC([2000, i]); - this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase(); - this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase(); - } - } + hooks.fn = proto; + hooks.min = min; + hooks.max = max; + hooks.now = now; + hooks.utc = createUTC; + hooks.unix = createUnix; + hooks.months = listMonths; + hooks.isDate = isDate; + hooks.locale = getSetGlobalLocale; + hooks.invalid = createInvalid; + hooks.duration = createDuration; + hooks.isMoment = isMoment; + hooks.weekdays = listWeekdays; + hooks.parseZone = createInZone; + hooks.localeData = getLocale; + hooks.isDuration = isDuration; + hooks.monthsShort = listMonthsShort; + hooks.weekdaysMin = listWeekdaysMin; + hooks.defineLocale = defineLocale; + hooks.updateLocale = updateLocale; + hooks.locales = listLocales; + hooks.weekdaysShort = listWeekdaysShort; + hooks.normalizeUnits = normalizeUnits; + hooks.relativeTimeRounding = getSetRelativeTimeRounding; + hooks.relativeTimeThreshold = getSetRelativeTimeThreshold; + hooks.calendarFormat = getCalendarFormat; + hooks.prototype = proto; - if (strict) { - if (format === 'MMM') { - ii = indexOf.call(this._shortMonthsParse, llc); - return ii !== -1 ? ii : null; - } else { - ii = indexOf.call(this._longMonthsParse, llc); - return ii !== -1 ? ii : null; - } - } else { - if (format === 'MMM') { - ii = indexOf.call(this._shortMonthsParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._longMonthsParse, llc); - return ii !== -1 ? ii : null; - } else { - ii = indexOf.call(this._longMonthsParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._shortMonthsParse, llc); - return ii !== -1 ? ii : null; - } - } - } + // currently HTML5 input type only supports 24-hour formats + hooks.HTML5_FMT = { + DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // + DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // + DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // + DATE: 'YYYY-MM-DD', // + TIME: 'HH:mm', // + TIME_SECONDS: 'HH:mm:ss', // + TIME_MS: 'HH:mm:ss.SSS', // + WEEK: 'GGGG-[W]WW', // + MONTH: 'YYYY-MM' // + }; - function localeMonthsParse (monthName, format, strict) { - var i, mom, regex; + return hooks; - if (this._monthsParseExact) { - return handleStrictParse.call(this, monthName, format, strict); - } +}))); - if (!this._monthsParse) { - this._monthsParse = []; - this._longMonthsParse = []; - this._shortMonthsParse = []; - } +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(11)(module))) - // TODO: add sorting - // Sorting makes sure if one month (or abbr) is a prefix of another - // see sorting in computeMonthsParse - for (i = 0; i < 12; i++) { - // make the regex if we don't have it already - mom = createUTC([2000, i]); - if (strict && !this._longMonthsParse[i]) { - this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'); - this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i'); - } - if (!strict && !this._monthsParse[i]) { - regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); - this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); - } - // test the regex - if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) { - return i; - } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) { - return i; - } else if (!strict && this._monthsParse[i].test(monthName)) { - return i; - } - } - } +/***/ }), +/* 11 */ +/***/ (function(module, exports) { - // MOMENTS +module.exports = function(module) { + if (!module.webpackPolyfill) { + module.deprecate = function() {}; + module.paths = []; + // module.parent = undefined by default + if (!module.children) module.children = []; + Object.defineProperty(module, "loaded", { + enumerable: true, + get: function() { + return module.l; + } + }); + Object.defineProperty(module, "id", { + enumerable: true, + get: function() { + return module.i; + } + }); + module.webpackPolyfill = 1; + } + return module; +}; - function setMonth (mom, value) { - var dayOfMonth; - if (!mom.isValid()) { - // No op - return mom; - } +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { - if (typeof value === 'string') { - if (/^\d+$/.test(value)) { - value = toInt(value); - } else { - value = mom.localeData().monthsParse(value); - // TODO: Another silent failure? - if (!isNumber(value)) { - return mom; - } - } - } +var map = { + "./af": 13, + "./af.js": 13, + "./ar": 14, + "./ar-dz": 15, + "./ar-dz.js": 15, + "./ar-kw": 16, + "./ar-kw.js": 16, + "./ar-ly": 17, + "./ar-ly.js": 17, + "./ar-ma": 18, + "./ar-ma.js": 18, + "./ar-sa": 19, + "./ar-sa.js": 19, + "./ar-tn": 20, + "./ar-tn.js": 20, + "./ar.js": 14, + "./az": 21, + "./az.js": 21, + "./be": 22, + "./be.js": 22, + "./bg": 23, + "./bg.js": 23, + "./bm": 24, + "./bm.js": 24, + "./bn": 25, + "./bn.js": 25, + "./bo": 26, + "./bo.js": 26, + "./br": 27, + "./br.js": 27, + "./bs": 28, + "./bs.js": 28, + "./ca": 29, + "./ca.js": 29, + "./cs": 30, + "./cs.js": 30, + "./cv": 31, + "./cv.js": 31, + "./cy": 32, + "./cy.js": 32, + "./da": 33, + "./da.js": 33, + "./de": 34, + "./de-at": 35, + "./de-at.js": 35, + "./de-ch": 36, + "./de-ch.js": 36, + "./de.js": 34, + "./dv": 37, + "./dv.js": 37, + "./el": 38, + "./el.js": 38, + "./en-SG": 39, + "./en-SG.js": 39, + "./en-au": 40, + "./en-au.js": 40, + "./en-ca": 41, + "./en-ca.js": 41, + "./en-gb": 42, + "./en-gb.js": 42, + "./en-ie": 43, + "./en-ie.js": 43, + "./en-il": 44, + "./en-il.js": 44, + "./en-nz": 45, + "./en-nz.js": 45, + "./eo": 46, + "./eo.js": 46, + "./es": 47, + "./es-do": 48, + "./es-do.js": 48, + "./es-us": 49, + "./es-us.js": 49, + "./es.js": 47, + "./et": 50, + "./et.js": 50, + "./eu": 51, + "./eu.js": 51, + "./fa": 52, + "./fa.js": 52, + "./fi": 53, + "./fi.js": 53, + "./fo": 54, + "./fo.js": 54, + "./fr": 55, + "./fr-ca": 56, + "./fr-ca.js": 56, + "./fr-ch": 57, + "./fr-ch.js": 57, + "./fr.js": 55, + "./fy": 58, + "./fy.js": 58, + "./ga": 59, + "./ga.js": 59, + "./gd": 60, + "./gd.js": 60, + "./gl": 61, + "./gl.js": 61, + "./gom-latn": 62, + "./gom-latn.js": 62, + "./gu": 63, + "./gu.js": 63, + "./he": 64, + "./he.js": 64, + "./hi": 65, + "./hi.js": 65, + "./hr": 66, + "./hr.js": 66, + "./hu": 67, + "./hu.js": 67, + "./hy-am": 68, + "./hy-am.js": 68, + "./id": 69, + "./id.js": 69, + "./is": 70, + "./is.js": 70, + "./it": 71, + "./it-ch": 72, + "./it-ch.js": 72, + "./it.js": 71, + "./ja": 73, + "./ja.js": 73, + "./jv": 74, + "./jv.js": 74, + "./ka": 75, + "./ka.js": 75, + "./kk": 76, + "./kk.js": 76, + "./km": 77, + "./km.js": 77, + "./kn": 78, + "./kn.js": 78, + "./ko": 79, + "./ko.js": 79, + "./ku": 80, + "./ku.js": 80, + "./ky": 81, + "./ky.js": 81, + "./lb": 82, + "./lb.js": 82, + "./lo": 83, + "./lo.js": 83, + "./lt": 84, + "./lt.js": 84, + "./lv": 85, + "./lv.js": 85, + "./me": 86, + "./me.js": 86, + "./mi": 87, + "./mi.js": 87, + "./mk": 88, + "./mk.js": 88, + "./ml": 89, + "./ml.js": 89, + "./mn": 90, + "./mn.js": 90, + "./mr": 91, + "./mr.js": 91, + "./ms": 92, + "./ms-my": 93, + "./ms-my.js": 93, + "./ms.js": 92, + "./mt": 94, + "./mt.js": 94, + "./my": 95, + "./my.js": 95, + "./nb": 96, + "./nb.js": 96, + "./ne": 97, + "./ne.js": 97, + "./nl": 98, + "./nl-be": 99, + "./nl-be.js": 99, + "./nl.js": 98, + "./nn": 100, + "./nn.js": 100, + "./pa-in": 101, + "./pa-in.js": 101, + "./pl": 102, + "./pl.js": 102, + "./pt": 103, + "./pt-br": 104, + "./pt-br.js": 104, + "./pt.js": 103, + "./ro": 105, + "./ro.js": 105, + "./ru": 106, + "./ru.js": 106, + "./sd": 107, + "./sd.js": 107, + "./se": 108, + "./se.js": 108, + "./si": 109, + "./si.js": 109, + "./sk": 110, + "./sk.js": 110, + "./sl": 111, + "./sl.js": 111, + "./sq": 112, + "./sq.js": 112, + "./sr": 113, + "./sr-cyrl": 114, + "./sr-cyrl.js": 114, + "./sr.js": 113, + "./ss": 115, + "./ss.js": 115, + "./sv": 116, + "./sv.js": 116, + "./sw": 117, + "./sw.js": 117, + "./ta": 118, + "./ta.js": 118, + "./te": 119, + "./te.js": 119, + "./tet": 120, + "./tet.js": 120, + "./tg": 121, + "./tg.js": 121, + "./th": 122, + "./th.js": 122, + "./tl-ph": 123, + "./tl-ph.js": 123, + "./tlh": 124, + "./tlh.js": 124, + "./tr": 125, + "./tr.js": 125, + "./tzl": 126, + "./tzl.js": 126, + "./tzm": 127, + "./tzm-latn": 128, + "./tzm-latn.js": 128, + "./tzm.js": 127, + "./ug-cn": 129, + "./ug-cn.js": 129, + "./uk": 130, + "./uk.js": 130, + "./ur": 131, + "./ur.js": 131, + "./uz": 132, + "./uz-latn": 133, + "./uz-latn.js": 133, + "./uz.js": 132, + "./vi": 134, + "./vi.js": 134, + "./x-pseudo": 135, + "./x-pseudo.js": 135, + "./yo": 136, + "./yo.js": 136, + "./zh-cn": 137, + "./zh-cn.js": 137, + "./zh-hk": 138, + "./zh-hk.js": 138, + "./zh-tw": 139, + "./zh-tw.js": 139 +}; - dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); - mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); - return mom; - } - function getSetMonth (value) { - if (value != null) { - setMonth(this, value); - hooks.updateOffset(this, true); - return this; - } else { - return get(this, 'Month'); - } - } +function webpackContext(req) { + var id = webpackContextResolve(req); + return __webpack_require__(id); +} +function webpackContextResolve(req) { + if(!__webpack_require__.o(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return map[req]; +} +webpackContext.keys = function webpackContextKeys() { + return Object.keys(map); +}; +webpackContext.resolve = webpackContextResolve; +module.exports = webpackContext; +webpackContext.id = 12; - function getDaysInMonth () { - return daysInMonth(this.year(), this.month()); - } +/***/ }), +/* 13 */ +/***/ (function(module, exports, __webpack_require__) { - var defaultMonthsShortRegex = matchWord; - function monthsShortRegex (isStrict) { - if (this._monthsParseExact) { - if (!hasOwnProp(this, '_monthsRegex')) { - computeMonthsParse.call(this); - } - if (isStrict) { - return this._monthsShortStrictRegex; - } else { - return this._monthsShortRegex; - } - } else { - if (!hasOwnProp(this, '_monthsShortRegex')) { - this._monthsShortRegex = defaultMonthsShortRegex; - } - return this._monthsShortStrictRegex && isStrict ? - this._monthsShortStrictRegex : this._monthsShortRegex; - } - } +//! moment.js locale configuration - var defaultMonthsRegex = matchWord; - function monthsRegex (isStrict) { - if (this._monthsParseExact) { - if (!hasOwnProp(this, '_monthsRegex')) { - computeMonthsParse.call(this); - } - if (isStrict) { - return this._monthsStrictRegex; +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; + + + var af = moment.defineLocale('af', { + months : 'Januarie_Februarie_Maart_April_Mei_Junie_Julie_Augustus_September_Oktober_November_Desember'.split('_'), + monthsShort : 'Jan_Feb_Mrt_Apr_Mei_Jun_Jul_Aug_Sep_Okt_Nov_Des'.split('_'), + weekdays : 'Sondag_Maandag_Dinsdag_Woensdag_Donderdag_Vrydag_Saterdag'.split('_'), + weekdaysShort : 'Son_Maa_Din_Woe_Don_Vry_Sat'.split('_'), + weekdaysMin : 'So_Ma_Di_Wo_Do_Vr_Sa'.split('_'), + meridiemParse: /vm|nm/i, + isPM : function (input) { + return /^nm$/i.test(input); + }, + meridiem : function (hours, minutes, isLower) { + if (hours < 12) { + return isLower ? 'vm' : 'VM'; } else { - return this._monthsRegex; - } - } else { - if (!hasOwnProp(this, '_monthsRegex')) { - this._monthsRegex = defaultMonthsRegex; + return isLower ? 'nm' : 'NM'; } - return this._monthsStrictRegex && isStrict ? - this._monthsStrictRegex : this._monthsRegex; + }, + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd, D MMMM YYYY HH:mm' + }, + calendar : { + sameDay : '[Vandag om] LT', + nextDay : '[Môre om] LT', + nextWeek : 'dddd [om] LT', + lastDay : '[Gister om] LT', + lastWeek : '[Laas] dddd [om] LT', + sameElse : 'L' + }, + relativeTime : { + future : 'oor %s', + past : '%s gelede', + s : '\'n paar sekondes', + ss : '%d sekondes', + m : '\'n minuut', + mm : '%d minute', + h : '\'n uur', + hh : '%d ure', + d : '\'n dag', + dd : '%d dae', + M : '\'n maand', + MM : '%d maande', + y : '\'n jaar', + yy : '%d jaar' + }, + dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, + ordinal : function (number) { + return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); // Thanks to Joris Röling : https://github.com/jjupiter + }, + week : { + dow : 1, // Maandag is die eerste dag van die week. + doy : 4 // Die week wat die 4de Januarie bevat is die eerste week van die jaar. } - } + }); - function computeMonthsParse () { - function cmpLenRev(a, b) { - return b.length - a.length; - } + return af; - var shortPieces = [], longPieces = [], mixedPieces = [], - i, mom; - for (i = 0; i < 12; i++) { - // make the regex if we don't have it already - mom = createUTC([2000, i]); - shortPieces.push(this.monthsShort(mom, '')); - longPieces.push(this.months(mom, '')); - mixedPieces.push(this.months(mom, '')); - mixedPieces.push(this.monthsShort(mom, '')); - } - // Sorting makes sure if one month (or abbr) is a prefix of another it - // will match the longer piece. - shortPieces.sort(cmpLenRev); - longPieces.sort(cmpLenRev); - mixedPieces.sort(cmpLenRev); - for (i = 0; i < 12; i++) { - shortPieces[i] = regexEscape(shortPieces[i]); - longPieces[i] = regexEscape(longPieces[i]); - } - for (i = 0; i < 24; i++) { - mixedPieces[i] = regexEscape(mixedPieces[i]); - } +}))); - this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); - this._monthsShortRegex = this._monthsRegex; - this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); - this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); - } - function createDate (y, m, d, h, M, s, ms) { - // can't just apply() to create a date: - // https://stackoverflow.com/q/181348 - var date; - // the date constructor remaps years 0-99 to 1900-1999 - if (y < 100 && y >= 0) { - // preserve leap years using a full 400 year cycle, then reset - date = new Date(y + 400, m, d, h, M, s, ms); - if (isFinite(date.getFullYear())) { - date.setFullYear(y); - } - } else { - date = new Date(y, m, d, h, M, s, ms); - } +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { - return date; - } +//! moment.js locale configuration - function createUTCDate (y) { - var date; - // the Date.UTC function remaps years 0-99 to 1900-1999 - if (y < 100 && y >= 0) { - var args = Array.prototype.slice.call(arguments); - // preserve leap years using a full 400 year cycle, then reset - args[0] = y + 400; - date = new Date(Date.UTC.apply(null, args)); - if (isFinite(date.getUTCFullYear())) { - date.setUTCFullYear(y); +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; + + + var symbolMap = { + '1': '١', + '2': '٢', + '3': '٣', + '4': '٤', + '5': '٥', + '6': '٦', + '7': '٧', + '8': '٨', + '9': '٩', + '0': '٠' + }, numberMap = { + '١': '1', + '٢': '2', + '٣': '3', + '٤': '4', + '٥': '5', + '٦': '6', + '٧': '7', + '٨': '8', + '٩': '9', + '٠': '0' + }, pluralForm = function (n) { + return n === 0 ? 0 : n === 1 ? 1 : n === 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5; + }, plurals = { + s : ['أقل من ثانية', 'ثانية واحدة', ['ثانيتان', 'ثانيتين'], '%d ثوان', '%d ثانية', '%d ثانية'], + m : ['أقل من دقيقة', 'دقيقة واحدة', ['دقيقتان', 'دقيقتين'], '%d دقائق', '%d دقيقة', '%d دقيقة'], + h : ['أقل من ساعة', 'ساعة واحدة', ['ساعتان', 'ساعتين'], '%d ساعات', '%d ساعة', '%d ساعة'], + d : ['أقل من يوم', 'يوم واحد', ['يومان', 'يومين'], '%d أيام', '%d يومًا', '%d يوم'], + M : ['أقل من شهر', 'شهر واحد', ['شهران', 'شهرين'], '%d أشهر', '%d شهرا', '%d شهر'], + y : ['أقل من عام', 'عام واحد', ['عامان', 'عامين'], '%d أعوام', '%d عامًا', '%d عام'] + }, pluralize = function (u) { + return function (number, withoutSuffix, string, isFuture) { + var f = pluralForm(number), + str = plurals[u][pluralForm(number)]; + if (f === 2) { + str = str[withoutSuffix ? 0 : 1]; } - } else { - date = new Date(Date.UTC.apply(null, arguments)); + return str.replace(/%d/i, number); + }; + }, months = [ + 'يناير', + 'فبراير', + 'مارس', + 'أبريل', + 'مايو', + 'يونيو', + 'يوليو', + 'أغسطس', + 'سبتمبر', + 'أكتوبر', + 'نوفمبر', + 'ديسمبر' + ]; + + var ar = moment.defineLocale('ar', { + months : months, + monthsShort : months, + weekdays : 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), + weekdaysShort : 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), + weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'D/\u200FM/\u200FYYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd D MMMM YYYY HH:mm' + }, + meridiemParse: /ص|م/, + isPM : function (input) { + return 'م' === input; + }, + meridiem : function (hour, minute, isLower) { + if (hour < 12) { + return 'ص'; + } else { + return 'م'; + } + }, + calendar : { + sameDay: '[اليوم عند الساعة] LT', + nextDay: '[غدًا عند الساعة] LT', + nextWeek: 'dddd [عند الساعة] LT', + lastDay: '[أمس عند الساعة] LT', + lastWeek: 'dddd [عند الساعة] LT', + sameElse: 'L' + }, + relativeTime : { + future : 'بعد %s', + past : 'منذ %s', + s : pluralize('s'), + ss : pluralize('s'), + m : pluralize('m'), + mm : pluralize('m'), + h : pluralize('h'), + hh : pluralize('h'), + d : pluralize('d'), + dd : pluralize('d'), + M : pluralize('M'), + MM : pluralize('M'), + y : pluralize('y'), + yy : pluralize('y') + }, + preparse: function (string) { + return string.replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) { + return numberMap[match]; + }).replace(/،/g, ','); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }).replace(/,/g, '،'); + }, + week : { + dow : 6, // Saturday is the first day of the week. + doy : 12 // The week that contains Jan 12th is the first week of the year. } + }); - return date; - } + return ar; - // start-of-first-week - start-of-year - function firstWeekOffset(year, dow, doy) { - var // first-week day -- which january is always in the first week (4 for iso, 1 for other) - fwd = 7 + dow - doy, - // first-week day local weekday -- which local weekday is fwd - fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; +}))); - return -fwdlw + fwd - 1; - } - // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday - function dayOfYearFromWeeks(year, week, weekday, dow, doy) { - var localWeekday = (7 + weekday - dow) % 7, - weekOffset = firstWeekOffset(year, dow, doy), - dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, - resYear, resDayOfYear; +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { - if (dayOfYear <= 0) { - resYear = year - 1; - resDayOfYear = daysInYear(resYear) + dayOfYear; - } else if (dayOfYear > daysInYear(year)) { - resYear = year + 1; - resDayOfYear = dayOfYear - daysInYear(year); - } else { - resYear = year; - resDayOfYear = dayOfYear; - } +//! moment.js locale configuration - return { - year: resYear, - dayOfYear: resDayOfYear - }; - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - function weekOfYear(mom, dow, doy) { - var weekOffset = firstWeekOffset(mom.year(), dow, doy), - week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, - resWeek, resYear; - if (week < 1) { - resYear = mom.year() - 1; - resWeek = week + weeksInYear(resYear, dow, doy); - } else if (week > weeksInYear(mom.year(), dow, doy)) { - resWeek = week - weeksInYear(mom.year(), dow, doy); - resYear = mom.year() + 1; - } else { - resYear = mom.year(); - resWeek = week; + var arDz = moment.defineLocale('ar-dz', { + months : 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), + monthsShort : 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), + weekdays : 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), + weekdaysShort : 'احد_اثنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'), + weekdaysMin : 'أح_إث_ثلا_أر_خم_جم_سب'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd D MMMM YYYY HH:mm' + }, + calendar : { + sameDay: '[اليوم على الساعة] LT', + nextDay: '[غدا على الساعة] LT', + nextWeek: 'dddd [على الساعة] LT', + lastDay: '[أمس على الساعة] LT', + lastWeek: 'dddd [على الساعة] LT', + sameElse: 'L' + }, + relativeTime : { + future : 'في %s', + past : 'منذ %s', + s : 'ثوان', + ss : '%d ثانية', + m : 'دقيقة', + mm : '%d دقائق', + h : 'ساعة', + hh : '%d ساعات', + d : 'يوم', + dd : '%d أيام', + M : 'شهر', + MM : '%d أشهر', + y : 'سنة', + yy : '%d سنوات' + }, + week : { + dow : 0, // Sunday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } + }); - return { - week: resWeek, - year: resYear - }; - } + return arDz; - function weeksInYear(year, dow, doy) { - var weekOffset = firstWeekOffset(year, dow, doy), - weekOffsetNext = firstWeekOffset(year + 1, dow, doy); - return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; - } +}))); - // FORMATTING - addFormatToken('w', ['ww', 2], 'wo', 'week'); - addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { - // ALIASES +//! moment.js locale configuration - addUnitAlias('week', 'w'); - addUnitAlias('isoWeek', 'W'); +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - // PRIORITIES - addUnitPriority('week', 5); - addUnitPriority('isoWeek', 5); + var arKw = moment.defineLocale('ar-kw', { + months : 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'), + monthsShort : 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'), + weekdays : 'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), + weekdaysShort : 'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'), + weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd D MMMM YYYY HH:mm' + }, + calendar : { + sameDay: '[اليوم على الساعة] LT', + nextDay: '[غدا على الساعة] LT', + nextWeek: 'dddd [على الساعة] LT', + lastDay: '[أمس على الساعة] LT', + lastWeek: 'dddd [على الساعة] LT', + sameElse: 'L' + }, + relativeTime : { + future : 'في %s', + past : 'منذ %s', + s : 'ثوان', + ss : '%d ثانية', + m : 'دقيقة', + mm : '%d دقائق', + h : 'ساعة', + hh : '%d ساعات', + d : 'يوم', + dd : '%d أيام', + M : 'شهر', + MM : '%d أشهر', + y : 'سنة', + yy : '%d سنوات' + }, + week : { + dow : 0, // Sunday is the first day of the week. + doy : 12 // The week that contains Jan 12th is the first week of the year. + } + }); - // PARSING + return arKw; - addRegexToken('w', match1to2); - addRegexToken('ww', match1to2, match2); - addRegexToken('W', match1to2); - addRegexToken('WW', match1to2, match2); +}))); - addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) { - week[token.substr(0, 1)] = toInt(input); - }); - // HELPERS +/***/ }), +/* 17 */ +/***/ (function(module, exports, __webpack_require__) { - // LOCALES +//! moment.js locale configuration - function localeWeek (mom) { - return weekOfYear(mom, this._week.dow, this._week.doy).week; - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - var defaultLocaleWeek = { - dow : 0, // Sunday is the first day of the week. - doy : 6 // The week that contains Jan 6th is the first week of the year. - }; - function localeFirstDayOfWeek () { - return this._week.dow; - } + var symbolMap = { + '1': '1', + '2': '2', + '3': '3', + '4': '4', + '5': '5', + '6': '6', + '7': '7', + '8': '8', + '9': '9', + '0': '0' + }, pluralForm = function (n) { + return n === 0 ? 0 : n === 1 ? 1 : n === 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5; + }, plurals = { + s : ['أقل من ثانية', 'ثانية واحدة', ['ثانيتان', 'ثانيتين'], '%d ثوان', '%d ثانية', '%d ثانية'], + m : ['أقل من دقيقة', 'دقيقة واحدة', ['دقيقتان', 'دقيقتين'], '%d دقائق', '%d دقيقة', '%d دقيقة'], + h : ['أقل من ساعة', 'ساعة واحدة', ['ساعتان', 'ساعتين'], '%d ساعات', '%d ساعة', '%d ساعة'], + d : ['أقل من يوم', 'يوم واحد', ['يومان', 'يومين'], '%d أيام', '%d يومًا', '%d يوم'], + M : ['أقل من شهر', 'شهر واحد', ['شهران', 'شهرين'], '%d أشهر', '%d شهرا', '%d شهر'], + y : ['أقل من عام', 'عام واحد', ['عامان', 'عامين'], '%d أعوام', '%d عامًا', '%d عام'] + }, pluralize = function (u) { + return function (number, withoutSuffix, string, isFuture) { + var f = pluralForm(number), + str = plurals[u][pluralForm(number)]; + if (f === 2) { + str = str[withoutSuffix ? 0 : 1]; + } + return str.replace(/%d/i, number); + }; + }, months = [ + 'يناير', + 'فبراير', + 'مارس', + 'أبريل', + 'مايو', + 'يونيو', + 'يوليو', + 'أغسطس', + 'سبتمبر', + 'أكتوبر', + 'نوفمبر', + 'ديسمبر' + ]; - function localeFirstDayOfYear () { - return this._week.doy; - } + var arLy = moment.defineLocale('ar-ly', { + months : months, + monthsShort : months, + weekdays : 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), + weekdaysShort : 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), + weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'D/\u200FM/\u200FYYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd D MMMM YYYY HH:mm' + }, + meridiemParse: /ص|م/, + isPM : function (input) { + return 'م' === input; + }, + meridiem : function (hour, minute, isLower) { + if (hour < 12) { + return 'ص'; + } else { + return 'م'; + } + }, + calendar : { + sameDay: '[اليوم عند الساعة] LT', + nextDay: '[غدًا عند الساعة] LT', + nextWeek: 'dddd [عند الساعة] LT', + lastDay: '[أمس عند الساعة] LT', + lastWeek: 'dddd [عند الساعة] LT', + sameElse: 'L' + }, + relativeTime : { + future : 'بعد %s', + past : 'منذ %s', + s : pluralize('s'), + ss : pluralize('s'), + m : pluralize('m'), + mm : pluralize('m'), + h : pluralize('h'), + hh : pluralize('h'), + d : pluralize('d'), + dd : pluralize('d'), + M : pluralize('M'), + MM : pluralize('M'), + y : pluralize('y'), + yy : pluralize('y') + }, + preparse: function (string) { + return string.replace(/،/g, ','); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }).replace(/,/g, '،'); + }, + week : { + dow : 6, // Saturday is the first day of the week. + doy : 12 // The week that contains Jan 12th is the first week of the year. + } + }); - // MOMENTS + return arLy; - function getSetWeek (input) { - var week = this.localeData().week(this); - return input == null ? week : this.add((input - week) * 7, 'd'); - } +}))); - function getSetISOWeek (input) { - var week = weekOfYear(this, 1, 4).week; - return input == null ? week : this.add((input - week) * 7, 'd'); - } - // FORMATTING +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { - addFormatToken('d', 0, 'do', 'day'); +//! moment.js locale configuration - addFormatToken('dd', 0, 0, function (format) { - return this.localeData().weekdaysMin(this, format); - }); +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - addFormatToken('ddd', 0, 0, function (format) { - return this.localeData().weekdaysShort(this, format); - }); - addFormatToken('dddd', 0, 0, function (format) { - return this.localeData().weekdays(this, format); + var arMa = moment.defineLocale('ar-ma', { + months : 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'), + monthsShort : 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'), + weekdays : 'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), + weekdaysShort : 'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'), + weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd D MMMM YYYY HH:mm' + }, + calendar : { + sameDay: '[اليوم على الساعة] LT', + nextDay: '[غدا على الساعة] LT', + nextWeek: 'dddd [على الساعة] LT', + lastDay: '[أمس على الساعة] LT', + lastWeek: 'dddd [على الساعة] LT', + sameElse: 'L' + }, + relativeTime : { + future : 'في %s', + past : 'منذ %s', + s : 'ثوان', + ss : '%d ثانية', + m : 'دقيقة', + mm : '%d دقائق', + h : 'ساعة', + hh : '%d ساعات', + d : 'يوم', + dd : '%d أيام', + M : 'شهر', + MM : '%d أشهر', + y : 'سنة', + yy : '%d سنوات' + }, + week : { + dow : 6, // Saturday is the first day of the week. + doy : 12 // The week that contains Jan 12th is the first week of the year. + } }); - addFormatToken('e', 0, 0, 'weekday'); - addFormatToken('E', 0, 0, 'isoWeekday'); + return arMa; - // ALIASES +}))); - addUnitAlias('day', 'd'); - addUnitAlias('weekday', 'e'); - addUnitAlias('isoWeekday', 'E'); - // PRIORITY - addUnitPriority('day', 11); - addUnitPriority('weekday', 11); - addUnitPriority('isoWeekday', 11); +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { - // PARSING +//! moment.js locale configuration - addRegexToken('d', match1to2); - addRegexToken('e', match1to2); - addRegexToken('E', match1to2); - addRegexToken('dd', function (isStrict, locale) { - return locale.weekdaysMinRegex(isStrict); - }); - addRegexToken('ddd', function (isStrict, locale) { - return locale.weekdaysShortRegex(isStrict); - }); - addRegexToken('dddd', function (isStrict, locale) { - return locale.weekdaysRegex(isStrict); - }); +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { - var weekday = config._locale.weekdaysParse(input, token, config._strict); - // if we didn't get a weekday name, mark the date as invalid - if (weekday != null) { - week.d = weekday; - } else { - getParsingFlags(config).invalidWeekday = input; - } - }); - addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { - week[token] = toInt(input); + var symbolMap = { + '1': '١', + '2': '٢', + '3': '٣', + '4': '٤', + '5': '٥', + '6': '٦', + '7': '٧', + '8': '٨', + '9': '٩', + '0': '٠' + }, numberMap = { + '١': '1', + '٢': '2', + '٣': '3', + '٤': '4', + '٥': '5', + '٦': '6', + '٧': '7', + '٨': '8', + '٩': '9', + '٠': '0' + }; + + var arSa = moment.defineLocale('ar-sa', { + months : 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), + monthsShort : 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), + weekdays : 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), + weekdaysShort : 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), + weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd D MMMM YYYY HH:mm' + }, + meridiemParse: /ص|م/, + isPM : function (input) { + return 'م' === input; + }, + meridiem : function (hour, minute, isLower) { + if (hour < 12) { + return 'ص'; + } else { + return 'م'; + } + }, + calendar : { + sameDay: '[اليوم على الساعة] LT', + nextDay: '[غدا على الساعة] LT', + nextWeek: 'dddd [على الساعة] LT', + lastDay: '[أمس على الساعة] LT', + lastWeek: 'dddd [على الساعة] LT', + sameElse: 'L' + }, + relativeTime : { + future : 'في %s', + past : 'منذ %s', + s : 'ثوان', + ss : '%d ثانية', + m : 'دقيقة', + mm : '%d دقائق', + h : 'ساعة', + hh : '%d ساعات', + d : 'يوم', + dd : '%d أيام', + M : 'شهر', + MM : '%d أشهر', + y : 'سنة', + yy : '%d سنوات' + }, + preparse: function (string) { + return string.replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) { + return numberMap[match]; + }).replace(/،/g, ','); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }).replace(/,/g, '،'); + }, + week : { + dow : 0, // Sunday is the first day of the week. + doy : 6 // The week that contains Jan 6th is the first week of the year. + } }); - // HELPERS + return arSa; - function parseWeekday(input, locale) { - if (typeof input !== 'string') { - return input; - } +}))); - if (!isNaN(input)) { - return parseInt(input, 10); - } - input = locale.weekdaysParse(input); - if (typeof input === 'number') { - return input; - } +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { - return null; - } +//! moment.js locale configuration - function parseIsoWeekday(input, locale) { - if (typeof input === 'string') { - return locale.weekdaysParse(input) % 7 || 7; - } - return isNaN(input) ? null : input; - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - // LOCALES - function shiftWeekdays (ws, n) { - return ws.slice(n, 7).concat(ws.slice(0, n)); - } - var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); - function localeWeekdays (m, format) { - var weekdays = isArray(this._weekdays) ? this._weekdays : - this._weekdays[(m && m !== true && this._weekdays.isFormat.test(format)) ? 'format' : 'standalone']; - return (m === true) ? shiftWeekdays(weekdays, this._week.dow) - : (m) ? weekdays[m.day()] : weekdays; - } - - var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); - function localeWeekdaysShort (m) { - return (m === true) ? shiftWeekdays(this._weekdaysShort, this._week.dow) - : (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort; - } + var arTn = moment.defineLocale('ar-tn', { + months: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), + monthsShort: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), + weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), + weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), + weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), + weekdaysParseExact : true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm' + }, + calendar: { + sameDay: '[اليوم على الساعة] LT', + nextDay: '[غدا على الساعة] LT', + nextWeek: 'dddd [على الساعة] LT', + lastDay: '[أمس على الساعة] LT', + lastWeek: 'dddd [على الساعة] LT', + sameElse: 'L' + }, + relativeTime: { + future: 'في %s', + past: 'منذ %s', + s: 'ثوان', + ss : '%d ثانية', + m: 'دقيقة', + mm: '%d دقائق', + h: 'ساعة', + hh: '%d ساعات', + d: 'يوم', + dd: '%d أيام', + M: 'شهر', + MM: '%d أشهر', + y: 'سنة', + yy: '%d سنوات' + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4 // The week that contains Jan 4th is the first week of the year. + } + }); - var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); - function localeWeekdaysMin (m) { - return (m === true) ? shiftWeekdays(this._weekdaysMin, this._week.dow) - : (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin; - } + return arTn; - function handleStrictParse$1(weekdayName, format, strict) { - var i, ii, mom, llc = weekdayName.toLocaleLowerCase(); - if (!this._weekdaysParse) { - this._weekdaysParse = []; - this._shortWeekdaysParse = []; - this._minWeekdaysParse = []; +}))); - for (i = 0; i < 7; ++i) { - mom = createUTC([2000, 1]).day(i); - this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase(); - this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase(); - this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase(); - } - } - if (strict) { - if (format === 'dddd') { - ii = indexOf.call(this._weekdaysParse, llc); - return ii !== -1 ? ii : null; - } else if (format === 'ddd') { - ii = indexOf.call(this._shortWeekdaysParse, llc); - return ii !== -1 ? ii : null; - } else { - ii = indexOf.call(this._minWeekdaysParse, llc); - return ii !== -1 ? ii : null; - } - } else { - if (format === 'dddd') { - ii = indexOf.call(this._weekdaysParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._shortWeekdaysParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._minWeekdaysParse, llc); - return ii !== -1 ? ii : null; - } else if (format === 'ddd') { - ii = indexOf.call(this._shortWeekdaysParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._weekdaysParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._minWeekdaysParse, llc); - return ii !== -1 ? ii : null; - } else { - ii = indexOf.call(this._minWeekdaysParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._weekdaysParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._shortWeekdaysParse, llc); - return ii !== -1 ? ii : null; - } - } - } +/***/ }), +/* 21 */ +/***/ (function(module, exports, __webpack_require__) { - function localeWeekdaysParse (weekdayName, format, strict) { - var i, mom, regex; +//! moment.js locale configuration - if (this._weekdaysParseExact) { - return handleStrictParse$1.call(this, weekdayName, format, strict); - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - if (!this._weekdaysParse) { - this._weekdaysParse = []; - this._minWeekdaysParse = []; - this._shortWeekdaysParse = []; - this._fullWeekdaysParse = []; - } - for (i = 0; i < 7; i++) { - // make the regex if we don't have it already + var suffixes = { + 1: '-inci', + 5: '-inci', + 8: '-inci', + 70: '-inci', + 80: '-inci', + 2: '-nci', + 7: '-nci', + 20: '-nci', + 50: '-nci', + 3: '-üncü', + 4: '-üncü', + 100: '-üncü', + 6: '-ncı', + 9: '-uncu', + 10: '-uncu', + 30: '-uncu', + 60: '-ıncı', + 90: '-ıncı' + }; - mom = createUTC([2000, 1]).day(i); - if (strict && !this._fullWeekdaysParse[i]) { - this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', 'i'); - this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', 'i'); - this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', 'i'); - } - if (!this._weekdaysParse[i]) { - regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); - this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); + var az = moment.defineLocale('az', { + months : 'yanvar_fevral_mart_aprel_may_iyun_iyul_avqust_sentyabr_oktyabr_noyabr_dekabr'.split('_'), + monthsShort : 'yan_fev_mar_apr_may_iyn_iyl_avq_sen_okt_noy_dek'.split('_'), + weekdays : 'Bazar_Bazar ertəsi_Çərşənbə axşamı_Çərşənbə_Cümə axşamı_Cümə_Şənbə'.split('_'), + weekdaysShort : 'Baz_BzE_ÇAx_Çər_CAx_Cüm_Şən'.split('_'), + weekdaysMin : 'Bz_BE_ÇA_Çə_CA_Cü_Şə'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd, D MMMM YYYY HH:mm' + }, + calendar : { + sameDay : '[bugün saat] LT', + nextDay : '[sabah saat] LT', + nextWeek : '[gələn həftə] dddd [saat] LT', + lastDay : '[dünən] LT', + lastWeek : '[keçən həftə] dddd [saat] LT', + sameElse : 'L' + }, + relativeTime : { + future : '%s sonra', + past : '%s əvvəl', + s : 'birneçə saniyə', + ss : '%d saniyə', + m : 'bir dəqiqə', + mm : '%d dəqiqə', + h : 'bir saat', + hh : '%d saat', + d : 'bir gün', + dd : '%d gün', + M : 'bir ay', + MM : '%d ay', + y : 'bir il', + yy : '%d il' + }, + meridiemParse: /gecə|səhər|gündüz|axşam/, + isPM : function (input) { + return /^(gündüz|axşam)$/.test(input); + }, + meridiem : function (hour, minute, isLower) { + if (hour < 4) { + return 'gecə'; + } else if (hour < 12) { + return 'səhər'; + } else if (hour < 17) { + return 'gündüz'; + } else { + return 'axşam'; } - // test the regex - if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) { - return i; - } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) { - return i; - } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) { - return i; - } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { - return i; + }, + dayOfMonthOrdinalParse: /\d{1,2}-(ıncı|inci|nci|üncü|ncı|uncu)/, + ordinal : function (number) { + if (number === 0) { // special case for zero + return number + '-ıncı'; } + var a = number % 10, + b = number % 100 - a, + c = number >= 100 ? 100 : null; + return number + (suffixes[a] || suffixes[b] || suffixes[c]); + }, + week : { + dow : 1, // Monday is the first day of the week. + doy : 7 // The week that contains Jan 7th is the first week of the year. } - } + }); - // MOMENTS + return az; - function getSetDayOfWeek (input) { - if (!this.isValid()) { - return input != null ? this : NaN; - } - var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); - if (input != null) { - input = parseWeekday(input, this.localeData()); - return this.add(input - day, 'd'); - } else { - return day; - } - } +}))); - function getSetLocaleDayOfWeek (input) { - if (!this.isValid()) { - return input != null ? this : NaN; - } - var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; - return input == null ? weekday : this.add(input - weekday, 'd'); - } - function getSetISODayOfWeek (input) { - if (!this.isValid()) { - return input != null ? this : NaN; - } +/***/ }), +/* 22 */ +/***/ (function(module, exports, __webpack_require__) { - // behaves the same as moment#day except - // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) - // as a setter, sunday should belong to the previous week. +//! moment.js locale configuration - if (input != null) { - var weekday = parseIsoWeekday(input, this.localeData()); - return this.day(this.day() % 7 ? weekday : weekday - 7); - } else { - return this.day() || 7; - } - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - var defaultWeekdaysRegex = matchWord; - function weekdaysRegex (isStrict) { - if (this._weekdaysParseExact) { - if (!hasOwnProp(this, '_weekdaysRegex')) { - computeWeekdaysParse.call(this); - } - if (isStrict) { - return this._weekdaysStrictRegex; - } else { - return this._weekdaysRegex; - } - } else { - if (!hasOwnProp(this, '_weekdaysRegex')) { - this._weekdaysRegex = defaultWeekdaysRegex; - } - return this._weekdaysStrictRegex && isStrict ? - this._weekdaysStrictRegex : this._weekdaysRegex; - } - } - var defaultWeekdaysShortRegex = matchWord; - function weekdaysShortRegex (isStrict) { - if (this._weekdaysParseExact) { - if (!hasOwnProp(this, '_weekdaysRegex')) { - computeWeekdaysParse.call(this); - } - if (isStrict) { - return this._weekdaysShortStrictRegex; - } else { - return this._weekdaysShortRegex; - } - } else { - if (!hasOwnProp(this, '_weekdaysShortRegex')) { - this._weekdaysShortRegex = defaultWeekdaysShortRegex; - } - return this._weekdaysShortStrictRegex && isStrict ? - this._weekdaysShortStrictRegex : this._weekdaysShortRegex; + function plural(word, num) { + var forms = word.split('_'); + return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); + } + function relativeTimeWithPlural(number, withoutSuffix, key) { + var format = { + 'ss': withoutSuffix ? 'секунда_секунды_секунд' : 'секунду_секунды_секунд', + 'mm': withoutSuffix ? 'хвіліна_хвіліны_хвілін' : 'хвіліну_хвіліны_хвілін', + 'hh': withoutSuffix ? 'гадзіна_гадзіны_гадзін' : 'гадзіну_гадзіны_гадзін', + 'dd': 'дзень_дні_дзён', + 'MM': 'месяц_месяцы_месяцаў', + 'yy': 'год_гады_гадоў' + }; + if (key === 'm') { + return withoutSuffix ? 'хвіліна' : 'хвіліну'; + } + else if (key === 'h') { + return withoutSuffix ? 'гадзіна' : 'гадзіну'; + } + else { + return number + ' ' + plural(format[key], +number); } } - var defaultWeekdaysMinRegex = matchWord; - function weekdaysMinRegex (isStrict) { - if (this._weekdaysParseExact) { - if (!hasOwnProp(this, '_weekdaysRegex')) { - computeWeekdaysParse.call(this); - } - if (isStrict) { - return this._weekdaysMinStrictRegex; + var be = moment.defineLocale('be', { + months : { + format: 'студзеня_лютага_сакавіка_красавіка_траўня_чэрвеня_ліпеня_жніўня_верасня_кастрычніка_лістапада_снежня'.split('_'), + standalone: 'студзень_люты_сакавік_красавік_травень_чэрвень_ліпень_жнівень_верасень_кастрычнік_лістапад_снежань'.split('_') + }, + monthsShort : 'студ_лют_сак_крас_трав_чэрв_ліп_жнів_вер_каст_ліст_снеж'.split('_'), + weekdays : { + format: 'нядзелю_панядзелак_аўторак_сераду_чацвер_пятніцу_суботу'.split('_'), + standalone: 'нядзеля_панядзелак_аўторак_серада_чацвер_пятніца_субота'.split('_'), + isFormat: /\[ ?[Ууў] ?(?:мінулую|наступную)? ?\] ?dddd/ + }, + weekdaysShort : 'нд_пн_ат_ср_чц_пт_сб'.split('_'), + weekdaysMin : 'нд_пн_ат_ср_чц_пт_сб'.split('_'), + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D MMMM YYYY г.', + LLL : 'D MMMM YYYY г., HH:mm', + LLLL : 'dddd, D MMMM YYYY г., HH:mm' + }, + calendar : { + sameDay: '[Сёння ў] LT', + nextDay: '[Заўтра ў] LT', + lastDay: '[Учора ў] LT', + nextWeek: function () { + return '[У] dddd [ў] LT'; + }, + lastWeek: function () { + switch (this.day()) { + case 0: + case 3: + case 5: + case 6: + return '[У мінулую] dddd [ў] LT'; + case 1: + case 2: + case 4: + return '[У мінулы] dddd [ў] LT'; + } + }, + sameElse: 'L' + }, + relativeTime : { + future : 'праз %s', + past : '%s таму', + s : 'некалькі секунд', + m : relativeTimeWithPlural, + mm : relativeTimeWithPlural, + h : relativeTimeWithPlural, + hh : relativeTimeWithPlural, + d : 'дзень', + dd : relativeTimeWithPlural, + M : 'месяц', + MM : relativeTimeWithPlural, + y : 'год', + yy : relativeTimeWithPlural + }, + meridiemParse: /ночы|раніцы|дня|вечара/, + isPM : function (input) { + return /^(дня|вечара)$/.test(input); + }, + meridiem : function (hour, minute, isLower) { + if (hour < 4) { + return 'ночы'; + } else if (hour < 12) { + return 'раніцы'; + } else if (hour < 17) { + return 'дня'; } else { - return this._weekdaysMinRegex; + return 'вечара'; } - } else { - if (!hasOwnProp(this, '_weekdaysMinRegex')) { - this._weekdaysMinRegex = defaultWeekdaysMinRegex; + }, + dayOfMonthOrdinalParse: /\d{1,2}-(і|ы|га)/, + ordinal: function (number, period) { + switch (period) { + case 'M': + case 'd': + case 'DDD': + case 'w': + case 'W': + return (number % 10 === 2 || number % 10 === 3) && (number % 100 !== 12 && number % 100 !== 13) ? number + '-і' : number + '-ы'; + case 'D': + return number + '-га'; + default: + return number; } - return this._weekdaysMinStrictRegex && isStrict ? - this._weekdaysMinStrictRegex : this._weekdaysMinRegex; - } - } - - - function computeWeekdaysParse () { - function cmpLenRev(a, b) { - return b.length - a.length; - } - - var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], - i, mom, minp, shortp, longp; - for (i = 0; i < 7; i++) { - // make the regex if we don't have it already - mom = createUTC([2000, 1]).day(i); - minp = this.weekdaysMin(mom, ''); - shortp = this.weekdaysShort(mom, ''); - longp = this.weekdays(mom, ''); - minPieces.push(minp); - shortPieces.push(shortp); - longPieces.push(longp); - mixedPieces.push(minp); - mixedPieces.push(shortp); - mixedPieces.push(longp); - } - // Sorting makes sure if one weekday (or abbr) is a prefix of another it - // will match the longer piece. - minPieces.sort(cmpLenRev); - shortPieces.sort(cmpLenRev); - longPieces.sort(cmpLenRev); - mixedPieces.sort(cmpLenRev); - for (i = 0; i < 7; i++) { - shortPieces[i] = regexEscape(shortPieces[i]); - longPieces[i] = regexEscape(longPieces[i]); - mixedPieces[i] = regexEscape(mixedPieces[i]); + }, + week : { + dow : 1, // Monday is the first day of the week. + doy : 7 // The week that contains Jan 7th is the first week of the year. } + }); - this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); - this._weekdaysShortRegex = this._weekdaysRegex; - this._weekdaysMinRegex = this._weekdaysRegex; + return be; - this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); - this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); - this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i'); - } +}))); - // FORMATTING - function hFormat() { - return this.hours() % 12 || 12; - } +/***/ }), +/* 23 */ +/***/ (function(module, exports, __webpack_require__) { - function kFormat() { - return this.hours() || 24; - } +//! moment.js locale configuration - addFormatToken('H', ['HH', 2], 0, 'hour'); - addFormatToken('h', ['hh', 2], 0, hFormat); - addFormatToken('k', ['kk', 2], 0, kFormat); +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - addFormatToken('hmm', 0, 0, function () { - return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2); - }); - addFormatToken('hmmss', 0, 0, function () { - return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + - zeroFill(this.seconds(), 2); - }); - - addFormatToken('Hmm', 0, 0, function () { - return '' + this.hours() + zeroFill(this.minutes(), 2); - }); - - addFormatToken('Hmmss', 0, 0, function () { - return '' + this.hours() + zeroFill(this.minutes(), 2) + - zeroFill(this.seconds(), 2); + var bg = moment.defineLocale('bg', { + months : 'януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември'.split('_'), + monthsShort : 'янр_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек'.split('_'), + weekdays : 'неделя_понеделник_вторник_сряда_четвъртък_петък_събота'.split('_'), + weekdaysShort : 'нед_пон_вто_сря_чет_пет_съб'.split('_'), + weekdaysMin : 'нд_пн_вт_ср_чт_пт_сб'.split('_'), + longDateFormat : { + LT : 'H:mm', + LTS : 'H:mm:ss', + L : 'D.MM.YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY H:mm', + LLLL : 'dddd, D MMMM YYYY H:mm' + }, + calendar : { + sameDay : '[Днес в] LT', + nextDay : '[Утре в] LT', + nextWeek : 'dddd [в] LT', + lastDay : '[Вчера в] LT', + lastWeek : function () { + switch (this.day()) { + case 0: + case 3: + case 6: + return '[В изминалата] dddd [в] LT'; + case 1: + case 2: + case 4: + case 5: + return '[В изминалия] dddd [в] LT'; + } + }, + sameElse : 'L' + }, + relativeTime : { + future : 'след %s', + past : 'преди %s', + s : 'няколко секунди', + ss : '%d секунди', + m : 'минута', + mm : '%d минути', + h : 'час', + hh : '%d часа', + d : 'ден', + dd : '%d дни', + M : 'месец', + MM : '%d месеца', + y : 'година', + yy : '%d години' + }, + dayOfMonthOrdinalParse: /\d{1,2}-(ев|ен|ти|ви|ри|ми)/, + ordinal : function (number) { + var lastDigit = number % 10, + last2Digits = number % 100; + if (number === 0) { + return number + '-ев'; + } else if (last2Digits === 0) { + return number + '-ен'; + } else if (last2Digits > 10 && last2Digits < 20) { + return number + '-ти'; + } else if (lastDigit === 1) { + return number + '-ви'; + } else if (lastDigit === 2) { + return number + '-ри'; + } else if (lastDigit === 7 || lastDigit === 8) { + return number + '-ми'; + } else { + return number + '-ти'; + } + }, + week : { + dow : 1, // Monday is the first day of the week. + doy : 7 // The week that contains Jan 7th is the first week of the year. + } }); - function meridiem (token, lowercase) { - addFormatToken(token, 0, 0, function () { - return this.localeData().meridiem(this.hours(), this.minutes(), lowercase); - }); - } - - meridiem('a', true); - meridiem('A', false); - - // ALIASES - - addUnitAlias('hour', 'h'); - - // PRIORITY - addUnitPriority('hour', 13); - - // PARSING + return bg; - function matchMeridiem (isStrict, locale) { - return locale._meridiemParse; - } +}))); - addRegexToken('a', matchMeridiem); - addRegexToken('A', matchMeridiem); - addRegexToken('H', match1to2); - addRegexToken('h', match1to2); - addRegexToken('k', match1to2); - addRegexToken('HH', match1to2, match2); - addRegexToken('hh', match1to2, match2); - addRegexToken('kk', match1to2, match2); - addRegexToken('hmm', match3to4); - addRegexToken('hmmss', match5to6); - addRegexToken('Hmm', match3to4); - addRegexToken('Hmmss', match5to6); +/***/ }), +/* 24 */ +/***/ (function(module, exports, __webpack_require__) { - addParseToken(['H', 'HH'], HOUR); - addParseToken(['k', 'kk'], function (input, array, config) { - var kInput = toInt(input); - array[HOUR] = kInput === 24 ? 0 : kInput; - }); - addParseToken(['a', 'A'], function (input, array, config) { - config._isPm = config._locale.isPM(input); - config._meridiem = input; - }); - addParseToken(['h', 'hh'], function (input, array, config) { - array[HOUR] = toInt(input); - getParsingFlags(config).bigHour = true; - }); - addParseToken('hmm', function (input, array, config) { - var pos = input.length - 2; - array[HOUR] = toInt(input.substr(0, pos)); - array[MINUTE] = toInt(input.substr(pos)); - getParsingFlags(config).bigHour = true; - }); - addParseToken('hmmss', function (input, array, config) { - var pos1 = input.length - 4; - var pos2 = input.length - 2; - array[HOUR] = toInt(input.substr(0, pos1)); - array[MINUTE] = toInt(input.substr(pos1, 2)); - array[SECOND] = toInt(input.substr(pos2)); - getParsingFlags(config).bigHour = true; - }); - addParseToken('Hmm', function (input, array, config) { - var pos = input.length - 2; - array[HOUR] = toInt(input.substr(0, pos)); - array[MINUTE] = toInt(input.substr(pos)); - }); - addParseToken('Hmmss', function (input, array, config) { - var pos1 = input.length - 4; - var pos2 = input.length - 2; - array[HOUR] = toInt(input.substr(0, pos1)); - array[MINUTE] = toInt(input.substr(pos1, 2)); - array[SECOND] = toInt(input.substr(pos2)); - }); +//! moment.js locale configuration - // LOCALES +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - function localeIsPM (input) { - // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays - // Using charAt should be more compatible. - return ((input + '').toLowerCase().charAt(0) === 'p'); - } - var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i; - function localeMeridiem (hours, minutes, isLower) { - if (hours > 11) { - return isLower ? 'pm' : 'PM'; - } else { - return isLower ? 'am' : 'AM'; + var bm = moment.defineLocale('bm', { + months : 'Zanwuyekalo_Fewuruyekalo_Marisikalo_Awirilikalo_Mɛkalo_Zuwɛnkalo_Zuluyekalo_Utikalo_Sɛtanburukalo_ɔkutɔburukalo_Nowanburukalo_Desanburukalo'.split('_'), + monthsShort : 'Zan_Few_Mar_Awi_Mɛ_Zuw_Zul_Uti_Sɛt_ɔku_Now_Des'.split('_'), + weekdays : 'Kari_Ntɛnɛn_Tarata_Araba_Alamisa_Juma_Sibiri'.split('_'), + weekdaysShort : 'Kar_Ntɛ_Tar_Ara_Ala_Jum_Sib'.split('_'), + weekdaysMin : 'Ka_Nt_Ta_Ar_Al_Ju_Si'.split('_'), + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'MMMM [tile] D [san] YYYY', + LLL : 'MMMM [tile] D [san] YYYY [lɛrɛ] HH:mm', + LLLL : 'dddd MMMM [tile] D [san] YYYY [lɛrɛ] HH:mm' + }, + calendar : { + sameDay : '[Bi lɛrɛ] LT', + nextDay : '[Sini lɛrɛ] LT', + nextWeek : 'dddd [don lɛrɛ] LT', + lastDay : '[Kunu lɛrɛ] LT', + lastWeek : 'dddd [tɛmɛnen lɛrɛ] LT', + sameElse : 'L' + }, + relativeTime : { + future : '%s kɔnɔ', + past : 'a bɛ %s bɔ', + s : 'sanga dama dama', + ss : 'sekondi %d', + m : 'miniti kelen', + mm : 'miniti %d', + h : 'lɛrɛ kelen', + hh : 'lɛrɛ %d', + d : 'tile kelen', + dd : 'tile %d', + M : 'kalo kelen', + MM : 'kalo %d', + y : 'san kelen', + yy : 'san %d' + }, + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } - } + }); + return bm; - // MOMENTS +}))); - // Setting the hour should keep the time, because the user explicitly - // specified which hour they want. So trying to maintain the same hour (in - // a new timezone) makes sense. Adding/subtracting hours does not follow - // this rule. - var getSetHour = makeGetSet('Hours', true); - var baseConfig = { - calendar: defaultCalendar, - longDateFormat: defaultLongDateFormat, - invalidDate: defaultInvalidDate, - ordinal: defaultOrdinal, - dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, - relativeTime: defaultRelativeTime, +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { - months: defaultLocaleMonths, - monthsShort: defaultLocaleMonthsShort, +//! moment.js locale configuration - week: defaultLocaleWeek, +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - weekdays: defaultLocaleWeekdays, - weekdaysMin: defaultLocaleWeekdaysMin, - weekdaysShort: defaultLocaleWeekdaysShort, - meridiemParse: defaultLocaleMeridiemParse + var symbolMap = { + '1': '১', + '2': '২', + '3': '৩', + '4': '৪', + '5': '৫', + '6': '৬', + '7': '৭', + '8': '৮', + '9': '৯', + '0': '০' + }, + numberMap = { + '১': '1', + '২': '2', + '৩': '3', + '৪': '4', + '৫': '5', + '৬': '6', + '৭': '7', + '৮': '8', + '৯': '9', + '০': '0' }; - // internal storage for locale config files - var locales = {}; - var localeFamilies = {}; - var globalLocale; - - function normalizeLocale(key) { - return key ? key.toLowerCase().replace('_', '-') : key; - } - - // pick the locale from the array - // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each - // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root - function chooseLocale(names) { - var i = 0, j, next, locale, split; - - while (i < names.length) { - split = normalizeLocale(names[i]).split('-'); - j = split.length; - next = normalizeLocale(names[i + 1]); - next = next ? next.split('-') : null; - while (j > 0) { - locale = loadLocale(split.slice(0, j).join('-')); - if (locale) { - return locale; - } - if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { - //the next array item is better than a shallower substring of this one - break; - } - j--; - } - i++; - } - return globalLocale; - } - - function loadLocale(name) { - var oldLocale = null; - // TODO: Find a better way to register and load all the locales in Node - if (!locales[name] && (typeof module !== 'undefined') && - module && module.exports) { - try { - oldLocale = globalLocale._abbr; - var aliasedRequire = require; - __webpack_require__(41)("./" + name); - getSetGlobalLocale(oldLocale); - } catch (e) {} - } - return locales[name]; - } - - // This function will load locale and then set the global locale. If - // no arguments are passed in, it will simply return the current global - // locale key. - function getSetGlobalLocale (key, values) { - var data; - if (key) { - if (isUndefined(values)) { - data = getLocale(key); - } - else { - data = defineLocale(key, values); + var bn = moment.defineLocale('bn', { + months : 'জানুয়ারী_ফেব্রুয়ারি_মার্চ_এপ্রিল_মে_জুন_জুলাই_আগস্ট_সেপ্টেম্বর_অক্টোবর_নভেম্বর_ডিসেম্বর'.split('_'), + monthsShort : 'জানু_ফেব_মার্চ_এপ্র_মে_জুন_জুল_আগ_সেপ্ট_অক্টো_নভে_ডিসে'.split('_'), + weekdays : 'রবিবার_সোমবার_মঙ্গলবার_বুধবার_বৃহস্পতিবার_শুক্রবার_শনিবার'.split('_'), + weekdaysShort : 'রবি_সোম_মঙ্গল_বুধ_বৃহস্পতি_শুক্র_শনি'.split('_'), + weekdaysMin : 'রবি_সোম_মঙ্গ_বুধ_বৃহঃ_শুক্র_শনি'.split('_'), + longDateFormat : { + LT : 'A h:mm সময়', + LTS : 'A h:mm:ss সময়', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY, A h:mm সময়', + LLLL : 'dddd, D MMMM YYYY, A h:mm সময়' + }, + calendar : { + sameDay : '[আজ] LT', + nextDay : '[আগামীকাল] LT', + nextWeek : 'dddd, LT', + lastDay : '[গতকাল] LT', + lastWeek : '[গত] dddd, LT', + sameElse : 'L' + }, + relativeTime : { + future : '%s পরে', + past : '%s আগে', + s : 'কয়েক সেকেন্ড', + ss : '%d সেকেন্ড', + m : 'এক মিনিট', + mm : '%d মিনিট', + h : 'এক ঘন্টা', + hh : '%d ঘন্টা', + d : 'এক দিন', + dd : '%d দিন', + M : 'এক মাস', + MM : '%d মাস', + y : 'এক বছর', + yy : '%d বছর' + }, + preparse: function (string) { + return string.replace(/[১২৩৪৫৬৭৮৯০]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + meridiemParse: /রাত|সকাল|দুপুর|বিকাল|রাত/, + meridiemHour : function (hour, meridiem) { + if (hour === 12) { + hour = 0; } - - if (data) { - // moment.duration._locale = moment._locale = data; - globalLocale = data; + if ((meridiem === 'রাত' && hour >= 4) || + (meridiem === 'দুপুর' && hour < 5) || + meridiem === 'বিকাল') { + return hour + 12; + } else { + return hour; } - else { - if ((typeof console !== 'undefined') && console.warn) { - //warn user if arguments are passed but the locale could not be set - console.warn('Locale ' + key + ' not found. Did you forget to load it?'); - } + }, + meridiem : function (hour, minute, isLower) { + if (hour < 4) { + return 'রাত'; + } else if (hour < 10) { + return 'সকাল'; + } else if (hour < 17) { + return 'দুপুর'; + } else if (hour < 20) { + return 'বিকাল'; + } else { + return 'রাত'; } + }, + week : { + dow : 0, // Sunday is the first day of the week. + doy : 6 // The week that contains Jan 6th is the first week of the year. } + }); - return globalLocale._abbr; - } - - function defineLocale (name, config) { - if (config !== null) { - var locale, parentConfig = baseConfig; - config.abbr = name; - if (locales[name] != null) { - deprecateSimple('defineLocaleOverride', - 'use moment.updateLocale(localeName, config) to change ' + - 'an existing locale. moment.defineLocale(localeName, ' + - 'config) should only be used for creating a new locale ' + - 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'); - parentConfig = locales[name]._config; - } else if (config.parentLocale != null) { - if (locales[config.parentLocale] != null) { - parentConfig = locales[config.parentLocale]._config; - } else { - locale = loadLocale(config.parentLocale); - if (locale != null) { - parentConfig = locale._config; - } else { - if (!localeFamilies[config.parentLocale]) { - localeFamilies[config.parentLocale] = []; - } - localeFamilies[config.parentLocale].push({ - name: name, - config: config - }); - return null; - } - } - } - locales[name] = new Locale(mergeConfigs(parentConfig, config)); - - if (localeFamilies[name]) { - localeFamilies[name].forEach(function (x) { - defineLocale(x.name, x.config); - }); - } - - // backwards compat for now: also set the locale - // make sure we set the locale AFTER all child locales have been - // created, so we won't end up with the child locale set. - getSetGlobalLocale(name); + return bn; +}))); - return locales[name]; - } else { - // useful for testing - delete locales[name]; - return null; - } - } - function updateLocale(name, config) { - if (config != null) { - var locale, tmpLocale, parentConfig = baseConfig; - // MERGE - tmpLocale = loadLocale(name); - if (tmpLocale != null) { - parentConfig = tmpLocale._config; - } - config = mergeConfigs(parentConfig, config); - locale = new Locale(config); - locale.parentLocale = locales[name]; - locales[name] = locale; +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { - // backwards compat for now: also set the locale - getSetGlobalLocale(name); - } else { - // pass null for config to unupdate, useful for tests - if (locales[name] != null) { - if (locales[name].parentLocale != null) { - locales[name] = locales[name].parentLocale; - } else if (locales[name] != null) { - delete locales[name]; - } - } - } - return locales[name]; - } +//! moment.js locale configuration - // returns locale data - function getLocale (key) { - var locale; +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - if (key && key._locale && key._locale._abbr) { - key = key._locale._abbr; - } - if (!key) { - return globalLocale; - } + var symbolMap = { + '1': '༡', + '2': '༢', + '3': '༣', + '4': '༤', + '5': '༥', + '6': '༦', + '7': '༧', + '8': '༨', + '9': '༩', + '0': '༠' + }, + numberMap = { + '༡': '1', + '༢': '2', + '༣': '3', + '༤': '4', + '༥': '5', + '༦': '6', + '༧': '7', + '༨': '8', + '༩': '9', + '༠': '0' + }; - if (!isArray(key)) { - //short-circuit everything else - locale = loadLocale(key); - if (locale) { - return locale; + var bo = moment.defineLocale('bo', { + months : 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split('_'), + monthsShort : 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split('_'), + weekdays : 'གཟའ་ཉི་མ་_གཟའ་ཟླ་བ་_གཟའ་མིག་དམར་_གཟའ་ལྷག་པ་_གཟའ་ཕུར་བུ_གཟའ་པ་སངས་_གཟའ་སྤེན་པ་'.split('_'), + weekdaysShort : 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split('_'), + weekdaysMin : 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split('_'), + longDateFormat : { + LT : 'A h:mm', + LTS : 'A h:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY, A h:mm', + LLLL : 'dddd, D MMMM YYYY, A h:mm' + }, + calendar : { + sameDay : '[དི་རིང] LT', + nextDay : '[སང་ཉིན] LT', + nextWeek : '[བདུན་ཕྲག་རྗེས་མ], LT', + lastDay : '[ཁ་སང] LT', + lastWeek : '[བདུན་ཕྲག་མཐའ་མ] dddd, LT', + sameElse : 'L' + }, + relativeTime : { + future : '%s ལ་', + past : '%s སྔན་ལ', + s : 'ལམ་སང', + ss : '%d སྐར་ཆ།', + m : 'སྐར་མ་གཅིག', + mm : '%d སྐར་མ', + h : 'ཆུ་ཚོད་གཅིག', + hh : '%d ཆུ་ཚོད', + d : 'ཉིན་གཅིག', + dd : '%d ཉིན་', + M : 'ཟླ་བ་གཅིག', + MM : '%d ཟླ་བ', + y : 'ལོ་གཅིག', + yy : '%d ལོ' + }, + preparse: function (string) { + return string.replace(/[༡༢༣༤༥༦༧༨༩༠]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + meridiemParse: /མཚན་མོ|ཞོགས་ཀས|ཉིན་གུང|དགོང་དག|མཚན་མོ/, + meridiemHour : function (hour, meridiem) { + if (hour === 12) { + hour = 0; } - key = [key]; + if ((meridiem === 'མཚན་མོ' && hour >= 4) || + (meridiem === 'ཉིན་གུང' && hour < 5) || + meridiem === 'དགོང་དག') { + return hour + 12; + } else { + return hour; + } + }, + meridiem : function (hour, minute, isLower) { + if (hour < 4) { + return 'མཚན་མོ'; + } else if (hour < 10) { + return 'ཞོགས་ཀས'; + } else if (hour < 17) { + return 'ཉིན་གུང'; + } else if (hour < 20) { + return 'དགོང་དག'; + } else { + return 'མཚན་མོ'; + } + }, + week : { + dow : 0, // Sunday is the first day of the week. + doy : 6 // The week that contains Jan 6th is the first week of the year. } + }); - return chooseLocale(key); - } + return bo; - function listLocales() { - return keys(locales); - } +}))); - function checkOverflow (m) { - var overflow; - var a = m._a; - if (a && getParsingFlags(m).overflow === -2) { - overflow = - a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : - a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : - a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR : - a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : - a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : - a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : - -1; +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { - if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { - overflow = DATE; - } - if (getParsingFlags(m)._overflowWeeks && overflow === -1) { - overflow = WEEK; - } - if (getParsingFlags(m)._overflowWeekday && overflow === -1) { - overflow = WEEKDAY; - } +//! moment.js locale configuration - getParsingFlags(m).overflow = overflow; - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - return m; - } - // Pick the first defined of two or three arguments. - function defaults(a, b, c) { - if (a != null) { - return a; + function relativeTimeWithMutation(number, withoutSuffix, key) { + var format = { + 'mm': 'munutenn', + 'MM': 'miz', + 'dd': 'devezh' + }; + return number + ' ' + mutation(format[key], number); + } + function specialMutationForYears(number) { + switch (lastNumber(number)) { + case 1: + case 3: + case 4: + case 5: + case 9: + return number + ' bloaz'; + default: + return number + ' vloaz'; } - if (b != null) { - return b; + } + function lastNumber(number) { + if (number > 9) { + return lastNumber(number % 10); } - return c; + return number; } - - function currentDateArray(config) { - // hooks is actually the exported moment object - var nowValue = new Date(hooks.now()); - if (config._useUTC) { - return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()]; + function mutation(text, number) { + if (number === 2) { + return softMutation(text); } - return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; + return text; } - - // convert an array to a date. - // the array should mirror the parameters below - // note: all values past the year are optional and will default to the lowest possible value. - // [year, month, day , hour, minute, second, millisecond] - function configFromArray (config) { - var i, date, input = [], currentDate, expectedWeekday, yearToUse; - - if (config._d) { - return; + function softMutation(text) { + var mutationTable = { + 'm': 'v', + 'b': 'v', + 'd': 'z' + }; + if (mutationTable[text.charAt(0)] === undefined) { + return text; } + return mutationTable[text.charAt(0)] + text.substring(1); + } - currentDate = currentDateArray(config); - - //compute day of the year from weeks and weekdays - if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { - dayOfYearFromWeekInfo(config); + var br = moment.defineLocale('br', { + months : 'Genver_C\'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu'.split('_'), + monthsShort : 'Gen_C\'hwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker'.split('_'), + weekdays : 'Sul_Lun_Meurzh_Merc\'her_Yaou_Gwener_Sadorn'.split('_'), + weekdaysShort : 'Sul_Lun_Meu_Mer_Yao_Gwe_Sad'.split('_'), + weekdaysMin : 'Su_Lu_Me_Mer_Ya_Gw_Sa'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'h[e]mm A', + LTS : 'h[e]mm:ss A', + L : 'DD/MM/YYYY', + LL : 'D [a viz] MMMM YYYY', + LLL : 'D [a viz] MMMM YYYY h[e]mm A', + LLLL : 'dddd, D [a viz] MMMM YYYY h[e]mm A' + }, + calendar : { + sameDay : '[Hiziv da] LT', + nextDay : '[Warc\'hoazh da] LT', + nextWeek : 'dddd [da] LT', + lastDay : '[Dec\'h da] LT', + lastWeek : 'dddd [paset da] LT', + sameElse : 'L' + }, + relativeTime : { + future : 'a-benn %s', + past : '%s \'zo', + s : 'un nebeud segondennoù', + ss : '%d eilenn', + m : 'ur vunutenn', + mm : relativeTimeWithMutation, + h : 'un eur', + hh : '%d eur', + d : 'un devezh', + dd : relativeTimeWithMutation, + M : 'ur miz', + MM : relativeTimeWithMutation, + y : 'ur bloaz', + yy : specialMutationForYears + }, + dayOfMonthOrdinalParse: /\d{1,2}(añ|vet)/, + ordinal : function (number) { + var output = (number === 1) ? 'añ' : 'vet'; + return number + output; + }, + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } + }); - //if the day of the year is set, figure out what it is - if (config._dayOfYear != null) { - yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); - - if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) { - getParsingFlags(config)._overflowDayOfYear = true; - } - - date = createUTCDate(yearToUse, 0, config._dayOfYear); - config._a[MONTH] = date.getUTCMonth(); - config._a[DATE] = date.getUTCDate(); - } + return br; - // Default to current date. - // * if no year, month, day of month are given, default to today - // * if day of month is given, default month and year - // * if month is given, default only year - // * if year is given, don't default anything - for (i = 0; i < 3 && config._a[i] == null; ++i) { - config._a[i] = input[i] = currentDate[i]; - } +}))); - // Zero out whatever was not defaulted, including time - for (; i < 7; i++) { - config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; - } - // Check for 24:00:00.000 - if (config._a[HOUR] === 24 && - config._a[MINUTE] === 0 && - config._a[SECOND] === 0 && - config._a[MILLISECOND] === 0) { - config._nextDay = true; - config._a[HOUR] = 0; - } +/***/ }), +/* 28 */ +/***/ (function(module, exports, __webpack_require__) { - config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input); - expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay(); +//! moment.js locale configuration - // Apply timezone offset from input. The actual utcOffset can be changed - // with parseZone. - if (config._tzm != null) { - config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - if (config._nextDay) { - config._a[HOUR] = 24; - } - // check for mismatching day of week - if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) { - getParsingFlags(config).weekdayMismatch = true; + function translate(number, withoutSuffix, key) { + var result = number + ' '; + switch (key) { + case 'ss': + if (number === 1) { + result += 'sekunda'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'sekunde'; + } else { + result += 'sekundi'; + } + return result; + case 'm': + return withoutSuffix ? 'jedna minuta' : 'jedne minute'; + case 'mm': + if (number === 1) { + result += 'minuta'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'minute'; + } else { + result += 'minuta'; + } + return result; + case 'h': + return withoutSuffix ? 'jedan sat' : 'jednog sata'; + case 'hh': + if (number === 1) { + result += 'sat'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'sata'; + } else { + result += 'sati'; + } + return result; + case 'dd': + if (number === 1) { + result += 'dan'; + } else { + result += 'dana'; + } + return result; + case 'MM': + if (number === 1) { + result += 'mjesec'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'mjeseca'; + } else { + result += 'mjeseci'; + } + return result; + case 'yy': + if (number === 1) { + result += 'godina'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'godine'; + } else { + result += 'godina'; + } + return result; } } - function dayOfYearFromWeekInfo(config) { - var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow; + var bs = moment.defineLocale('bs', { + months : 'januar_februar_mart_april_maj_juni_juli_august_septembar_oktobar_novembar_decembar'.split('_'), + monthsShort : 'jan._feb._mar._apr._maj._jun._jul._aug._sep._okt._nov._dec.'.split('_'), + monthsParseExact: true, + weekdays : 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'), + weekdaysShort : 'ned._pon._uto._sri._čet._pet._sub.'.split('_'), + weekdaysMin : 'ne_po_ut_sr_če_pe_su'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'H:mm', + LTS : 'H:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D. MMMM YYYY', + LLL : 'D. MMMM YYYY H:mm', + LLLL : 'dddd, D. MMMM YYYY H:mm' + }, + calendar : { + sameDay : '[danas u] LT', + nextDay : '[sutra u] LT', + nextWeek : function () { + switch (this.day()) { + case 0: + return '[u] [nedjelju] [u] LT'; + case 3: + return '[u] [srijedu] [u] LT'; + case 6: + return '[u] [subotu] [u] LT'; + case 1: + case 2: + case 4: + case 5: + return '[u] dddd [u] LT'; + } + }, + lastDay : '[jučer u] LT', + lastWeek : function () { + switch (this.day()) { + case 0: + case 3: + return '[prošlu] dddd [u] LT'; + case 6: + return '[prošle] [subote] [u] LT'; + case 1: + case 2: + case 4: + case 5: + return '[prošli] dddd [u] LT'; + } + }, + sameElse : 'L' + }, + relativeTime : { + future : 'za %s', + past : 'prije %s', + s : 'par sekundi', + ss : translate, + m : translate, + mm : translate, + h : translate, + hh : translate, + d : 'dan', + dd : translate, + M : 'mjesec', + MM : translate, + y : 'godinu', + yy : translate + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', + week : { + dow : 1, // Monday is the first day of the week. + doy : 7 // The week that contains Jan 7th is the first week of the year. + } + }); - w = config._w; - if (w.GG != null || w.W != null || w.E != null) { - dow = 1; - doy = 4; + return bs; - // TODO: We need to take the current isoWeekYear, but that depends on - // how we interpret now (local, utc, fixed offset). So create - // a now version of current config (take local/utc/offset flags, and - // create now). - weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year); - week = defaults(w.W, 1); - weekday = defaults(w.E, 1); - if (weekday < 1 || weekday > 7) { - weekdayOverflow = true; - } - } else { - dow = config._locale._week.dow; - doy = config._locale._week.doy; +}))); - var curWeek = weekOfYear(createLocal(), dow, doy); - weekYear = defaults(w.gg, config._a[YEAR], curWeek.year); +/***/ }), +/* 29 */ +/***/ (function(module, exports, __webpack_require__) { - // Default to current week. - week = defaults(w.w, curWeek.week); +//! moment.js locale configuration - if (w.d != null) { - // weekday -- low day numbers are considered next week - weekday = w.d; - if (weekday < 0 || weekday > 6) { - weekdayOverflow = true; - } - } else if (w.e != null) { - // local weekday -- counting starts from beginning of week - weekday = w.e + dow; - if (w.e < 0 || w.e > 6) { - weekdayOverflow = true; - } - } else { - // default to beginning of week - weekday = dow; - } - } - if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { - getParsingFlags(config)._overflowWeeks = true; - } else if (weekdayOverflow != null) { - getParsingFlags(config)._overflowWeekday = true; - } else { - temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); - config._a[YEAR] = temp.year; - config._dayOfYear = temp.dayOfYear; - } - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - // iso 8601 regex - // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) - var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; - var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; - var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/; - - var isoDates = [ - ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], - ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], - ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], - ['GGGG-[W]WW', /\d{4}-W\d\d/, false], - ['YYYY-DDD', /\d{4}-\d{3}/], - ['YYYY-MM', /\d{4}-\d\d/, false], - ['YYYYYYMMDD', /[+-]\d{10}/], - ['YYYYMMDD', /\d{8}/], - // YYYYMM is NOT allowed by the standard - ['GGGG[W]WWE', /\d{4}W\d{3}/], - ['GGGG[W]WW', /\d{4}W\d{2}/, false], - ['YYYYDDD', /\d{7}/] - ]; - - // iso time formats and regexes - var isoTimes = [ - ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], - ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], - ['HH:mm:ss', /\d\d:\d\d:\d\d/], - ['HH:mm', /\d\d:\d\d/], - ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], - ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], - ['HHmmss', /\d\d\d\d\d\d/], - ['HHmm', /\d\d\d\d/], - ['HH', /\d\d/] - ]; + var ca = moment.defineLocale('ca', { + months : { + standalone: 'gener_febrer_març_abril_maig_juny_juliol_agost_setembre_octubre_novembre_desembre'.split('_'), + format: 'de gener_de febrer_de març_d\'abril_de maig_de juny_de juliol_d\'agost_de setembre_d\'octubre_de novembre_de desembre'.split('_'), + isFormat: /D[oD]?(\s)+MMMM/ + }, + monthsShort : 'gen._febr._març_abr._maig_juny_jul._ag._set._oct._nov._des.'.split('_'), + monthsParseExact : true, + weekdays : 'diumenge_dilluns_dimarts_dimecres_dijous_divendres_dissabte'.split('_'), + weekdaysShort : 'dg._dl._dt._dc._dj._dv._ds.'.split('_'), + weekdaysMin : 'dg_dl_dt_dc_dj_dv_ds'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'H:mm', + LTS : 'H:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM [de] YYYY', + ll : 'D MMM YYYY', + LLL : 'D MMMM [de] YYYY [a les] H:mm', + lll : 'D MMM YYYY, H:mm', + LLLL : 'dddd D MMMM [de] YYYY [a les] H:mm', + llll : 'ddd D MMM YYYY, H:mm' + }, + calendar : { + sameDay : function () { + return '[avui a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; + }, + nextDay : function () { + return '[demà a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; + }, + nextWeek : function () { + return 'dddd [a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; + }, + lastDay : function () { + return '[ahir a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; + }, + lastWeek : function () { + return '[el] dddd [passat a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; + }, + sameElse : 'L' + }, + relativeTime : { + future : 'd\'aquí %s', + past : 'fa %s', + s : 'uns segons', + ss : '%d segons', + m : 'un minut', + mm : '%d minuts', + h : 'una hora', + hh : '%d hores', + d : 'un dia', + dd : '%d dies', + M : 'un mes', + MM : '%d mesos', + y : 'un any', + yy : '%d anys' + }, + dayOfMonthOrdinalParse: /\d{1,2}(r|n|t|è|a)/, + ordinal : function (number, period) { + var output = (number === 1) ? 'r' : + (number === 2) ? 'n' : + (number === 3) ? 'r' : + (number === 4) ? 't' : 'è'; + if (period === 'w' || period === 'W') { + output = 'a'; + } + return number + output; + }, + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. + } + }); - var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; + return ca; - // date from iso format - function configFromISO(config) { - var i, l, - string = config._i, - match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), - allowTime, dateFormat, timeFormat, tzFormat; +}))); - if (match) { - getParsingFlags(config).iso = true; - for (i = 0, l = isoDates.length; i < l; i++) { - if (isoDates[i][1].exec(match[1])) { - dateFormat = isoDates[i][0]; - allowTime = isoDates[i][2] !== false; - break; - } - } - if (dateFormat == null) { - config._isValid = false; - return; - } - if (match[3]) { - for (i = 0, l = isoTimes.length; i < l; i++) { - if (isoTimes[i][1].exec(match[3])) { - // match[2] should be 'T' or space - timeFormat = (match[2] || ' ') + isoTimes[i][0]; - break; - } - } - if (timeFormat == null) { - config._isValid = false; - return; - } - } - if (!allowTime && timeFormat != null) { - config._isValid = false; - return; - } - if (match[4]) { - if (tzRegex.exec(match[4])) { - tzFormat = 'Z'; - } else { - config._isValid = false; - return; - } - } - config._f = dateFormat + (timeFormat || '') + (tzFormat || ''); - configFromStringAndFormat(config); - } else { - config._isValid = false; - } - } +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { - // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3 - var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/; +//! moment.js locale configuration - function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { - var result = [ - untruncateYear(yearStr), - defaultLocaleMonthsShort.indexOf(monthStr), - parseInt(dayStr, 10), - parseInt(hourStr, 10), - parseInt(minuteStr, 10) - ]; +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - if (secondStr) { - result.push(parseInt(secondStr, 10)); - } - return result; - } + var months = 'leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec'.split('_'), + monthsShort = 'led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro'.split('_'); - function untruncateYear(yearStr) { - var year = parseInt(yearStr, 10); - if (year <= 49) { - return 2000 + year; - } else if (year <= 999) { - return 1900 + year; - } - return year; - } + var monthsParse = [/^led/i, /^úno/i, /^bře/i, /^dub/i, /^kvě/i, /^(čvn|červen$|června)/i, /^(čvc|červenec|července)/i, /^srp/i, /^zář/i, /^říj/i, /^lis/i, /^pro/i]; + // NOTE: 'červen' is substring of 'červenec'; therefore 'červenec' must precede 'červen' in the regex to be fully matched. + // Otherwise parser matches '1. červenec' as '1. červen' + 'ec'. + var monthsRegex = /^(leden|únor|březen|duben|květen|červenec|července|červen|června|srpen|září|říjen|listopad|prosinec|led|úno|bře|dub|kvě|čvn|čvc|srp|zář|říj|lis|pro)/i; - function preprocessRFC2822(s) { - // Remove comments and folding whitespace and replace multiple-spaces with a single space - return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, ''); + function plural(n) { + return (n > 1) && (n < 5) && (~~(n / 10) !== 1); } - - function checkWeekday(weekdayStr, parsedInput, config) { - if (weekdayStr) { - // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check. - var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), - weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay(); - if (weekdayProvided !== weekdayActual) { - getParsingFlags(config).weekdayMismatch = true; - config._isValid = false; - return false; - } + function translate(number, withoutSuffix, key, isFuture) { + var result = number + ' '; + switch (key) { + case 's': // a few seconds / in a few seconds / a few seconds ago + return (withoutSuffix || isFuture) ? 'pár sekund' : 'pár sekundami'; + case 'ss': // 9 seconds / in 9 seconds / 9 seconds ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'sekundy' : 'sekund'); + } else { + return result + 'sekundami'; + } + break; + case 'm': // a minute / in a minute / a minute ago + return withoutSuffix ? 'minuta' : (isFuture ? 'minutu' : 'minutou'); + case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'minuty' : 'minut'); + } else { + return result + 'minutami'; + } + break; + case 'h': // an hour / in an hour / an hour ago + return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou'); + case 'hh': // 9 hours / in 9 hours / 9 hours ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'hodiny' : 'hodin'); + } else { + return result + 'hodinami'; + } + break; + case 'd': // a day / in a day / a day ago + return (withoutSuffix || isFuture) ? 'den' : 'dnem'; + case 'dd': // 9 days / in 9 days / 9 days ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'dny' : 'dní'); + } else { + return result + 'dny'; + } + break; + case 'M': // a month / in a month / a month ago + return (withoutSuffix || isFuture) ? 'měsíc' : 'měsícem'; + case 'MM': // 9 months / in 9 months / 9 months ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'měsíce' : 'měsíců'); + } else { + return result + 'měsíci'; + } + break; + case 'y': // a year / in a year / a year ago + return (withoutSuffix || isFuture) ? 'rok' : 'rokem'; + case 'yy': // 9 years / in 9 years / 9 years ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'roky' : 'let'); + } else { + return result + 'lety'; + } + break; } - return true; } - var obsOffsets = { - UT: 0, - GMT: 0, - EDT: -4 * 60, - EST: -5 * 60, - CDT: -5 * 60, - CST: -6 * 60, - MDT: -6 * 60, - MST: -7 * 60, - PDT: -7 * 60, - PST: -8 * 60 - }; - - function calculateOffset(obsOffset, militaryOffset, numOffset) { - if (obsOffset) { - return obsOffsets[obsOffset]; - } else if (militaryOffset) { - // the only allowed military tz is Z - return 0; - } else { - var hm = parseInt(numOffset, 10); - var m = hm % 100, h = (hm - m) / 100; - return h * 60 + m; + var cs = moment.defineLocale('cs', { + months : months, + monthsShort : monthsShort, + monthsRegex : monthsRegex, + monthsShortRegex : monthsRegex, + // NOTE: 'červen' is substring of 'červenec'; therefore 'červenec' must precede 'červen' in the regex to be fully matched. + // Otherwise parser matches '1. červenec' as '1. červen' + 'ec'. + monthsStrictRegex : /^(leden|ledna|února|únor|březen|března|duben|dubna|květen|května|červenec|července|červen|června|srpen|srpna|září|říjen|října|listopadu|listopad|prosinec|prosince)/i, + monthsShortStrictRegex : /^(led|úno|bře|dub|kvě|čvn|čvc|srp|zář|říj|lis|pro)/i, + monthsParse : monthsParse, + longMonthsParse : monthsParse, + shortMonthsParse : monthsParse, + weekdays : 'neděle_pondělí_úterý_středa_čtvrtek_pátek_sobota'.split('_'), + weekdaysShort : 'ne_po_út_st_čt_pá_so'.split('_'), + weekdaysMin : 'ne_po_út_st_čt_pá_so'.split('_'), + longDateFormat : { + LT: 'H:mm', + LTS : 'H:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D. MMMM YYYY', + LLL : 'D. MMMM YYYY H:mm', + LLLL : 'dddd D. MMMM YYYY H:mm', + l : 'D. M. YYYY' + }, + calendar : { + sameDay: '[dnes v] LT', + nextDay: '[zítra v] LT', + nextWeek: function () { + switch (this.day()) { + case 0: + return '[v neděli v] LT'; + case 1: + case 2: + return '[v] dddd [v] LT'; + case 3: + return '[ve středu v] LT'; + case 4: + return '[ve čtvrtek v] LT'; + case 5: + return '[v pátek v] LT'; + case 6: + return '[v sobotu v] LT'; + } + }, + lastDay: '[včera v] LT', + lastWeek: function () { + switch (this.day()) { + case 0: + return '[minulou neděli v] LT'; + case 1: + case 2: + return '[minulé] dddd [v] LT'; + case 3: + return '[minulou středu v] LT'; + case 4: + case 5: + return '[minulý] dddd [v] LT'; + case 6: + return '[minulou sobotu v] LT'; + } + }, + sameElse: 'L' + }, + relativeTime : { + future : 'za %s', + past : 'před %s', + s : translate, + ss : translate, + m : translate, + mm : translate, + h : translate, + hh : translate, + d : translate, + dd : translate, + M : translate, + MM : translate, + y : translate, + yy : translate + }, + dayOfMonthOrdinalParse : /\d{1,2}\./, + ordinal : '%d.', + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } - } + }); - // date and time from ref 2822 format - function configFromRFC2822(config) { - var match = rfc2822.exec(preprocessRFC2822(config._i)); - if (match) { - var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]); - if (!checkWeekday(match[1], parsedArray, config)) { - return; - } + return cs; - config._a = parsedArray; - config._tzm = calculateOffset(match[8], match[9], match[10]); +}))); - config._d = createUTCDate.apply(null, config._a); - config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); - getParsingFlags(config).rfc2822 = true; - } else { - config._isValid = false; - } - } +/***/ }), +/* 31 */ +/***/ (function(module, exports, __webpack_require__) { - // date from iso format or fallback - function configFromString(config) { - var matched = aspNetJsonRegex.exec(config._i); +//! moment.js locale configuration - if (matched !== null) { - config._d = new Date(+matched[1]); - return; - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - configFromISO(config); - if (config._isValid === false) { - delete config._isValid; - } else { - return; - } - configFromRFC2822(config); - if (config._isValid === false) { - delete config._isValid; - } else { - return; + var cv = moment.defineLocale('cv', { + months : 'кӑрлач_нарӑс_пуш_ака_май_ҫӗртме_утӑ_ҫурла_авӑн_юпа_чӳк_раштав'.split('_'), + monthsShort : 'кӑр_нар_пуш_ака_май_ҫӗр_утӑ_ҫур_авн_юпа_чӳк_раш'.split('_'), + weekdays : 'вырсарникун_тунтикун_ытларикун_юнкун_кӗҫнерникун_эрнекун_шӑматкун'.split('_'), + weekdaysShort : 'выр_тун_ытл_юн_кӗҫ_эрн_шӑм'.split('_'), + weekdaysMin : 'вр_тн_ыт_юн_кҫ_эр_шм'.split('_'), + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD-MM-YYYY', + LL : 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ]', + LLL : 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm', + LLLL : 'dddd, YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm' + }, + calendar : { + sameDay: '[Паян] LT [сехетре]', + nextDay: '[Ыран] LT [сехетре]', + lastDay: '[Ӗнер] LT [сехетре]', + nextWeek: '[Ҫитес] dddd LT [сехетре]', + lastWeek: '[Иртнӗ] dddd LT [сехетре]', + sameElse: 'L' + }, + relativeTime : { + future : function (output) { + var affix = /сехет$/i.exec(output) ? 'рен' : /ҫул$/i.exec(output) ? 'тан' : 'ран'; + return output + affix; + }, + past : '%s каялла', + s : 'пӗр-ик ҫеккунт', + ss : '%d ҫеккунт', + m : 'пӗр минут', + mm : '%d минут', + h : 'пӗр сехет', + hh : '%d сехет', + d : 'пӗр кун', + dd : '%d кун', + M : 'пӗр уйӑх', + MM : '%d уйӑх', + y : 'пӗр ҫул', + yy : '%d ҫул' + }, + dayOfMonthOrdinalParse: /\d{1,2}-мӗш/, + ordinal : '%d-мӗш', + week : { + dow : 1, // Monday is the first day of the week. + doy : 7 // The week that contains Jan 7th is the first week of the year. } + }); - // Final attempt, use Input Fallback - hooks.createFromInputFallback(config); - } + return cv; - hooks.createFromInputFallback = deprecate( - 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' + - 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' + - 'discouraged and will be removed in an upcoming major release. Please refer to ' + - 'http://momentjs.com/guides/#/warnings/js-date/ for more info.', - function (config) { - config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); - } - ); +}))); - // constant that refers to the ISO standard - hooks.ISO_8601 = function () {}; - // constant that refers to the RFC 2822 form - hooks.RFC_2822 = function () {}; +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { - // date from string and format string - function configFromStringAndFormat(config) { - // TODO: Move this to another part of the creation flow to prevent circular deps - if (config._f === hooks.ISO_8601) { - configFromISO(config); - return; - } - if (config._f === hooks.RFC_2822) { - configFromRFC2822(config); - return; - } - config._a = []; - getParsingFlags(config).empty = true; +//! moment.js locale configuration - // This array is used to make a Date, either with `new Date` or `Date.UTC` - var string = '' + config._i, - i, parsedInput, tokens, token, skipped, - stringLength = string.length, - totalParsedInputLength = 0; +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; - for (i = 0; i < tokens.length; i++) { - token = tokens[i]; - parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; - // console.log('token', token, 'parsedInput', parsedInput, - // 'regex', getParseRegexForToken(token, config)); - if (parsedInput) { - skipped = string.substr(0, string.indexOf(parsedInput)); - if (skipped.length > 0) { - getParsingFlags(config).unusedInput.push(skipped); - } - string = string.slice(string.indexOf(parsedInput) + parsedInput.length); - totalParsedInputLength += parsedInput.length; - } - // don't parse if it's not a known token - if (formatTokenFunctions[token]) { - if (parsedInput) { - getParsingFlags(config).empty = false; - } - else { - getParsingFlags(config).unusedTokens.push(token); + var cy = moment.defineLocale('cy', { + months: 'Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr'.split('_'), + monthsShort: 'Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag'.split('_'), + weekdays: 'Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn'.split('_'), + weekdaysShort: 'Sul_Llun_Maw_Mer_Iau_Gwe_Sad'.split('_'), + weekdaysMin: 'Su_Ll_Ma_Me_Ia_Gw_Sa'.split('_'), + weekdaysParseExact : true, + // time formats are the same as en-gb + longDateFormat: { + LT: 'HH:mm', + LTS : 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm' + }, + calendar: { + sameDay: '[Heddiw am] LT', + nextDay: '[Yfory am] LT', + nextWeek: 'dddd [am] LT', + lastDay: '[Ddoe am] LT', + lastWeek: 'dddd [diwethaf am] LT', + sameElse: 'L' + }, + relativeTime: { + future: 'mewn %s', + past: '%s yn ôl', + s: 'ychydig eiliadau', + ss: '%d eiliad', + m: 'munud', + mm: '%d munud', + h: 'awr', + hh: '%d awr', + d: 'diwrnod', + dd: '%d diwrnod', + M: 'mis', + MM: '%d mis', + y: 'blwyddyn', + yy: '%d flynedd' + }, + dayOfMonthOrdinalParse: /\d{1,2}(fed|ain|af|il|ydd|ed|eg)/, + // traditional ordinal numbers above 31 are not commonly used in colloquial Welsh + ordinal: function (number) { + var b = number, + output = '', + lookup = [ + '', 'af', 'il', 'ydd', 'ydd', 'ed', 'ed', 'ed', 'fed', 'fed', 'fed', // 1af to 10fed + 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'fed' // 11eg to 20fed + ]; + if (b > 20) { + if (b === 40 || b === 50 || b === 60 || b === 80 || b === 100) { + output = 'fed'; // not 30ain, 70ain or 90ain + } else { + output = 'ain'; } - addTimeToArrayFromToken(token, parsedInput, config); - } - else if (config._strict && !parsedInput) { - getParsingFlags(config).unusedTokens.push(token); + } else if (b > 0) { + output = lookup[b]; } + return number + output; + }, + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } + }); - // add remaining unparsed input length to the string - getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength; - if (string.length > 0) { - getParsingFlags(config).unusedInput.push(string); - } + return cy; - // clear _12h flag if hour is <= 12 - if (config._a[HOUR] <= 12 && - getParsingFlags(config).bigHour === true && - config._a[HOUR] > 0) { - getParsingFlags(config).bigHour = undefined; - } +}))); - getParsingFlags(config).parsedDateParts = config._a.slice(0); - getParsingFlags(config).meridiem = config._meridiem; - // handle meridiem - config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem); - configFromArray(config); - checkOverflow(config); - } +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { +//! moment.js locale configuration - function meridiemFixWrap (locale, hour, meridiem) { - var isPm; +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - if (meridiem == null) { - // nothing to do - return hour; - } - if (locale.meridiemHour != null) { - return locale.meridiemHour(hour, meridiem); - } else if (locale.isPM != null) { - // Fallback - isPm = locale.isPM(meridiem); - if (isPm && hour < 12) { - hour += 12; - } - if (!isPm && hour === 12) { - hour = 0; - } - return hour; - } else { - // this is not supposed to happen - return hour; + + var da = moment.defineLocale('da', { + months : 'januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december'.split('_'), + monthsShort : 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'), + weekdays : 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'), + weekdaysShort : 'søn_man_tir_ons_tor_fre_lør'.split('_'), + weekdaysMin : 'sø_ma_ti_on_to_fr_lø'.split('_'), + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D. MMMM YYYY', + LLL : 'D. MMMM YYYY HH:mm', + LLLL : 'dddd [d.] D. MMMM YYYY [kl.] HH:mm' + }, + calendar : { + sameDay : '[i dag kl.] LT', + nextDay : '[i morgen kl.] LT', + nextWeek : 'på dddd [kl.] LT', + lastDay : '[i går kl.] LT', + lastWeek : '[i] dddd[s kl.] LT', + sameElse : 'L' + }, + relativeTime : { + future : 'om %s', + past : '%s siden', + s : 'få sekunder', + ss : '%d sekunder', + m : 'et minut', + mm : '%d minutter', + h : 'en time', + hh : '%d timer', + d : 'en dag', + dd : '%d dage', + M : 'en måned', + MM : '%d måneder', + y : 'et år', + yy : '%d år' + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } - } + }); - // date from string and array of format strings - function configFromStringAndArray(config) { - var tempConfig, - bestMoment, + return da; - scoreToBeat, - i, - currentScore; +}))); - if (config._f.length === 0) { - getParsingFlags(config).invalidFormat = true; - config._d = new Date(NaN); - return; - } - for (i = 0; i < config._f.length; i++) { - currentScore = 0; - tempConfig = copyConfig({}, config); - if (config._useUTC != null) { - tempConfig._useUTC = config._useUTC; - } - tempConfig._f = config._f[i]; - configFromStringAndFormat(tempConfig); +/***/ }), +/* 34 */ +/***/ (function(module, exports, __webpack_require__) { - if (!isValid(tempConfig)) { - continue; - } +//! moment.js locale configuration - // if there is any input that was not parsed add a penalty for that format - currentScore += getParsingFlags(tempConfig).charsLeftOver; +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - //or tokens - currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; - getParsingFlags(tempConfig).score = currentScore; + function processRelativeTime(number, withoutSuffix, key, isFuture) { + var format = { + 'm': ['eine Minute', 'einer Minute'], + 'h': ['eine Stunde', 'einer Stunde'], + 'd': ['ein Tag', 'einem Tag'], + 'dd': [number + ' Tage', number + ' Tagen'], + 'M': ['ein Monat', 'einem Monat'], + 'MM': [number + ' Monate', number + ' Monaten'], + 'y': ['ein Jahr', 'einem Jahr'], + 'yy': [number + ' Jahre', number + ' Jahren'] + }; + return withoutSuffix ? format[key][0] : format[key][1]; + } - if (scoreToBeat == null || currentScore < scoreToBeat) { - scoreToBeat = currentScore; - bestMoment = tempConfig; - } + var de = moment.defineLocale('de', { + months : 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), + monthsShort : 'Jan._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'), + monthsParseExact : true, + weekdays : 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'), + weekdaysShort : 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'), + weekdaysMin : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D. MMMM YYYY', + LLL : 'D. MMMM YYYY HH:mm', + LLLL : 'dddd, D. MMMM YYYY HH:mm' + }, + calendar : { + sameDay: '[heute um] LT [Uhr]', + sameElse: 'L', + nextDay: '[morgen um] LT [Uhr]', + nextWeek: 'dddd [um] LT [Uhr]', + lastDay: '[gestern um] LT [Uhr]', + lastWeek: '[letzten] dddd [um] LT [Uhr]' + }, + relativeTime : { + future : 'in %s', + past : 'vor %s', + s : 'ein paar Sekunden', + ss : '%d Sekunden', + m : processRelativeTime, + mm : '%d Minuten', + h : processRelativeTime, + hh : '%d Stunden', + d : processRelativeTime, + dd : processRelativeTime, + M : processRelativeTime, + MM : processRelativeTime, + y : processRelativeTime, + yy : processRelativeTime + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } + }); - extend(config, bestMoment || tempConfig); - } + return de; - function configFromObject(config) { - if (config._d) { - return; - } +}))); - var i = normalizeObjectUnits(config._i); - config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) { - return obj && parseInt(obj, 10); - }); - configFromArray(config); +/***/ }), +/* 35 */ +/***/ (function(module, exports, __webpack_require__) { + +//! moment.js locale configuration + +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; + + + function processRelativeTime(number, withoutSuffix, key, isFuture) { + var format = { + 'm': ['eine Minute', 'einer Minute'], + 'h': ['eine Stunde', 'einer Stunde'], + 'd': ['ein Tag', 'einem Tag'], + 'dd': [number + ' Tage', number + ' Tagen'], + 'M': ['ein Monat', 'einem Monat'], + 'MM': [number + ' Monate', number + ' Monaten'], + 'y': ['ein Jahr', 'einem Jahr'], + 'yy': [number + ' Jahre', number + ' Jahren'] + }; + return withoutSuffix ? format[key][0] : format[key][1]; } - function createFromConfig (config) { - var res = new Moment(checkOverflow(prepareConfig(config))); - if (res._nextDay) { - // Adding is smart enough around DST - res.add(1, 'd'); - res._nextDay = undefined; + var deAt = moment.defineLocale('de-at', { + months : 'Jänner_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), + monthsShort : 'Jän._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'), + monthsParseExact : true, + weekdays : 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'), + weekdaysShort : 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'), + weekdaysMin : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D. MMMM YYYY', + LLL : 'D. MMMM YYYY HH:mm', + LLLL : 'dddd, D. MMMM YYYY HH:mm' + }, + calendar : { + sameDay: '[heute um] LT [Uhr]', + sameElse: 'L', + nextDay: '[morgen um] LT [Uhr]', + nextWeek: 'dddd [um] LT [Uhr]', + lastDay: '[gestern um] LT [Uhr]', + lastWeek: '[letzten] dddd [um] LT [Uhr]' + }, + relativeTime : { + future : 'in %s', + past : 'vor %s', + s : 'ein paar Sekunden', + ss : '%d Sekunden', + m : processRelativeTime, + mm : '%d Minuten', + h : processRelativeTime, + hh : '%d Stunden', + d : processRelativeTime, + dd : processRelativeTime, + M : processRelativeTime, + MM : processRelativeTime, + y : processRelativeTime, + yy : processRelativeTime + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } + }); - return res; - } + return deAt; - function prepareConfig (config) { - var input = config._i, - format = config._f; +}))); - config._locale = config._locale || getLocale(config._l); - if (input === null || (format === undefined && input === '')) { - return createInvalid({nullInput: true}); - } +/***/ }), +/* 36 */ +/***/ (function(module, exports, __webpack_require__) { - if (typeof input === 'string') { - config._i = input = config._locale.preparse(input); - } +//! moment.js locale configuration - if (isMoment(input)) { - return new Moment(checkOverflow(input)); - } else if (isDate(input)) { - config._d = input; - } else if (isArray(format)) { - configFromStringAndArray(config); - } else if (format) { - configFromStringAndFormat(config); - } else { - configFromInput(config); - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - if (!isValid(config)) { - config._d = null; - } - return config; + function processRelativeTime(number, withoutSuffix, key, isFuture) { + var format = { + 'm': ['eine Minute', 'einer Minute'], + 'h': ['eine Stunde', 'einer Stunde'], + 'd': ['ein Tag', 'einem Tag'], + 'dd': [number + ' Tage', number + ' Tagen'], + 'M': ['ein Monat', 'einem Monat'], + 'MM': [number + ' Monate', number + ' Monaten'], + 'y': ['ein Jahr', 'einem Jahr'], + 'yy': [number + ' Jahre', number + ' Jahren'] + }; + return withoutSuffix ? format[key][0] : format[key][1]; } - function configFromInput(config) { - var input = config._i; - if (isUndefined(input)) { - config._d = new Date(hooks.now()); - } else if (isDate(input)) { - config._d = new Date(input.valueOf()); - } else if (typeof input === 'string') { - configFromString(config); - } else if (isArray(input)) { - config._a = map(input.slice(0), function (obj) { - return parseInt(obj, 10); - }); - configFromArray(config); - } else if (isObject(input)) { - configFromObject(config); - } else if (isNumber(input)) { - // from milliseconds - config._d = new Date(input); - } else { - hooks.createFromInputFallback(config); + var deCh = moment.defineLocale('de-ch', { + months : 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), + monthsShort : 'Jan._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'), + monthsParseExact : true, + weekdays : 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'), + weekdaysShort : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), + weekdaysMin : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D. MMMM YYYY', + LLL : 'D. MMMM YYYY HH:mm', + LLLL : 'dddd, D. MMMM YYYY HH:mm' + }, + calendar : { + sameDay: '[heute um] LT [Uhr]', + sameElse: 'L', + nextDay: '[morgen um] LT [Uhr]', + nextWeek: 'dddd [um] LT [Uhr]', + lastDay: '[gestern um] LT [Uhr]', + lastWeek: '[letzten] dddd [um] LT [Uhr]' + }, + relativeTime : { + future : 'in %s', + past : 'vor %s', + s : 'ein paar Sekunden', + ss : '%d Sekunden', + m : processRelativeTime, + mm : '%d Minuten', + h : processRelativeTime, + hh : '%d Stunden', + d : processRelativeTime, + dd : processRelativeTime, + M : processRelativeTime, + MM : processRelativeTime, + y : processRelativeTime, + yy : processRelativeTime + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } - } + }); - function createLocalOrUTC (input, format, locale, strict, isUTC) { - var c = {}; + return deCh; - if (locale === true || locale === false) { - strict = locale; - locale = undefined; - } +}))); - if ((isObject(input) && isObjectEmpty(input)) || - (isArray(input) && input.length === 0)) { - input = undefined; - } - // object construction must be done this way. - // https://github.com/moment/moment/issues/1423 - c._isAMomentObject = true; - c._useUTC = c._isUTC = isUTC; - c._l = locale; - c._i = input; - c._f = format; - c._strict = strict; - return createFromConfig(c); - } +/***/ }), +/* 37 */ +/***/ (function(module, exports, __webpack_require__) { - function createLocal (input, format, locale, strict) { - return createLocalOrUTC(input, format, locale, strict, false); - } +//! moment.js locale configuration - var prototypeMin = deprecate( - 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', - function () { - var other = createLocal.apply(null, arguments); - if (this.isValid() && other.isValid()) { - return other < this ? this : other; - } else { - return createInvalid(); - } - } - ); +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - var prototypeMax = deprecate( - 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', - function () { - var other = createLocal.apply(null, arguments); - if (this.isValid() && other.isValid()) { - return other > this ? this : other; + + var months = [ + 'ޖެނުއަރީ', + 'ފެބްރުއަރީ', + 'މާރިޗު', + 'އޭޕްރީލު', + 'މޭ', + 'ޖޫން', + 'ޖުލައި', + 'އޯގަސްޓު', + 'ސެޕްޓެމްބަރު', + 'އޮކްޓޯބަރު', + 'ނޮވެމްބަރު', + 'ޑިސެމްބަރު' + ], weekdays = [ + 'އާދިއްތަ', + 'ހޯމަ', + 'އަންގާރަ', + 'ބުދަ', + 'ބުރާސްފަތި', + 'ހުކުރު', + 'ހޮނިހިރު' + ]; + + var dv = moment.defineLocale('dv', { + months : months, + monthsShort : months, + weekdays : weekdays, + weekdaysShort : weekdays, + weekdaysMin : 'އާދި_ހޯމަ_އަން_ބުދަ_ބުރާ_ހުކު_ހޮނި'.split('_'), + longDateFormat : { + + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'D/M/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd D MMMM YYYY HH:mm' + }, + meridiemParse: /މކ|މފ/, + isPM : function (input) { + return 'މފ' === input; + }, + meridiem : function (hour, minute, isLower) { + if (hour < 12) { + return 'މކ'; } else { - return createInvalid(); + return 'މފ'; } + }, + calendar : { + sameDay : '[މިއަދު] LT', + nextDay : '[މާދަމާ] LT', + nextWeek : 'dddd LT', + lastDay : '[އިއްޔެ] LT', + lastWeek : '[ފާއިތުވި] dddd LT', + sameElse : 'L' + }, + relativeTime : { + future : 'ތެރޭގައި %s', + past : 'ކުރިން %s', + s : 'ސިކުންތުކޮޅެއް', + ss : 'd% ސިކުންތު', + m : 'މިނިޓެއް', + mm : 'މިނިޓު %d', + h : 'ގަޑިއިރެއް', + hh : 'ގަޑިއިރު %d', + d : 'ދުވަހެއް', + dd : 'ދުވަސް %d', + M : 'މަހެއް', + MM : 'މަސް %d', + y : 'އަހަރެއް', + yy : 'އަހަރު %d' + }, + preparse: function (string) { + return string.replace(/،/g, ','); + }, + postformat: function (string) { + return string.replace(/,/g, '،'); + }, + week : { + dow : 7, // Sunday is the first day of the week. + doy : 12 // The week that contains Jan 12th is the first week of the year. } - ); + }); - // Pick a moment m from moments so that m[fn](other) is true for all - // other. This relies on the function fn to be transitive. - // - // moments should either be an array of moment objects or an array, whose - // first element is an array of moment objects. - function pickBy(fn, moments) { - var res, i; - if (moments.length === 1 && isArray(moments[0])) { - moments = moments[0]; - } - if (!moments.length) { - return createLocal(); - } - res = moments[0]; - for (i = 1; i < moments.length; ++i) { - if (!moments[i].isValid() || moments[i][fn](res)) { - res = moments[i]; - } - } - return res; - } + return dv; - // TODO: Use [].sort instead? - function min () { - var args = [].slice.call(arguments, 0); +}))); - return pickBy('isBefore', args); - } - function max () { - var args = [].slice.call(arguments, 0); +/***/ }), +/* 38 */ +/***/ (function(module, exports, __webpack_require__) { - return pickBy('isAfter', args); - } +//! moment.js locale configuration - var now = function () { - return Date.now ? Date.now() : +(new Date()); - }; +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond']; + function isFunction(input) { + return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]'; + } - function isDurationValid(m) { - for (var key in m) { - if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) { - return false; - } - } - var unitHasDecimal = false; - for (var i = 0; i < ordering.length; ++i) { - if (m[ordering[i]]) { - if (unitHasDecimal) { - return false; // only allow non-integers for smallest unit - } - if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) { - unitHasDecimal = true; + var el = moment.defineLocale('el', { + monthsNominativeEl : 'Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος'.split('_'), + monthsGenitiveEl : 'Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου'.split('_'), + months : function (momentToFormat, format) { + if (!momentToFormat) { + return this._monthsNominativeEl; + } else if (typeof format === 'string' && /D/.test(format.substring(0, format.indexOf('MMMM')))) { // if there is a day number before 'MMMM' + return this._monthsGenitiveEl[momentToFormat.month()]; + } else { + return this._monthsNominativeEl[momentToFormat.month()]; + } + }, + monthsShort : 'Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ'.split('_'), + weekdays : 'Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο'.split('_'), + weekdaysShort : 'Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ'.split('_'), + weekdaysMin : 'Κυ_Δε_Τρ_Τε_Πε_Πα_Σα'.split('_'), + meridiem : function (hours, minutes, isLower) { + if (hours > 11) { + return isLower ? 'μμ' : 'ΜΜ'; + } else { + return isLower ? 'πμ' : 'ΠΜ'; + } + }, + isPM : function (input) { + return ((input + '').toLowerCase()[0] === 'μ'); + }, + meridiemParse : /[ΠΜ]\.?Μ?\.?/i, + longDateFormat : { + LT : 'h:mm A', + LTS : 'h:mm:ss A', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY h:mm A', + LLLL : 'dddd, D MMMM YYYY h:mm A' + }, + calendarEl : { + sameDay : '[Σήμερα {}] LT', + nextDay : '[Αύριο {}] LT', + nextWeek : 'dddd [{}] LT', + lastDay : '[Χθες {}] LT', + lastWeek : function () { + switch (this.day()) { + case 6: + return '[το προηγούμενο] dddd [{}] LT'; + default: + return '[την προηγούμενη] dddd [{}] LT'; } + }, + sameElse : 'L' + }, + calendar : function (key, mom) { + var output = this._calendarEl[key], + hours = mom && mom.hours(); + if (isFunction(output)) { + output = output.apply(mom); } + return output.replace('{}', (hours % 12 === 1 ? 'στη' : 'στις')); + }, + relativeTime : { + future : 'σε %s', + past : '%s πριν', + s : 'λίγα δευτερόλεπτα', + ss : '%d δευτερόλεπτα', + m : 'ένα λεπτό', + mm : '%d λεπτά', + h : 'μία ώρα', + hh : '%d ώρες', + d : 'μία μέρα', + dd : '%d μέρες', + M : 'ένας μήνας', + MM : '%d μήνες', + y : 'ένας χρόνος', + yy : '%d χρόνια' + }, + dayOfMonthOrdinalParse: /\d{1,2}η/, + ordinal: '%dη', + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4st is the first week of the year. } + }); - return true; - } - - function isValid$1() { - return this._isValid; - } - - function createInvalid$1() { - return createDuration(NaN); - } - - function Duration (duration) { - var normalizedInput = normalizeObjectUnits(duration), - years = normalizedInput.year || 0, - quarters = normalizedInput.quarter || 0, - months = normalizedInput.month || 0, - weeks = normalizedInput.week || normalizedInput.isoWeek || 0, - days = normalizedInput.day || 0, - hours = normalizedInput.hour || 0, - minutes = normalizedInput.minute || 0, - seconds = normalizedInput.second || 0, - milliseconds = normalizedInput.millisecond || 0; + return el; - this._isValid = isDurationValid(normalizedInput); +}))); - // representation for dateAddRemove - this._milliseconds = +milliseconds + - seconds * 1e3 + // 1000 - minutes * 6e4 + // 1000 * 60 - hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978 - // Because of dateAddRemove treats 24 hours as different from a - // day when working around DST, we need to store them separately - this._days = +days + - weeks * 7; - // It is impossible to translate months into days without knowing - // which months you are are talking about, so we have to store - // it separately. - this._months = +months + - quarters * 3 + - years * 12; - this._data = {}; +/***/ }), +/* 39 */ +/***/ (function(module, exports, __webpack_require__) { - this._locale = getLocale(); +//! moment.js locale configuration - this._bubble(); - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - function isDuration (obj) { - return obj instanceof Duration; - } - function absRound (number) { - if (number < 0) { - return Math.round(-1 * number) * -1; - } else { - return Math.round(number); + var enSG = moment.defineLocale('en-SG', { + months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), + monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), + weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), + weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), + weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd, D MMMM YYYY HH:mm' + }, + calendar : { + sameDay : '[Today at] LT', + nextDay : '[Tomorrow at] LT', + nextWeek : 'dddd [at] LT', + lastDay : '[Yesterday at] LT', + lastWeek : '[Last] dddd [at] LT', + sameElse : 'L' + }, + relativeTime : { + future : 'in %s', + past : '%s ago', + s : 'a few seconds', + ss : '%d seconds', + m : 'a minute', + mm : '%d minutes', + h : 'an hour', + hh : '%d hours', + d : 'a day', + dd : '%d days', + M : 'a month', + MM : '%d months', + y : 'a year', + yy : '%d years' + }, + dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, + ordinal : function (number) { + var b = number % 10, + output = (~~(number % 100 / 10) === 1) ? 'th' : + (b === 1) ? 'st' : + (b === 2) ? 'nd' : + (b === 3) ? 'rd' : 'th'; + return number + output; + }, + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } - } - - // FORMATTING + }); - function offset (token, separator) { - addFormatToken(token, 0, 0, function () { - var offset = this.utcOffset(); - var sign = '+'; - if (offset < 0) { - offset = -offset; - sign = '-'; - } - return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2); - }); - } + return enSG; - offset('Z', ':'); - offset('ZZ', ''); +}))); - // PARSING - addRegexToken('Z', matchShortOffset); - addRegexToken('ZZ', matchShortOffset); - addParseToken(['Z', 'ZZ'], function (input, array, config) { - config._useUTC = true; - config._tzm = offsetFromString(matchShortOffset, input); - }); +/***/ }), +/* 40 */ +/***/ (function(module, exports, __webpack_require__) { - // HELPERS +//! moment.js locale configuration - // timezone chunker - // '+10:00' > ['10', '00'] - // '-1530' > ['-15', '30'] - var chunkOffset = /([\+\-]|\d\d)/gi; +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - function offsetFromString(matcher, string) { - var matches = (string || '').match(matcher); - if (matches === null) { - return null; + var enAu = moment.defineLocale('en-au', { + months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), + monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), + weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), + weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), + weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + longDateFormat : { + LT : 'h:mm A', + LTS : 'h:mm:ss A', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY h:mm A', + LLLL : 'dddd, D MMMM YYYY h:mm A' + }, + calendar : { + sameDay : '[Today at] LT', + nextDay : '[Tomorrow at] LT', + nextWeek : 'dddd [at] LT', + lastDay : '[Yesterday at] LT', + lastWeek : '[Last] dddd [at] LT', + sameElse : 'L' + }, + relativeTime : { + future : 'in %s', + past : '%s ago', + s : 'a few seconds', + ss : '%d seconds', + m : 'a minute', + mm : '%d minutes', + h : 'an hour', + hh : '%d hours', + d : 'a day', + dd : '%d days', + M : 'a month', + MM : '%d months', + y : 'a year', + yy : '%d years' + }, + dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, + ordinal : function (number) { + var b = number % 10, + output = (~~(number % 100 / 10) === 1) ? 'th' : + (b === 1) ? 'st' : + (b === 2) ? 'nd' : + (b === 3) ? 'rd' : 'th'; + return number + output; + }, + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } + }); - var chunk = matches[matches.length - 1] || []; - var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; - var minutes = +(parts[1] * 60) + toInt(parts[2]); + return enAu; - return minutes === 0 ? - 0 : - parts[0] === '+' ? minutes : -minutes; - } +}))); - // Return a moment from input, that is local/utc/zone equivalent to model. - function cloneWithOffset(input, model) { - var res, diff; - if (model._isUTC) { - res = model.clone(); - diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(); - // Use low-level api, because this fn is low-level api. - res._d.setTime(res._d.valueOf() + diff); - hooks.updateOffset(res, false); - return res; - } else { - return createLocal(input).local(); - } - } - function getDateOffset (m) { - // On Firefox.24 Date#getTimezoneOffset returns a floating point. - // https://github.com/moment/moment/pull/1871 - return -Math.round(m._d.getTimezoneOffset() / 15) * 15; - } +/***/ }), +/* 41 */ +/***/ (function(module, exports, __webpack_require__) { - // HOOKS +//! moment.js locale configuration - // This function will be called whenever a moment is mutated. - // It is intended to keep the offset in sync with the timezone. - hooks.updateOffset = function () {}; +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - // MOMENTS - // keepLocalTime = true means only change the timezone, without - // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> - // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset - // +0200, so we adjust the time as needed, to be valid. - // - // Keeping the time actually adds/subtracts (one hour) - // from the actual represented time. That is why we call updateOffset - // a second time. In case it wants us to change the offset again - // _changeInProgress == true case, then we have to adjust, because - // there is no such time in the given timezone. - function getSetOffset (input, keepLocalTime, keepMinutes) { - var offset = this._offset || 0, - localAdjust; - if (!this.isValid()) { - return input != null ? this : NaN; - } - if (input != null) { - if (typeof input === 'string') { - input = offsetFromString(matchShortOffset, input); - if (input === null) { - return this; - } - } else if (Math.abs(input) < 16 && !keepMinutes) { - input = input * 60; - } - if (!this._isUTC && keepLocalTime) { - localAdjust = getDateOffset(this); - } - this._offset = input; - this._isUTC = true; - if (localAdjust != null) { - this.add(localAdjust, 'm'); - } - if (offset !== input) { - if (!keepLocalTime || this._changeInProgress) { - addSubtract(this, createDuration(input - offset, 'm'), 1, false); - } else if (!this._changeInProgress) { - this._changeInProgress = true; - hooks.updateOffset(this, true); - this._changeInProgress = null; - } - } - return this; - } else { - return this._isUTC ? offset : getDateOffset(this); + var enCa = moment.defineLocale('en-ca', { + months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), + monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), + weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), + weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), + weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + longDateFormat : { + LT : 'h:mm A', + LTS : 'h:mm:ss A', + L : 'YYYY-MM-DD', + LL : 'MMMM D, YYYY', + LLL : 'MMMM D, YYYY h:mm A', + LLLL : 'dddd, MMMM D, YYYY h:mm A' + }, + calendar : { + sameDay : '[Today at] LT', + nextDay : '[Tomorrow at] LT', + nextWeek : 'dddd [at] LT', + lastDay : '[Yesterday at] LT', + lastWeek : '[Last] dddd [at] LT', + sameElse : 'L' + }, + relativeTime : { + future : 'in %s', + past : '%s ago', + s : 'a few seconds', + ss : '%d seconds', + m : 'a minute', + mm : '%d minutes', + h : 'an hour', + hh : '%d hours', + d : 'a day', + dd : '%d days', + M : 'a month', + MM : '%d months', + y : 'a year', + yy : '%d years' + }, + dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, + ordinal : function (number) { + var b = number % 10, + output = (~~(number % 100 / 10) === 1) ? 'th' : + (b === 1) ? 'st' : + (b === 2) ? 'nd' : + (b === 3) ? 'rd' : 'th'; + return number + output; } - } + }); - function getSetZone (input, keepLocalTime) { - if (input != null) { - if (typeof input !== 'string') { - input = -input; - } + return enCa; - this.utcOffset(input, keepLocalTime); +}))); - return this; - } else { - return -this.utcOffset(); - } - } - function setOffsetToUTC (keepLocalTime) { - return this.utcOffset(0, keepLocalTime); - } +/***/ }), +/* 42 */ +/***/ (function(module, exports, __webpack_require__) { - function setOffsetToLocal (keepLocalTime) { - if (this._isUTC) { - this.utcOffset(0, keepLocalTime); - this._isUTC = false; +//! moment.js locale configuration - if (keepLocalTime) { - this.subtract(getDateOffset(this), 'm'); - } - } - return this; - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - function setOffsetToParsedOffset () { - if (this._tzm != null) { - this.utcOffset(this._tzm, false, true); - } else if (typeof this._i === 'string') { - var tZone = offsetFromString(matchOffset, this._i); - if (tZone != null) { - this.utcOffset(tZone); - } - else { - this.utcOffset(0, true); - } - } - return this; - } - function hasAlignedHourOffset (input) { - if (!this.isValid()) { - return false; + var enGb = moment.defineLocale('en-gb', { + months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), + monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), + weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), + weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), + weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd, D MMMM YYYY HH:mm' + }, + calendar : { + sameDay : '[Today at] LT', + nextDay : '[Tomorrow at] LT', + nextWeek : 'dddd [at] LT', + lastDay : '[Yesterday at] LT', + lastWeek : '[Last] dddd [at] LT', + sameElse : 'L' + }, + relativeTime : { + future : 'in %s', + past : '%s ago', + s : 'a few seconds', + ss : '%d seconds', + m : 'a minute', + mm : '%d minutes', + h : 'an hour', + hh : '%d hours', + d : 'a day', + dd : '%d days', + M : 'a month', + MM : '%d months', + y : 'a year', + yy : '%d years' + }, + dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, + ordinal : function (number) { + var b = number % 10, + output = (~~(number % 100 / 10) === 1) ? 'th' : + (b === 1) ? 'st' : + (b === 2) ? 'nd' : + (b === 3) ? 'rd' : 'th'; + return number + output; + }, + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } - input = input ? createLocal(input).utcOffset() : 0; - - return (this.utcOffset() - input) % 60 === 0; - } + }); - function isDaylightSavingTime () { - return ( - this.utcOffset() > this.clone().month(0).utcOffset() || - this.utcOffset() > this.clone().month(5).utcOffset() - ); - } + return enGb; - function isDaylightSavingTimeShifted () { - if (!isUndefined(this._isDSTShifted)) { - return this._isDSTShifted; - } +}))); - var c = {}; - copyConfig(c, this); - c = prepareConfig(c); +/***/ }), +/* 43 */ +/***/ (function(module, exports, __webpack_require__) { - if (c._a) { - var other = c._isUTC ? createUTC(c._a) : createLocal(c._a); - this._isDSTShifted = this.isValid() && - compareArrays(c._a, other.toArray()) > 0; - } else { - this._isDSTShifted = false; - } +//! moment.js locale configuration - return this._isDSTShifted; - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - function isLocal () { - return this.isValid() ? !this._isUTC : false; - } - function isUtcOffset () { - return this.isValid() ? this._isUTC : false; - } + var enIe = moment.defineLocale('en-ie', { + months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), + monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), + weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), + weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), + weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd D MMMM YYYY HH:mm' + }, + calendar : { + sameDay : '[Today at] LT', + nextDay : '[Tomorrow at] LT', + nextWeek : 'dddd [at] LT', + lastDay : '[Yesterday at] LT', + lastWeek : '[Last] dddd [at] LT', + sameElse : 'L' + }, + relativeTime : { + future : 'in %s', + past : '%s ago', + s : 'a few seconds', + ss : '%d seconds', + m : 'a minute', + mm : '%d minutes', + h : 'an hour', + hh : '%d hours', + d : 'a day', + dd : '%d days', + M : 'a month', + MM : '%d months', + y : 'a year', + yy : '%d years' + }, + dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, + ordinal : function (number) { + var b = number % 10, + output = (~~(number % 100 / 10) === 1) ? 'th' : + (b === 1) ? 'st' : + (b === 2) ? 'nd' : + (b === 3) ? 'rd' : 'th'; + return number + output; + }, + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. + } + }); - function isUtc () { - return this.isValid() ? this._isUTC && this._offset === 0 : false; - } + return enIe; - // ASP.NET json date format regex - var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/; +}))); - // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html - // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere - // and further modified to allow for strings containing both week and day - var isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; - function createDuration (input, key) { - var duration = input, - // matching against regexp is expensive, do it on demand - match = null, - sign, - ret, - diffRes; +/***/ }), +/* 44 */ +/***/ (function(module, exports, __webpack_require__) { - if (isDuration(input)) { - duration = { - ms : input._milliseconds, - d : input._days, - M : input._months - }; - } else if (isNumber(input)) { - duration = {}; - if (key) { - duration[key] = input; - } else { - duration.milliseconds = input; - } - } else if (!!(match = aspNetRegex.exec(input))) { - sign = (match[1] === '-') ? -1 : 1; - duration = { - y : 0, - d : toInt(match[DATE]) * sign, - h : toInt(match[HOUR]) * sign, - m : toInt(match[MINUTE]) * sign, - s : toInt(match[SECOND]) * sign, - ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match - }; - } else if (!!(match = isoRegex.exec(input))) { - sign = (match[1] === '-') ? -1 : 1; - duration = { - y : parseIso(match[2], sign), - M : parseIso(match[3], sign), - w : parseIso(match[4], sign), - d : parseIso(match[5], sign), - h : parseIso(match[6], sign), - m : parseIso(match[7], sign), - s : parseIso(match[8], sign) - }; - } else if (duration == null) {// checks for null or undefined - duration = {}; - } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { - diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to)); +//! moment.js locale configuration - duration = {}; - duration.ms = diffRes.milliseconds; - duration.M = diffRes.months; - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - ret = new Duration(duration); - if (isDuration(input) && hasOwnProp(input, '_locale')) { - ret._locale = input._locale; + var enIl = moment.defineLocale('en-il', { + months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), + monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), + weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), + weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), + weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd, D MMMM YYYY HH:mm' + }, + calendar : { + sameDay : '[Today at] LT', + nextDay : '[Tomorrow at] LT', + nextWeek : 'dddd [at] LT', + lastDay : '[Yesterday at] LT', + lastWeek : '[Last] dddd [at] LT', + sameElse : 'L' + }, + relativeTime : { + future : 'in %s', + past : '%s ago', + s : 'a few seconds', + m : 'a minute', + mm : '%d minutes', + h : 'an hour', + hh : '%d hours', + d : 'a day', + dd : '%d days', + M : 'a month', + MM : '%d months', + y : 'a year', + yy : '%d years' + }, + dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, + ordinal : function (number) { + var b = number % 10, + output = (~~(number % 100 / 10) === 1) ? 'th' : + (b === 1) ? 'st' : + (b === 2) ? 'nd' : + (b === 3) ? 'rd' : 'th'; + return number + output; } + }); - return ret; - } + return enIl; - createDuration.fn = Duration.prototype; - createDuration.invalid = createInvalid$1; +}))); - function parseIso (inp, sign) { - // We'd normally use ~~inp for this, but unfortunately it also - // converts floats to ints. - // inp may be undefined, so careful calling replace on it. - var res = inp && parseFloat(inp.replace(',', '.')); - // apply sign while we're at it - return (isNaN(res) ? 0 : res) * sign; - } - function positiveMomentsDifference(base, other) { - var res = {}; +/***/ }), +/* 45 */ +/***/ (function(module, exports, __webpack_require__) { - res.months = other.month() - base.month() + - (other.year() - base.year()) * 12; - if (base.clone().add(res.months, 'M').isAfter(other)) { - --res.months; - } +//! moment.js locale configuration - res.milliseconds = +other - +(base.clone().add(res.months, 'M')); +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - return res; - } - function momentsDifference(base, other) { - var res; - if (!(base.isValid() && other.isValid())) { - return {milliseconds: 0, months: 0}; + var enNz = moment.defineLocale('en-nz', { + months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), + monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), + weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), + weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), + weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + longDateFormat : { + LT : 'h:mm A', + LTS : 'h:mm:ss A', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY h:mm A', + LLLL : 'dddd, D MMMM YYYY h:mm A' + }, + calendar : { + sameDay : '[Today at] LT', + nextDay : '[Tomorrow at] LT', + nextWeek : 'dddd [at] LT', + lastDay : '[Yesterday at] LT', + lastWeek : '[Last] dddd [at] LT', + sameElse : 'L' + }, + relativeTime : { + future : 'in %s', + past : '%s ago', + s : 'a few seconds', + ss : '%d seconds', + m : 'a minute', + mm : '%d minutes', + h : 'an hour', + hh : '%d hours', + d : 'a day', + dd : '%d days', + M : 'a month', + MM : '%d months', + y : 'a year', + yy : '%d years' + }, + dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, + ordinal : function (number) { + var b = number % 10, + output = (~~(number % 100 / 10) === 1) ? 'th' : + (b === 1) ? 'st' : + (b === 2) ? 'nd' : + (b === 3) ? 'rd' : 'th'; + return number + output; + }, + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } + }); - other = cloneWithOffset(other, base); - if (base.isBefore(other)) { - res = positiveMomentsDifference(base, other); - } else { - res = positiveMomentsDifference(other, base); - res.milliseconds = -res.milliseconds; - res.months = -res.months; - } + return enNz; - return res; - } +}))); - // TODO: remove 'name' arg after deprecation is removed - function createAdder(direction, name) { - return function (val, period) { - var dur, tmp; - //invert the arguments, but complain about it - if (period !== null && !isNaN(+period)) { - deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' + - 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'); - tmp = val; val = period; period = tmp; - } - val = typeof val === 'string' ? +val : val; - dur = createDuration(val, period); - addSubtract(this, dur, direction); - return this; - }; - } +/***/ }), +/* 46 */ +/***/ (function(module, exports, __webpack_require__) { - function addSubtract (mom, duration, isAdding, updateOffset) { - var milliseconds = duration._milliseconds, - days = absRound(duration._days), - months = absRound(duration._months); +//! moment.js locale configuration - if (!mom.isValid()) { - // No op - return; - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - updateOffset = updateOffset == null ? true : updateOffset; - if (months) { - setMonth(mom, get(mom, 'Month') + months * isAdding); - } - if (days) { - set$1(mom, 'Date', get(mom, 'Date') + days * isAdding); - } - if (milliseconds) { - mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding); - } - if (updateOffset) { - hooks.updateOffset(mom, days || months); + var eo = moment.defineLocale('eo', { + months : 'januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro'.split('_'), + monthsShort : 'jan_feb_mar_apr_maj_jun_jul_aŭg_sep_okt_nov_dec'.split('_'), + weekdays : 'dimanĉo_lundo_mardo_merkredo_ĵaŭdo_vendredo_sabato'.split('_'), + weekdaysShort : 'dim_lun_mard_merk_ĵaŭ_ven_sab'.split('_'), + weekdaysMin : 'di_lu_ma_me_ĵa_ve_sa'.split('_'), + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'YYYY-MM-DD', + LL : 'D[-a de] MMMM, YYYY', + LLL : 'D[-a de] MMMM, YYYY HH:mm', + LLLL : 'dddd, [la] D[-a de] MMMM, YYYY HH:mm' + }, + meridiemParse: /[ap]\.t\.m/i, + isPM: function (input) { + return input.charAt(0).toLowerCase() === 'p'; + }, + meridiem : function (hours, minutes, isLower) { + if (hours > 11) { + return isLower ? 'p.t.m.' : 'P.T.M.'; + } else { + return isLower ? 'a.t.m.' : 'A.T.M.'; + } + }, + calendar : { + sameDay : '[Hodiaŭ je] LT', + nextDay : '[Morgaŭ je] LT', + nextWeek : 'dddd [je] LT', + lastDay : '[Hieraŭ je] LT', + lastWeek : '[pasinta] dddd [je] LT', + sameElse : 'L' + }, + relativeTime : { + future : 'post %s', + past : 'antaŭ %s', + s : 'sekundoj', + ss : '%d sekundoj', + m : 'minuto', + mm : '%d minutoj', + h : 'horo', + hh : '%d horoj', + d : 'tago',//ne 'diurno', ĉar estas uzita por proksimumo + dd : '%d tagoj', + M : 'monato', + MM : '%d monatoj', + y : 'jaro', + yy : '%d jaroj' + }, + dayOfMonthOrdinalParse: /\d{1,2}a/, + ordinal : '%da', + week : { + dow : 1, // Monday is the first day of the week. + doy : 7 // The week that contains Jan 7th is the first week of the year. } - } + }); - var add = createAdder(1, 'add'); - var subtract = createAdder(-1, 'subtract'); + return eo; - function getCalendarFormat(myMoment, now) { - var diff = myMoment.diff(now, 'days', true); - return diff < -6 ? 'sameElse' : - diff < -1 ? 'lastWeek' : - diff < 0 ? 'lastDay' : - diff < 1 ? 'sameDay' : - diff < 2 ? 'nextDay' : - diff < 7 ? 'nextWeek' : 'sameElse'; - } +}))); - function calendar$1 (time, formats) { - // We want to compare the start of today, vs this. - // Getting start-of-today depends on whether we're local/utc/offset or not. - var now = time || createLocal(), - sod = cloneWithOffset(now, this).startOf('day'), - format = hooks.calendarFormat(this, sod) || 'sameElse'; - var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]); +/***/ }), +/* 47 */ +/***/ (function(module, exports, __webpack_require__) { - return this.format(output || this.localeData().calendar(format, this, createLocal(now))); - } +//! moment.js locale configuration - function clone () { - return new Moment(this); - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - function isAfter (input, units) { - var localInput = isMoment(input) ? input : createLocal(input); - if (!(this.isValid() && localInput.isValid())) { - return false; - } - units = normalizeUnits(units) || 'millisecond'; - if (units === 'millisecond') { - return this.valueOf() > localInput.valueOf(); - } else { - return localInput.valueOf() < this.clone().startOf(units).valueOf(); - } - } - function isBefore (input, units) { - var localInput = isMoment(input) ? input : createLocal(input); - if (!(this.isValid() && localInput.isValid())) { - return false; - } - units = normalizeUnits(units) || 'millisecond'; - if (units === 'millisecond') { - return this.valueOf() < localInput.valueOf(); - } else { - return this.clone().endOf(units).valueOf() < localInput.valueOf(); - } - } + var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'), + monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'); - function isBetween (from, to, units, inclusivity) { - var localFrom = isMoment(from) ? from : createLocal(from), - localTo = isMoment(to) ? to : createLocal(to); - if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) { - return false; - } - inclusivity = inclusivity || '()'; - return (inclusivity[0] === '(' ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && - (inclusivity[1] === ')' ? this.isBefore(localTo, units) : !this.isAfter(localTo, units)); - } + var monthsParse = [/^ene/i, /^feb/i, /^mar/i, /^abr/i, /^may/i, /^jun/i, /^jul/i, /^ago/i, /^sep/i, /^oct/i, /^nov/i, /^dic/i]; + var monthsRegex = /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i; - function isSame (input, units) { - var localInput = isMoment(input) ? input : createLocal(input), - inputMs; - if (!(this.isValid() && localInput.isValid())) { - return false; - } - units = normalizeUnits(units) || 'millisecond'; - if (units === 'millisecond') { - return this.valueOf() === localInput.valueOf(); - } else { - inputMs = localInput.valueOf(); - return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf(); + var es = moment.defineLocale('es', { + months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'), + monthsShort : function (m, format) { + if (!m) { + return monthsShortDot; + } else if (/-MMM-/.test(format)) { + return monthsShort[m.month()]; + } else { + return monthsShortDot[m.month()]; + } + }, + monthsRegex : monthsRegex, + monthsShortRegex : monthsRegex, + monthsStrictRegex : /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i, + monthsShortStrictRegex : /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i, + monthsParse : monthsParse, + longMonthsParse : monthsParse, + shortMonthsParse : monthsParse, + weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), + weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), + weekdaysMin : 'do_lu_ma_mi_ju_vi_sá'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'H:mm', + LTS : 'H:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D [de] MMMM [de] YYYY', + LLL : 'D [de] MMMM [de] YYYY H:mm', + LLLL : 'dddd, D [de] MMMM [de] YYYY H:mm' + }, + calendar : { + sameDay : function () { + return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; + }, + nextDay : function () { + return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; + }, + nextWeek : function () { + return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; + }, + lastDay : function () { + return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; + }, + lastWeek : function () { + return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; + }, + sameElse : 'L' + }, + relativeTime : { + future : 'en %s', + past : 'hace %s', + s : 'unos segundos', + ss : '%d segundos', + m : 'un minuto', + mm : '%d minutos', + h : 'una hora', + hh : '%d horas', + d : 'un día', + dd : '%d días', + M : 'un mes', + MM : '%d meses', + y : 'un año', + yy : '%d años' + }, + dayOfMonthOrdinalParse : /\d{1,2}º/, + ordinal : '%dº', + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } - } + }); - function isSameOrAfter (input, units) { - return this.isSame(input, units) || this.isAfter(input, units); - } + return es; - function isSameOrBefore (input, units) { - return this.isSame(input, units) || this.isBefore(input, units); - } +}))); - function diff (input, units, asFloat) { - var that, - zoneDelta, - output; - if (!this.isValid()) { - return NaN; - } +/***/ }), +/* 48 */ +/***/ (function(module, exports, __webpack_require__) { - that = cloneWithOffset(input, this); +//! moment.js locale configuration - if (!that.isValid()) { - return NaN; - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; - units = normalizeUnits(units); + var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'), + monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'); - switch (units) { - case 'year': output = monthDiff(this, that) / 12; break; - case 'month': output = monthDiff(this, that); break; - case 'quarter': output = monthDiff(this, that) / 3; break; - case 'second': output = (this - that) / 1e3; break; // 1000 - case 'minute': output = (this - that) / 6e4; break; // 1000 * 60 - case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60 - case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst - case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst - default: output = this - that; + var monthsParse = [/^ene/i, /^feb/i, /^mar/i, /^abr/i, /^may/i, /^jun/i, /^jul/i, /^ago/i, /^sep/i, /^oct/i, /^nov/i, /^dic/i]; + var monthsRegex = /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i; + + var esDo = moment.defineLocale('es-do', { + months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'), + monthsShort : function (m, format) { + if (!m) { + return monthsShortDot; + } else if (/-MMM-/.test(format)) { + return monthsShort[m.month()]; + } else { + return monthsShortDot[m.month()]; + } + }, + monthsRegex: monthsRegex, + monthsShortRegex: monthsRegex, + monthsStrictRegex: /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i, + monthsShortStrictRegex: /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i, + monthsParse: monthsParse, + longMonthsParse: monthsParse, + shortMonthsParse: monthsParse, + weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), + weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), + weekdaysMin : 'do_lu_ma_mi_ju_vi_sá'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'h:mm A', + LTS : 'h:mm:ss A', + L : 'DD/MM/YYYY', + LL : 'D [de] MMMM [de] YYYY', + LLL : 'D [de] MMMM [de] YYYY h:mm A', + LLLL : 'dddd, D [de] MMMM [de] YYYY h:mm A' + }, + calendar : { + sameDay : function () { + return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; + }, + nextDay : function () { + return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; + }, + nextWeek : function () { + return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; + }, + lastDay : function () { + return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; + }, + lastWeek : function () { + return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; + }, + sameElse : 'L' + }, + relativeTime : { + future : 'en %s', + past : 'hace %s', + s : 'unos segundos', + ss : '%d segundos', + m : 'un minuto', + mm : '%d minutos', + h : 'una hora', + hh : '%d horas', + d : 'un día', + dd : '%d días', + M : 'un mes', + MM : '%d meses', + y : 'un año', + yy : '%d años' + }, + dayOfMonthOrdinalParse : /\d{1,2}º/, + ordinal : '%dº', + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } + }); - return asFloat ? output : absFloor(output); - } + return esDo; - function monthDiff (a, b) { - // difference in months - var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()), - // b is in (anchor - 1 month, anchor + 1 month) - anchor = a.clone().add(wholeMonthDiff, 'months'), - anchor2, adjust; +}))); - if (b - anchor < 0) { - anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); - // linear across the month - adjust = (b - anchor) / (anchor - anchor2); - } else { - anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); - // linear across the month - adjust = (b - anchor) / (anchor2 - anchor); - } - //check for negative zero, return zero if negative zero - return -(wholeMonthDiff + adjust) || 0; - } +/***/ }), +/* 49 */ +/***/ (function(module, exports, __webpack_require__) { - hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; - hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]'; +//! moment.js locale configuration - function toString () { - return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - function toISOString(keepOffset) { - if (!this.isValid()) { - return null; - } - var utc = keepOffset !== true; - var m = utc ? this.clone().utc() : this; - if (m.year() < 0 || m.year() > 9999) { - return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'); - } - if (isFunction(Date.prototype.toISOString)) { - // native implementation is ~50x faster, use it when we can - if (utc) { - return this.toDate().toISOString(); + + var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'), + monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'); + + var monthsParse = [/^ene/i, /^feb/i, /^mar/i, /^abr/i, /^may/i, /^jun/i, /^jul/i, /^ago/i, /^sep/i, /^oct/i, /^nov/i, /^dic/i]; + var monthsRegex = /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i; + + var esUs = moment.defineLocale('es-us', { + months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'), + monthsShort : function (m, format) { + if (!m) { + return monthsShortDot; + } else if (/-MMM-/.test(format)) { + return monthsShort[m.month()]; } else { - return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z')); + return monthsShortDot[m.month()]; } + }, + monthsRegex: monthsRegex, + monthsShortRegex: monthsRegex, + monthsStrictRegex: /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i, + monthsShortStrictRegex: /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i, + monthsParse: monthsParse, + longMonthsParse: monthsParse, + shortMonthsParse: monthsParse, + weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), + weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), + weekdaysMin : 'do_lu_ma_mi_ju_vi_sá'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'h:mm A', + LTS : 'h:mm:ss A', + L : 'MM/DD/YYYY', + LL : 'D [de] MMMM [de] YYYY', + LLL : 'D [de] MMMM [de] YYYY h:mm A', + LLLL : 'dddd, D [de] MMMM [de] YYYY h:mm A' + }, + calendar : { + sameDay : function () { + return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; + }, + nextDay : function () { + return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; + }, + nextWeek : function () { + return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; + }, + lastDay : function () { + return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; + }, + lastWeek : function () { + return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; + }, + sameElse : 'L' + }, + relativeTime : { + future : 'en %s', + past : 'hace %s', + s : 'unos segundos', + ss : '%d segundos', + m : 'un minuto', + mm : '%d minutos', + h : 'una hora', + hh : '%d horas', + d : 'un día', + dd : '%d días', + M : 'un mes', + MM : '%d meses', + y : 'un año', + yy : '%d años' + }, + dayOfMonthOrdinalParse : /\d{1,2}º/, + ordinal : '%dº', + week : { + dow : 0, // Sunday is the first day of the week. + doy : 6 // The week that contains Jan 6th is the first week of the year. } - return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'); - } + }); - /** - * Return a human readable representation of a moment that can - * also be evaluated to get a new moment which is the same - * - * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects - */ - function inspect () { - if (!this.isValid()) { - return 'moment.invalid(/* ' + this._i + ' */)'; - } - var func = 'moment'; - var zone = ''; - if (!this.isLocal()) { - func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone'; - zone = 'Z'; - } - var prefix = '[' + func + '("]'; - var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY'; - var datetime = '-MM-DD[T]HH:mm:ss.SSS'; - var suffix = zone + '[")]'; + return esUs; - return this.format(prefix + year + datetime + suffix); - } +}))); - function format (inputString) { - if (!inputString) { - inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat; - } - var output = formatMoment(this, inputString); - return this.localeData().postformat(output); - } - function from (time, withoutSuffix) { - if (this.isValid() && - ((isMoment(time) && time.isValid()) || - createLocal(time).isValid())) { - return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); - } else { - return this.localeData().invalidDate(); - } - } +/***/ }), +/* 50 */ +/***/ (function(module, exports, __webpack_require__) { - function fromNow (withoutSuffix) { - return this.from(createLocal(), withoutSuffix); - } +//! moment.js locale configuration - function to (time, withoutSuffix) { - if (this.isValid() && - ((isMoment(time) && time.isValid()) || - createLocal(time).isValid())) { - return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix); - } else { - return this.localeData().invalidDate(); - } - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - function toNow (withoutSuffix) { - return this.to(createLocal(), withoutSuffix); - } - // If passed a locale key, it will set the locale for this - // instance. Otherwise, it will return the locale configuration - // variables for this instance. - function locale (key) { - var newLocaleData; - - if (key === undefined) { - return this._locale._abbr; - } else { - newLocaleData = getLocale(key); - if (newLocaleData != null) { - this._locale = newLocaleData; - } - return this; + function processRelativeTime(number, withoutSuffix, key, isFuture) { + var format = { + 's' : ['mõne sekundi', 'mõni sekund', 'paar sekundit'], + 'ss': [number + 'sekundi', number + 'sekundit'], + 'm' : ['ühe minuti', 'üks minut'], + 'mm': [number + ' minuti', number + ' minutit'], + 'h' : ['ühe tunni', 'tund aega', 'üks tund'], + 'hh': [number + ' tunni', number + ' tundi'], + 'd' : ['ühe päeva', 'üks päev'], + 'M' : ['kuu aja', 'kuu aega', 'üks kuu'], + 'MM': [number + ' kuu', number + ' kuud'], + 'y' : ['ühe aasta', 'aasta', 'üks aasta'], + 'yy': [number + ' aasta', number + ' aastat'] + }; + if (withoutSuffix) { + return format[key][2] ? format[key][2] : format[key][1]; } + return isFuture ? format[key][0] : format[key][1]; } - var lang = deprecate( - 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', - function (key) { - if (key === undefined) { - return this.localeData(); - } else { - return this.locale(key); - } + var et = moment.defineLocale('et', { + months : 'jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember'.split('_'), + monthsShort : 'jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets'.split('_'), + weekdays : 'pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev'.split('_'), + weekdaysShort : 'P_E_T_K_N_R_L'.split('_'), + weekdaysMin : 'P_E_T_K_N_R_L'.split('_'), + longDateFormat : { + LT : 'H:mm', + LTS : 'H:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D. MMMM YYYY', + LLL : 'D. MMMM YYYY H:mm', + LLLL : 'dddd, D. MMMM YYYY H:mm' + }, + calendar : { + sameDay : '[Täna,] LT', + nextDay : '[Homme,] LT', + nextWeek : '[Järgmine] dddd LT', + lastDay : '[Eile,] LT', + lastWeek : '[Eelmine] dddd LT', + sameElse : 'L' + }, + relativeTime : { + future : '%s pärast', + past : '%s tagasi', + s : processRelativeTime, + ss : processRelativeTime, + m : processRelativeTime, + mm : processRelativeTime, + h : processRelativeTime, + hh : processRelativeTime, + d : processRelativeTime, + dd : '%d päeva', + M : processRelativeTime, + MM : processRelativeTime, + y : processRelativeTime, + yy : processRelativeTime + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } - ); + }); - function localeData () { - return this._locale; - } + return et; - var MS_PER_SECOND = 1000; - var MS_PER_MINUTE = 60 * MS_PER_SECOND; - var MS_PER_HOUR = 60 * MS_PER_MINUTE; - var MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR; +}))); - // actual modulo - handles negative numbers (for dates before 1970): - function mod$1(dividend, divisor) { - return (dividend % divisor + divisor) % divisor; - } - function localStartOfDate(y, m, d) { - // the date constructor remaps years 0-99 to 1900-1999 - if (y < 100 && y >= 0) { - // preserve leap years using a full 400 year cycle, then reset - return new Date(y + 400, m, d) - MS_PER_400_YEARS; - } else { - return new Date(y, m, d).valueOf(); - } - } +/***/ }), +/* 51 */ +/***/ (function(module, exports, __webpack_require__) { - function utcStartOfDate(y, m, d) { - // Date.UTC remaps years 0-99 to 1900-1999 - if (y < 100 && y >= 0) { - // preserve leap years using a full 400 year cycle, then reset - return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS; - } else { - return Date.UTC(y, m, d); - } - } +//! moment.js locale configuration - function startOf (units) { - var time; - units = normalizeUnits(units); - if (units === undefined || units === 'millisecond' || !this.isValid()) { - return this; - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; - switch (units) { - case 'year': - time = startOfDate(this.year(), 0, 1); - break; - case 'quarter': - time = startOfDate(this.year(), this.month() - this.month() % 3, 1); - break; - case 'month': - time = startOfDate(this.year(), this.month(), 1); - break; - case 'week': - time = startOfDate(this.year(), this.month(), this.date() - this.weekday()); - break; - case 'isoWeek': - time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1)); - break; - case 'day': - case 'date': - time = startOfDate(this.year(), this.month(), this.date()); - break; - case 'hour': - time = this._d.valueOf(); - time -= mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR); - break; - case 'minute': - time = this._d.valueOf(); - time -= mod$1(time, MS_PER_MINUTE); - break; - case 'second': - time = this._d.valueOf(); - time -= mod$1(time, MS_PER_SECOND); - break; + var eu = moment.defineLocale('eu', { + months : 'urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua'.split('_'), + monthsShort : 'urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.'.split('_'), + monthsParseExact : true, + weekdays : 'igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata'.split('_'), + weekdaysShort : 'ig._al._ar._az._og._ol._lr.'.split('_'), + weekdaysMin : 'ig_al_ar_az_og_ol_lr'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'YYYY-MM-DD', + LL : 'YYYY[ko] MMMM[ren] D[a]', + LLL : 'YYYY[ko] MMMM[ren] D[a] HH:mm', + LLLL : 'dddd, YYYY[ko] MMMM[ren] D[a] HH:mm', + l : 'YYYY-M-D', + ll : 'YYYY[ko] MMM D[a]', + lll : 'YYYY[ko] MMM D[a] HH:mm', + llll : 'ddd, YYYY[ko] MMM D[a] HH:mm' + }, + calendar : { + sameDay : '[gaur] LT[etan]', + nextDay : '[bihar] LT[etan]', + nextWeek : 'dddd LT[etan]', + lastDay : '[atzo] LT[etan]', + lastWeek : '[aurreko] dddd LT[etan]', + sameElse : 'L' + }, + relativeTime : { + future : '%s barru', + past : 'duela %s', + s : 'segundo batzuk', + ss : '%d segundo', + m : 'minutu bat', + mm : '%d minutu', + h : 'ordu bat', + hh : '%d ordu', + d : 'egun bat', + dd : '%d egun', + M : 'hilabete bat', + MM : '%d hilabete', + y : 'urte bat', + yy : '%d urte' + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', + week : { + dow : 1, // Monday is the first day of the week. + doy : 7 // The week that contains Jan 7th is the first week of the year. } + }); - this._d.setTime(time); - hooks.updateOffset(this, true); - return this; - } + return eu; - function endOf (units) { - var time; - units = normalizeUnits(units); - if (units === undefined || units === 'millisecond' || !this.isValid()) { - return this; +}))); + + +/***/ }), +/* 52 */ +/***/ (function(module, exports, __webpack_require__) { + +//! moment.js locale configuration + +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; + + + var symbolMap = { + '1': '۱', + '2': '۲', + '3': '۳', + '4': '۴', + '5': '۵', + '6': '۶', + '7': '۷', + '8': '۸', + '9': '۹', + '0': '۰' + }, numberMap = { + '۱': '1', + '۲': '2', + '۳': '3', + '۴': '4', + '۵': '5', + '۶': '6', + '۷': '7', + '۸': '8', + '۹': '9', + '۰': '0' + }; + + var fa = moment.defineLocale('fa', { + months : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), + monthsShort : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), + weekdays : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), + weekdaysShort : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), + weekdaysMin : 'ی_د_س_چ_پ_ج_ش'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd, D MMMM YYYY HH:mm' + }, + meridiemParse: /قبل از ظهر|بعد از ظهر/, + isPM: function (input) { + return /بعد از ظهر/.test(input); + }, + meridiem : function (hour, minute, isLower) { + if (hour < 12) { + return 'قبل از ظهر'; + } else { + return 'بعد از ظهر'; + } + }, + calendar : { + sameDay : '[امروز ساعت] LT', + nextDay : '[فردا ساعت] LT', + nextWeek : 'dddd [ساعت] LT', + lastDay : '[دیروز ساعت] LT', + lastWeek : 'dddd [پیش] [ساعت] LT', + sameElse : 'L' + }, + relativeTime : { + future : 'در %s', + past : '%s پیش', + s : 'چند ثانیه', + ss : 'ثانیه d%', + m : 'یک دقیقه', + mm : '%d دقیقه', + h : 'یک ساعت', + hh : '%d ساعت', + d : 'یک روز', + dd : '%d روز', + M : 'یک ماه', + MM : '%d ماه', + y : 'یک سال', + yy : '%d سال' + }, + preparse: function (string) { + return string.replace(/[۰-۹]/g, function (match) { + return numberMap[match]; + }).replace(/،/g, ','); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }).replace(/,/g, '،'); + }, + dayOfMonthOrdinalParse: /\d{1,2}م/, + ordinal : '%dم', + week : { + dow : 6, // Saturday is the first day of the week. + doy : 12 // The week that contains Jan 12th is the first week of the year. } + }); - var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; + return fa; - switch (units) { - case 'year': - time = startOfDate(this.year() + 1, 0, 1) - 1; - break; - case 'quarter': - time = startOfDate(this.year(), this.month() - this.month() % 3 + 3, 1) - 1; - break; - case 'month': - time = startOfDate(this.year(), this.month() + 1, 1) - 1; - break; - case 'week': - time = startOfDate(this.year(), this.month(), this.date() - this.weekday() + 7) - 1; - break; - case 'isoWeek': - time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7) - 1; +}))); + + +/***/ }), +/* 53 */ +/***/ (function(module, exports, __webpack_require__) { + +//! moment.js locale configuration + +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; + + + var numbersPast = 'nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän'.split(' '), + numbersFuture = [ + 'nolla', 'yhden', 'kahden', 'kolmen', 'neljän', 'viiden', 'kuuden', + numbersPast[7], numbersPast[8], numbersPast[9] + ]; + function translate(number, withoutSuffix, key, isFuture) { + var result = ''; + switch (key) { + case 's': + return isFuture ? 'muutaman sekunnin' : 'muutama sekunti'; + case 'ss': + return isFuture ? 'sekunnin' : 'sekuntia'; + case 'm': + return isFuture ? 'minuutin' : 'minuutti'; + case 'mm': + result = isFuture ? 'minuutin' : 'minuuttia'; break; - case 'day': - case 'date': - time = startOfDate(this.year(), this.month(), this.date() + 1) - 1; + case 'h': + return isFuture ? 'tunnin' : 'tunti'; + case 'hh': + result = isFuture ? 'tunnin' : 'tuntia'; break; - case 'hour': - time = this._d.valueOf(); - time += MS_PER_HOUR - mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR) - 1; + case 'd': + return isFuture ? 'päivän' : 'päivä'; + case 'dd': + result = isFuture ? 'päivän' : 'päivää'; break; - case 'minute': - time = this._d.valueOf(); - time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1; + case 'M': + return isFuture ? 'kuukauden' : 'kuukausi'; + case 'MM': + result = isFuture ? 'kuukauden' : 'kuukautta'; break; - case 'second': - time = this._d.valueOf(); - time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1; + case 'y': + return isFuture ? 'vuoden' : 'vuosi'; + case 'yy': + result = isFuture ? 'vuoden' : 'vuotta'; break; } - - this._d.setTime(time); - hooks.updateOffset(this, true); - return this; - } - - function valueOf () { - return this._d.valueOf() - ((this._offset || 0) * 60000); + result = verbalNumber(number, isFuture) + ' ' + result; + return result; } - - function unix () { - return Math.floor(this.valueOf() / 1000); + function verbalNumber(number, isFuture) { + return number < 10 ? (isFuture ? numbersFuture[number] : numbersPast[number]) : number; } - function toDate () { - return new Date(this.valueOf()); - } + var fi = moment.defineLocale('fi', { + months : 'tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu'.split('_'), + monthsShort : 'tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu'.split('_'), + weekdays : 'sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai'.split('_'), + weekdaysShort : 'su_ma_ti_ke_to_pe_la'.split('_'), + weekdaysMin : 'su_ma_ti_ke_to_pe_la'.split('_'), + longDateFormat : { + LT : 'HH.mm', + LTS : 'HH.mm.ss', + L : 'DD.MM.YYYY', + LL : 'Do MMMM[ta] YYYY', + LLL : 'Do MMMM[ta] YYYY, [klo] HH.mm', + LLLL : 'dddd, Do MMMM[ta] YYYY, [klo] HH.mm', + l : 'D.M.YYYY', + ll : 'Do MMM YYYY', + lll : 'Do MMM YYYY, [klo] HH.mm', + llll : 'ddd, Do MMM YYYY, [klo] HH.mm' + }, + calendar : { + sameDay : '[tänään] [klo] LT', + nextDay : '[huomenna] [klo] LT', + nextWeek : 'dddd [klo] LT', + lastDay : '[eilen] [klo] LT', + lastWeek : '[viime] dddd[na] [klo] LT', + sameElse : 'L' + }, + relativeTime : { + future : '%s päästä', + past : '%s sitten', + s : translate, + ss : translate, + m : translate, + mm : translate, + h : translate, + hh : translate, + d : translate, + dd : translate, + M : translate, + MM : translate, + y : translate, + yy : translate + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. + } + }); - function toArray () { - var m = this; - return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()]; - } + return fi; - function toObject () { - var m = this; - return { - years: m.year(), - months: m.month(), - date: m.date(), - hours: m.hours(), - minutes: m.minutes(), - seconds: m.seconds(), - milliseconds: m.milliseconds() - }; - } +}))); - function toJSON () { - // new Date(NaN).toJSON() === null - return this.isValid() ? this.toISOString() : null; - } - function isValid$2 () { - return isValid(this); - } +/***/ }), +/* 54 */ +/***/ (function(module, exports, __webpack_require__) { - function parsingFlags () { - return extend({}, getParsingFlags(this)); - } +//! moment.js locale configuration - function invalidAt () { - return getParsingFlags(this).overflow; - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - function creationData() { - return { - input: this._i, - format: this._f, - locale: this._locale, - isUTC: this._isUTC, - strict: this._strict - }; - } - // FORMATTING - - addFormatToken(0, ['gg', 2], 0, function () { - return this.weekYear() % 100; - }); - - addFormatToken(0, ['GG', 2], 0, function () { - return this.isoWeekYear() % 100; + var fo = moment.defineLocale('fo', { + months : 'januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember'.split('_'), + monthsShort : 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'), + weekdays : 'sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur'.split('_'), + weekdaysShort : 'sun_mán_týs_mik_hós_frí_ley'.split('_'), + weekdaysMin : 'su_má_tý_mi_hó_fr_le'.split('_'), + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd D. MMMM, YYYY HH:mm' + }, + calendar : { + sameDay : '[Í dag kl.] LT', + nextDay : '[Í morgin kl.] LT', + nextWeek : 'dddd [kl.] LT', + lastDay : '[Í gjár kl.] LT', + lastWeek : '[síðstu] dddd [kl] LT', + sameElse : 'L' + }, + relativeTime : { + future : 'um %s', + past : '%s síðani', + s : 'fá sekund', + ss : '%d sekundir', + m : 'ein minuttur', + mm : '%d minuttir', + h : 'ein tími', + hh : '%d tímar', + d : 'ein dagur', + dd : '%d dagar', + M : 'ein mánaður', + MM : '%d mánaðir', + y : 'eitt ár', + yy : '%d ár' + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. + } }); - function addWeekYearFormatToken (token, getter) { - addFormatToken(0, [token, token.length], 0, getter); - } - - addWeekYearFormatToken('gggg', 'weekYear'); - addWeekYearFormatToken('ggggg', 'weekYear'); - addWeekYearFormatToken('GGGG', 'isoWeekYear'); - addWeekYearFormatToken('GGGGG', 'isoWeekYear'); - - // ALIASES - - addUnitAlias('weekYear', 'gg'); - addUnitAlias('isoWeekYear', 'GG'); - - // PRIORITY - - addUnitPriority('weekYear', 1); - addUnitPriority('isoWeekYear', 1); - - - // PARSING + return fo; - addRegexToken('G', matchSigned); - addRegexToken('g', matchSigned); - addRegexToken('GG', match1to2, match2); - addRegexToken('gg', match1to2, match2); - addRegexToken('GGGG', match1to4, match4); - addRegexToken('gggg', match1to4, match4); - addRegexToken('GGGGG', match1to6, match6); - addRegexToken('ggggg', match1to6, match6); +}))); - addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) { - week[token.substr(0, 2)] = toInt(input); - }); - addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { - week[token] = hooks.parseTwoDigitYear(input); - }); +/***/ }), +/* 55 */ +/***/ (function(module, exports, __webpack_require__) { - // MOMENTS +//! moment.js locale configuration - function getSetWeekYear (input) { - return getSetWeekYearHelper.call(this, - input, - this.week(), - this.weekday(), - this.localeData()._week.dow, - this.localeData()._week.doy); - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - function getSetISOWeekYear (input) { - return getSetWeekYearHelper.call(this, - input, this.isoWeek(), this.isoWeekday(), 1, 4); - } - function getISOWeeksInYear () { - return weeksInYear(this.year(), 1, 4); - } + var fr = moment.defineLocale('fr', { + months : 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'), + monthsShort : 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'), + monthsParseExact : true, + weekdays : 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), + weekdaysShort : 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), + weekdaysMin : 'di_lu_ma_me_je_ve_sa'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd D MMMM YYYY HH:mm' + }, + calendar : { + sameDay : '[Aujourd’hui à] LT', + nextDay : '[Demain à] LT', + nextWeek : 'dddd [à] LT', + lastDay : '[Hier à] LT', + lastWeek : 'dddd [dernier à] LT', + sameElse : 'L' + }, + relativeTime : { + future : 'dans %s', + past : 'il y a %s', + s : 'quelques secondes', + ss : '%d secondes', + m : 'une minute', + mm : '%d minutes', + h : 'une heure', + hh : '%d heures', + d : 'un jour', + dd : '%d jours', + M : 'un mois', + MM : '%d mois', + y : 'un an', + yy : '%d ans' + }, + dayOfMonthOrdinalParse: /\d{1,2}(er|)/, + ordinal : function (number, period) { + switch (period) { + // TODO: Return 'e' when day of month > 1. Move this case inside + // block for masculine words below. + // See https://github.com/moment/moment/issues/3375 + case 'D': + return number + (number === 1 ? 'er' : ''); - function getWeeksInYear () { - var weekInfo = this.localeData()._week; - return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); - } + // Words with masculine grammatical gender: mois, trimestre, jour + default: + case 'M': + case 'Q': + case 'DDD': + case 'd': + return number + (number === 1 ? 'er' : 'e'); - function getSetWeekYearHelper(input, week, weekday, dow, doy) { - var weeksTarget; - if (input == null) { - return weekOfYear(this, dow, doy).year; - } else { - weeksTarget = weeksInYear(input, dow, doy); - if (week > weeksTarget) { - week = weeksTarget; + // Words with feminine grammatical gender: semaine + case 'w': + case 'W': + return number + (number === 1 ? 're' : 'e'); } - return setWeekAll.call(this, input, week, weekday, dow, doy); + }, + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } - } - - function setWeekAll(weekYear, week, weekday, dow, doy) { - var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), - date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); - - this.year(date.getUTCFullYear()); - this.month(date.getUTCMonth()); - this.date(date.getUTCDate()); - return this; - } - - // FORMATTING - - addFormatToken('Q', 0, 'Qo', 'quarter'); - - // ALIASES - - addUnitAlias('quarter', 'Q'); - - // PRIORITY - - addUnitPriority('quarter', 7); - - // PARSING - - addRegexToken('Q', match1); - addParseToken('Q', function (input, array) { - array[MONTH] = (toInt(input) - 1) * 3; }); - // MOMENTS - - function getSetQuarter (input) { - return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); - } + return fr; - // FORMATTING +}))); - addFormatToken('D', ['DD', 2], 'Do', 'date'); - // ALIASES +/***/ }), +/* 56 */ +/***/ (function(module, exports, __webpack_require__) { - addUnitAlias('date', 'D'); +//! moment.js locale configuration - // PRIORITY - addUnitPriority('date', 9); +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - // PARSING - addRegexToken('D', match1to2); - addRegexToken('DD', match1to2, match2); - addRegexToken('Do', function (isStrict, locale) { - // TODO: Remove "ordinalParse" fallback in next major release. - return isStrict ? - (locale._dayOfMonthOrdinalParse || locale._ordinalParse) : - locale._dayOfMonthOrdinalParseLenient; - }); + var frCa = moment.defineLocale('fr-ca', { + months : 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'), + monthsShort : 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'), + monthsParseExact : true, + weekdays : 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), + weekdaysShort : 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), + weekdaysMin : 'di_lu_ma_me_je_ve_sa'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'YYYY-MM-DD', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd D MMMM YYYY HH:mm' + }, + calendar : { + sameDay : '[Aujourd’hui à] LT', + nextDay : '[Demain à] LT', + nextWeek : 'dddd [à] LT', + lastDay : '[Hier à] LT', + lastWeek : 'dddd [dernier à] LT', + sameElse : 'L' + }, + relativeTime : { + future : 'dans %s', + past : 'il y a %s', + s : 'quelques secondes', + ss : '%d secondes', + m : 'une minute', + mm : '%d minutes', + h : 'une heure', + hh : '%d heures', + d : 'un jour', + dd : '%d jours', + M : 'un mois', + MM : '%d mois', + y : 'un an', + yy : '%d ans' + }, + dayOfMonthOrdinalParse: /\d{1,2}(er|e)/, + ordinal : function (number, period) { + switch (period) { + // Words with masculine grammatical gender: mois, trimestre, jour + default: + case 'M': + case 'Q': + case 'D': + case 'DDD': + case 'd': + return number + (number === 1 ? 'er' : 'e'); - addParseToken(['D', 'DD'], DATE); - addParseToken('Do', function (input, array) { - array[DATE] = toInt(input.match(match1to2)[0]); + // Words with feminine grammatical gender: semaine + case 'w': + case 'W': + return number + (number === 1 ? 're' : 'e'); + } + } }); - // MOMENTS + return frCa; - var getSetDayOfMonth = makeGetSet('Date', true); +}))); - // FORMATTING - addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); +/***/ }), +/* 57 */ +/***/ (function(module, exports, __webpack_require__) { - // ALIASES +//! moment.js locale configuration - addUnitAlias('dayOfYear', 'DDD'); +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - // PRIORITY - addUnitPriority('dayOfYear', 4); - // PARSING + var frCh = moment.defineLocale('fr-ch', { + months : 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'), + monthsShort : 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'), + monthsParseExact : true, + weekdays : 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), + weekdaysShort : 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), + weekdaysMin : 'di_lu_ma_me_je_ve_sa'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd D MMMM YYYY HH:mm' + }, + calendar : { + sameDay : '[Aujourd’hui à] LT', + nextDay : '[Demain à] LT', + nextWeek : 'dddd [à] LT', + lastDay : '[Hier à] LT', + lastWeek : 'dddd [dernier à] LT', + sameElse : 'L' + }, + relativeTime : { + future : 'dans %s', + past : 'il y a %s', + s : 'quelques secondes', + ss : '%d secondes', + m : 'une minute', + mm : '%d minutes', + h : 'une heure', + hh : '%d heures', + d : 'un jour', + dd : '%d jours', + M : 'un mois', + MM : '%d mois', + y : 'un an', + yy : '%d ans' + }, + dayOfMonthOrdinalParse: /\d{1,2}(er|e)/, + ordinal : function (number, period) { + switch (period) { + // Words with masculine grammatical gender: mois, trimestre, jour + default: + case 'M': + case 'Q': + case 'D': + case 'DDD': + case 'd': + return number + (number === 1 ? 'er' : 'e'); - addRegexToken('DDD', match1to3); - addRegexToken('DDDD', match3); - addParseToken(['DDD', 'DDDD'], function (input, array, config) { - config._dayOfYear = toInt(input); + // Words with feminine grammatical gender: semaine + case 'w': + case 'W': + return number + (number === 1 ? 're' : 'e'); + } + }, + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. + } }); - // HELPERS - - // MOMENTS - - function getSetDayOfYear (input) { - var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1; - return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); - } - - // FORMATTING + return frCh; - addFormatToken('m', ['mm', 2], 0, 'minute'); +}))); - // ALIASES - addUnitAlias('minute', 'm'); +/***/ }), +/* 58 */ +/***/ (function(module, exports, __webpack_require__) { - // PRIORITY +//! moment.js locale configuration - addUnitPriority('minute', 14); +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - // PARSING - addRegexToken('m', match1to2); - addRegexToken('mm', match1to2, match2); - addParseToken(['m', 'mm'], MINUTE); + var monthsShortWithDots = 'jan._feb._mrt._apr._mai_jun._jul._aug._sep._okt._nov._des.'.split('_'), + monthsShortWithoutDots = 'jan_feb_mrt_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'); - // MOMENTS + var fy = moment.defineLocale('fy', { + months : 'jannewaris_febrewaris_maart_april_maaie_juny_july_augustus_septimber_oktober_novimber_desimber'.split('_'), + monthsShort : function (m, format) { + if (!m) { + return monthsShortWithDots; + } else if (/-MMM-/.test(format)) { + return monthsShortWithoutDots[m.month()]; + } else { + return monthsShortWithDots[m.month()]; + } + }, + monthsParseExact : true, + weekdays : 'snein_moandei_tiisdei_woansdei_tongersdei_freed_sneon'.split('_'), + weekdaysShort : 'si._mo._ti._wo._to._fr._so.'.split('_'), + weekdaysMin : 'Si_Mo_Ti_Wo_To_Fr_So'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD-MM-YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd D MMMM YYYY HH:mm' + }, + calendar : { + sameDay: '[hjoed om] LT', + nextDay: '[moarn om] LT', + nextWeek: 'dddd [om] LT', + lastDay: '[juster om] LT', + lastWeek: '[ôfrûne] dddd [om] LT', + sameElse: 'L' + }, + relativeTime : { + future : 'oer %s', + past : '%s lyn', + s : 'in pear sekonden', + ss : '%d sekonden', + m : 'ien minút', + mm : '%d minuten', + h : 'ien oere', + hh : '%d oeren', + d : 'ien dei', + dd : '%d dagen', + M : 'ien moanne', + MM : '%d moannen', + y : 'ien jier', + yy : '%d jierren' + }, + dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, + ordinal : function (number) { + return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); + }, + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. + } + }); - var getSetMinute = makeGetSet('Minutes', false); + return fy; - // FORMATTING +}))); - addFormatToken('s', ['ss', 2], 0, 'second'); - // ALIASES +/***/ }), +/* 59 */ +/***/ (function(module, exports, __webpack_require__) { - addUnitAlias('second', 's'); +//! moment.js locale configuration - // PRIORITY +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - addUnitPriority('second', 15); - // PARSING - addRegexToken('s', match1to2); - addRegexToken('ss', match1to2, match2); - addParseToken(['s', 'ss'], SECOND); + var months = [ + 'Eanáir', 'Feabhra', 'Márta', 'Aibreán', 'Bealtaine', 'Méitheamh', 'Iúil', 'Lúnasa', 'Meán Fómhair', 'Deaireadh Fómhair', 'Samhain', 'Nollaig' + ]; - // MOMENTS + var monthsShort = ['Eaná', 'Feab', 'Márt', 'Aibr', 'Beal', 'Méit', 'Iúil', 'Lúna', 'Meán', 'Deai', 'Samh', 'Noll']; - var getSetSecond = makeGetSet('Seconds', false); + var weekdays = ['Dé Domhnaigh', 'Dé Luain', 'Dé Máirt', 'Dé Céadaoin', 'Déardaoin', 'Dé hAoine', 'Dé Satharn']; - // FORMATTING + var weekdaysShort = ['Dom', 'Lua', 'Mái', 'Céa', 'Déa', 'hAo', 'Sat']; - addFormatToken('S', 0, 0, function () { - return ~~(this.millisecond() / 100); - }); + var weekdaysMin = ['Do', 'Lu', 'Má', 'Ce', 'Dé', 'hA', 'Sa']; - addFormatToken(0, ['SS', 2], 0, function () { - return ~~(this.millisecond() / 10); + var ga = moment.defineLocale('ga', { + months: months, + monthsShort: monthsShort, + monthsParseExact: true, + weekdays: weekdays, + weekdaysShort: weekdaysShort, + weekdaysMin: weekdaysMin, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm' + }, + calendar: { + sameDay: '[Inniu ag] LT', + nextDay: '[Amárach ag] LT', + nextWeek: 'dddd [ag] LT', + lastDay: '[Inné aig] LT', + lastWeek: 'dddd [seo caite] [ag] LT', + sameElse: 'L' + }, + relativeTime: { + future: 'i %s', + past: '%s ó shin', + s: 'cúpla soicind', + ss: '%d soicind', + m: 'nóiméad', + mm: '%d nóiméad', + h: 'uair an chloig', + hh: '%d uair an chloig', + d: 'lá', + dd: '%d lá', + M: 'mí', + MM: '%d mí', + y: 'bliain', + yy: '%d bliain' + }, + dayOfMonthOrdinalParse: /\d{1,2}(d|na|mh)/, + ordinal: function (number) { + var output = number === 1 ? 'd' : number % 10 === 2 ? 'na' : 'mh'; + return number + output; + }, + week: { + dow: 1, // Monday is the first day of the week. + doy: 4 // The week that contains Jan 4th is the first week of the year. + } }); - addFormatToken(0, ['SSS', 3], 0, 'millisecond'); - addFormatToken(0, ['SSSS', 4], 0, function () { - return this.millisecond() * 10; - }); - addFormatToken(0, ['SSSSS', 5], 0, function () { - return this.millisecond() * 100; - }); - addFormatToken(0, ['SSSSSS', 6], 0, function () { - return this.millisecond() * 1000; - }); - addFormatToken(0, ['SSSSSSS', 7], 0, function () { - return this.millisecond() * 10000; - }); - addFormatToken(0, ['SSSSSSSS', 8], 0, function () { - return this.millisecond() * 100000; - }); - addFormatToken(0, ['SSSSSSSSS', 9], 0, function () { - return this.millisecond() * 1000000; - }); + return ga; +}))); - // ALIASES - addUnitAlias('millisecond', 'ms'); +/***/ }), +/* 60 */ +/***/ (function(module, exports, __webpack_require__) { - // PRIORITY +//! moment.js locale configuration - addUnitPriority('millisecond', 16); +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - // PARSING - addRegexToken('S', match1to3, match1); - addRegexToken('SS', match1to3, match2); - addRegexToken('SSS', match1to3, match3); + var months = [ + 'Am Faoilleach', 'An Gearran', 'Am Màrt', 'An Giblean', 'An Cèitean', 'An t-Ògmhios', 'An t-Iuchar', 'An Lùnastal', 'An t-Sultain', 'An Dàmhair', 'An t-Samhain', 'An Dùbhlachd' + ]; - var token; - for (token = 'SSSS'; token.length <= 9; token += 'S') { - addRegexToken(token, matchUnsigned); - } + var monthsShort = ['Faoi', 'Gear', 'Màrt', 'Gibl', 'Cèit', 'Ògmh', 'Iuch', 'Lùn', 'Sult', 'Dàmh', 'Samh', 'Dùbh']; - function parseMs(input, array) { - array[MILLISECOND] = toInt(('0.' + input) * 1000); - } + var weekdays = ['Didòmhnaich', 'Diluain', 'Dimàirt', 'Diciadain', 'Diardaoin', 'Dihaoine', 'Disathairne']; - for (token = 'S'; token.length <= 9; token += 'S') { - addParseToken(token, parseMs); - } - // MOMENTS + var weekdaysShort = ['Did', 'Dil', 'Dim', 'Dic', 'Dia', 'Dih', 'Dis']; - var getSetMillisecond = makeGetSet('Milliseconds', false); + var weekdaysMin = ['Dò', 'Lu', 'Mà', 'Ci', 'Ar', 'Ha', 'Sa']; - // FORMATTING + var gd = moment.defineLocale('gd', { + months : months, + monthsShort : monthsShort, + monthsParseExact : true, + weekdays : weekdays, + weekdaysShort : weekdaysShort, + weekdaysMin : weekdaysMin, + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd, D MMMM YYYY HH:mm' + }, + calendar : { + sameDay : '[An-diugh aig] LT', + nextDay : '[A-màireach aig] LT', + nextWeek : 'dddd [aig] LT', + lastDay : '[An-dè aig] LT', + lastWeek : 'dddd [seo chaidh] [aig] LT', + sameElse : 'L' + }, + relativeTime : { + future : 'ann an %s', + past : 'bho chionn %s', + s : 'beagan diogan', + ss : '%d diogan', + m : 'mionaid', + mm : '%d mionaidean', + h : 'uair', + hh : '%d uairean', + d : 'latha', + dd : '%d latha', + M : 'mìos', + MM : '%d mìosan', + y : 'bliadhna', + yy : '%d bliadhna' + }, + dayOfMonthOrdinalParse : /\d{1,2}(d|na|mh)/, + ordinal : function (number) { + var output = number === 1 ? 'd' : number % 10 === 2 ? 'na' : 'mh'; + return number + output; + }, + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. + } + }); - addFormatToken('z', 0, 0, 'zoneAbbr'); - addFormatToken('zz', 0, 0, 'zoneName'); + return gd; - // MOMENTS +}))); - function getZoneAbbr () { - return this._isUTC ? 'UTC' : ''; - } - function getZoneName () { - return this._isUTC ? 'Coordinated Universal Time' : ''; - } +/***/ }), +/* 61 */ +/***/ (function(module, exports, __webpack_require__) { - var proto = Moment.prototype; +//! moment.js locale configuration - proto.add = add; - proto.calendar = calendar$1; - proto.clone = clone; - proto.diff = diff; - proto.endOf = endOf; - proto.format = format; - proto.from = from; - proto.fromNow = fromNow; - proto.to = to; - proto.toNow = toNow; - proto.get = stringGet; - proto.invalidAt = invalidAt; - proto.isAfter = isAfter; - proto.isBefore = isBefore; - proto.isBetween = isBetween; - proto.isSame = isSame; - proto.isSameOrAfter = isSameOrAfter; - proto.isSameOrBefore = isSameOrBefore; - proto.isValid = isValid$2; - proto.lang = lang; - proto.locale = locale; - proto.localeData = localeData; - proto.max = prototypeMax; - proto.min = prototypeMin; - proto.parsingFlags = parsingFlags; - proto.set = stringSet; - proto.startOf = startOf; - proto.subtract = subtract; - proto.toArray = toArray; - proto.toObject = toObject; - proto.toDate = toDate; - proto.toISOString = toISOString; - proto.inspect = inspect; - proto.toJSON = toJSON; - proto.toString = toString; - proto.unix = unix; - proto.valueOf = valueOf; - proto.creationData = creationData; - proto.year = getSetYear; - proto.isLeapYear = getIsLeapYear; - proto.weekYear = getSetWeekYear; - proto.isoWeekYear = getSetISOWeekYear; - proto.quarter = proto.quarters = getSetQuarter; - proto.month = getSetMonth; - proto.daysInMonth = getDaysInMonth; - proto.week = proto.weeks = getSetWeek; - proto.isoWeek = proto.isoWeeks = getSetISOWeek; - proto.weeksInYear = getWeeksInYear; - proto.isoWeeksInYear = getISOWeeksInYear; - proto.date = getSetDayOfMonth; - proto.day = proto.days = getSetDayOfWeek; - proto.weekday = getSetLocaleDayOfWeek; - proto.isoWeekday = getSetISODayOfWeek; - proto.dayOfYear = getSetDayOfYear; - proto.hour = proto.hours = getSetHour; - proto.minute = proto.minutes = getSetMinute; - proto.second = proto.seconds = getSetSecond; - proto.millisecond = proto.milliseconds = getSetMillisecond; - proto.utcOffset = getSetOffset; - proto.utc = setOffsetToUTC; - proto.local = setOffsetToLocal; - proto.parseZone = setOffsetToParsedOffset; - proto.hasAlignedHourOffset = hasAlignedHourOffset; - proto.isDST = isDaylightSavingTime; - proto.isLocal = isLocal; - proto.isUtcOffset = isUtcOffset; - proto.isUtc = isUtc; - proto.isUTC = isUtc; - proto.zoneAbbr = getZoneAbbr; - proto.zoneName = getZoneName; - proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth); - proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth); - proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear); - proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone); - proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted); +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - function createUnix (input) { - return createLocal(input * 1000); - } - function createInZone () { - return createLocal.apply(null, arguments).parseZone(); - } + var gl = moment.defineLocale('gl', { + months : 'xaneiro_febreiro_marzo_abril_maio_xuño_xullo_agosto_setembro_outubro_novembro_decembro'.split('_'), + monthsShort : 'xan._feb._mar._abr._mai._xuñ._xul._ago._set._out._nov._dec.'.split('_'), + monthsParseExact: true, + weekdays : 'domingo_luns_martes_mércores_xoves_venres_sábado'.split('_'), + weekdaysShort : 'dom._lun._mar._mér._xov._ven._sáb.'.split('_'), + weekdaysMin : 'do_lu_ma_mé_xo_ve_sá'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'H:mm', + LTS : 'H:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D [de] MMMM [de] YYYY', + LLL : 'D [de] MMMM [de] YYYY H:mm', + LLLL : 'dddd, D [de] MMMM [de] YYYY H:mm' + }, + calendar : { + sameDay : function () { + return '[hoxe ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; + }, + nextDay : function () { + return '[mañá ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; + }, + nextWeek : function () { + return 'dddd [' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; + }, + lastDay : function () { + return '[onte ' + ((this.hours() !== 1) ? 'á' : 'a') + '] LT'; + }, + lastWeek : function () { + return '[o] dddd [pasado ' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; + }, + sameElse : 'L' + }, + relativeTime : { + future : function (str) { + if (str.indexOf('un') === 0) { + return 'n' + str; + } + return 'en ' + str; + }, + past : 'hai %s', + s : 'uns segundos', + ss : '%d segundos', + m : 'un minuto', + mm : '%d minutos', + h : 'unha hora', + hh : '%d horas', + d : 'un día', + dd : '%d días', + M : 'un mes', + MM : '%d meses', + y : 'un ano', + yy : '%d anos' + }, + dayOfMonthOrdinalParse : /\d{1,2}º/, + ordinal : '%dº', + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. + } + }); - function preParsePostFormat (string) { - return string; - } + return gl; - var proto$1 = Locale.prototype; +}))); - proto$1.calendar = calendar; - proto$1.longDateFormat = longDateFormat; - proto$1.invalidDate = invalidDate; - proto$1.ordinal = ordinal; - proto$1.preparse = preParsePostFormat; - proto$1.postformat = preParsePostFormat; - proto$1.relativeTime = relativeTime; - proto$1.pastFuture = pastFuture; - proto$1.set = set; - proto$1.months = localeMonths; - proto$1.monthsShort = localeMonthsShort; - proto$1.monthsParse = localeMonthsParse; - proto$1.monthsRegex = monthsRegex; - proto$1.monthsShortRegex = monthsShortRegex; - proto$1.week = localeWeek; - proto$1.firstDayOfYear = localeFirstDayOfYear; - proto$1.firstDayOfWeek = localeFirstDayOfWeek; +/***/ }), +/* 62 */ +/***/ (function(module, exports, __webpack_require__) { - proto$1.weekdays = localeWeekdays; - proto$1.weekdaysMin = localeWeekdaysMin; - proto$1.weekdaysShort = localeWeekdaysShort; - proto$1.weekdaysParse = localeWeekdaysParse; +//! moment.js locale configuration - proto$1.weekdaysRegex = weekdaysRegex; - proto$1.weekdaysShortRegex = weekdaysShortRegex; - proto$1.weekdaysMinRegex = weekdaysMinRegex; +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - proto$1.isPM = localeIsPM; - proto$1.meridiem = localeMeridiem; - function get$1 (format, index, field, setter) { - var locale = getLocale(); - var utc = createUTC().set(setter, index); - return locale[field](utc, format); + function processRelativeTime(number, withoutSuffix, key, isFuture) { + var format = { + 's': ['thodde secondanim', 'thodde second'], + 'ss': [number + ' secondanim', number + ' second'], + 'm': ['eka mintan', 'ek minute'], + 'mm': [number + ' mintanim', number + ' mintam'], + 'h': ['eka voran', 'ek vor'], + 'hh': [number + ' voranim', number + ' voram'], + 'd': ['eka disan', 'ek dis'], + 'dd': [number + ' disanim', number + ' dis'], + 'M': ['eka mhoinean', 'ek mhoino'], + 'MM': [number + ' mhoineanim', number + ' mhoine'], + 'y': ['eka vorsan', 'ek voros'], + 'yy': [number + ' vorsanim', number + ' vorsam'] + }; + return withoutSuffix ? format[key][0] : format[key][1]; } - function listMonthsImpl (format, index, field) { - if (isNumber(format)) { - index = format; - format = undefined; + var gomLatn = moment.defineLocale('gom-latn', { + months : 'Janer_Febrer_Mars_Abril_Mai_Jun_Julai_Agost_Setembr_Otubr_Novembr_Dezembr'.split('_'), + monthsShort : 'Jan._Feb._Mars_Abr._Mai_Jun_Jul._Ago._Set._Otu._Nov._Dez.'.split('_'), + monthsParseExact : true, + weekdays : 'Aitar_Somar_Mongllar_Budvar_Brestar_Sukrar_Son\'var'.split('_'), + weekdaysShort : 'Ait._Som._Mon._Bud._Bre._Suk._Son.'.split('_'), + weekdaysMin : 'Ai_Sm_Mo_Bu_Br_Su_Sn'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'A h:mm [vazta]', + LTS : 'A h:mm:ss [vazta]', + L : 'DD-MM-YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY A h:mm [vazta]', + LLLL : 'dddd, MMMM[achea] Do, YYYY, A h:mm [vazta]', + llll: 'ddd, D MMM YYYY, A h:mm [vazta]' + }, + calendar : { + sameDay: '[Aiz] LT', + nextDay: '[Faleam] LT', + nextWeek: '[Ieta to] dddd[,] LT', + lastDay: '[Kal] LT', + lastWeek: '[Fatlo] dddd[,] LT', + sameElse: 'L' + }, + relativeTime : { + future : '%s', + past : '%s adim', + s : processRelativeTime, + ss : processRelativeTime, + m : processRelativeTime, + mm : processRelativeTime, + h : processRelativeTime, + hh : processRelativeTime, + d : processRelativeTime, + dd : processRelativeTime, + M : processRelativeTime, + MM : processRelativeTime, + y : processRelativeTime, + yy : processRelativeTime + }, + dayOfMonthOrdinalParse : /\d{1,2}(er)/, + ordinal : function (number, period) { + switch (period) { + // the ordinal 'er' only applies to day of the month + case 'D': + return number + 'er'; + default: + case 'M': + case 'Q': + case 'DDD': + case 'd': + case 'w': + case 'W': + return number; + } + }, + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. + }, + meridiemParse: /rati|sokalli|donparam|sanje/, + meridiemHour : function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'rati') { + return hour < 4 ? hour : hour + 12; + } else if (meridiem === 'sokalli') { + return hour; + } else if (meridiem === 'donparam') { + return hour > 12 ? hour : hour + 12; + } else if (meridiem === 'sanje') { + return hour + 12; + } + }, + meridiem : function (hour, minute, isLower) { + if (hour < 4) { + return 'rati'; + } else if (hour < 12) { + return 'sokalli'; + } else if (hour < 16) { + return 'donparam'; + } else if (hour < 20) { + return 'sanje'; + } else { + return 'rati'; + } } + }); - format = format || ''; + return gomLatn; - if (index != null) { - return get$1(format, index, field, 'month'); - } +}))); - var i; - var out = []; - for (i = 0; i < 12; i++) { - out[i] = get$1(format, i, field, 'month'); - } - return out; - } - // () - // (5) - // (fmt, 5) - // (fmt) - // (true) - // (true, 5) - // (true, fmt, 5) - // (true, fmt) - function listWeekdaysImpl (localeSorted, format, index, field) { - if (typeof localeSorted === 'boolean') { - if (isNumber(format)) { - index = format; - format = undefined; - } +/***/ }), +/* 63 */ +/***/ (function(module, exports, __webpack_require__) { - format = format || ''; - } else { - format = localeSorted; - index = format; - localeSorted = false; +//! moment.js locale configuration - if (isNumber(format)) { - index = format; - format = undefined; - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - format = format || ''; - } - var locale = getLocale(), - shift = localeSorted ? locale._week.dow : 0; + var symbolMap = { + '1': '૧', + '2': '૨', + '3': '૩', + '4': '૪', + '5': '૫', + '6': '૬', + '7': '૭', + '8': '૮', + '9': '૯', + '0': '૦' + }, + numberMap = { + '૧': '1', + '૨': '2', + '૩': '3', + '૪': '4', + '૫': '5', + '૬': '6', + '૭': '7', + '૮': '8', + '૯': '9', + '૦': '0' + }; - if (index != null) { - return get$1(format, (index + shift) % 7, field, 'day'); + var gu = moment.defineLocale('gu', { + months: 'જાન્યુઆરી_ફેબ્રુઆરી_માર્ચ_એપ્રિલ_મે_જૂન_જુલાઈ_ઑગસ્ટ_સપ્ટેમ્બર_ઑક્ટ્બર_નવેમ્બર_ડિસેમ્બર'.split('_'), + monthsShort: 'જાન્યુ._ફેબ્રુ._માર્ચ_એપ્રિ._મે_જૂન_જુલા._ઑગ._સપ્ટે._ઑક્ટ્._નવે._ડિસે.'.split('_'), + monthsParseExact: true, + weekdays: 'રવિવાર_સોમવાર_મંગળવાર_બુધ્વાર_ગુરુવાર_શુક્રવાર_શનિવાર'.split('_'), + weekdaysShort: 'રવિ_સોમ_મંગળ_બુધ્_ગુરુ_શુક્ર_શનિ'.split('_'), + weekdaysMin: 'ર_સો_મં_બુ_ગુ_શુ_શ'.split('_'), + longDateFormat: { + LT: 'A h:mm વાગ્યે', + LTS: 'A h:mm:ss વાગ્યે', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY, A h:mm વાગ્યે', + LLLL: 'dddd, D MMMM YYYY, A h:mm વાગ્યે' + }, + calendar: { + sameDay: '[આજ] LT', + nextDay: '[કાલે] LT', + nextWeek: 'dddd, LT', + lastDay: '[ગઇકાલે] LT', + lastWeek: '[પાછલા] dddd, LT', + sameElse: 'L' + }, + relativeTime: { + future: '%s મા', + past: '%s પેહલા', + s: 'અમુક પળો', + ss: '%d સેકંડ', + m: 'એક મિનિટ', + mm: '%d મિનિટ', + h: 'એક કલાક', + hh: '%d કલાક', + d: 'એક દિવસ', + dd: '%d દિવસ', + M: 'એક મહિનો', + MM: '%d મહિનો', + y: 'એક વર્ષ', + yy: '%d વર્ષ' + }, + preparse: function (string) { + return string.replace(/[૧૨૩૪૫૬૭૮૯૦]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + // Gujarati notation for meridiems are quite fuzzy in practice. While there exists + // a rigid notion of a 'Pahar' it is not used as rigidly in modern Gujarati. + meridiemParse: /રાત|બપોર|સવાર|સાંજ/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'રાત') { + return hour < 4 ? hour : hour + 12; + } else if (meridiem === 'સવાર') { + return hour; + } else if (meridiem === 'બપોર') { + return hour >= 10 ? hour : hour + 12; + } else if (meridiem === 'સાંજ') { + return hour + 12; + } + }, + meridiem: function (hour, minute, isLower) { + if (hour < 4) { + return 'રાત'; + } else if (hour < 10) { + return 'સવાર'; + } else if (hour < 17) { + return 'બપોર'; + } else if (hour < 20) { + return 'સાંજ'; + } else { + return 'રાત'; + } + }, + week: { + dow: 0, // Sunday is the first day of the week. + doy: 6 // The week that contains Jan 6th is the first week of the year. } + }); - var i; - var out = []; - for (i = 0; i < 7; i++) { - out[i] = get$1(format, (i + shift) % 7, field, 'day'); - } - return out; - } + return gu; - function listMonths (format, index) { - return listMonthsImpl(format, index, 'months'); - } +}))); - function listMonthsShort (format, index) { - return listMonthsImpl(format, index, 'monthsShort'); - } - function listWeekdays (localeSorted, format, index) { - return listWeekdaysImpl(localeSorted, format, index, 'weekdays'); - } +/***/ }), +/* 64 */ +/***/ (function(module, exports, __webpack_require__) { - function listWeekdaysShort (localeSorted, format, index) { - return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort'); - } +//! moment.js locale configuration - function listWeekdaysMin (localeSorted, format, index) { - return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin'); - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - getSetGlobalLocale('en', { - dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, - ordinal : function (number) { - var b = number % 10, - output = (toInt(number % 100 / 10) === 1) ? 'th' : - (b === 1) ? 'st' : - (b === 2) ? 'nd' : - (b === 3) ? 'rd' : 'th'; - return number + output; + + var he = moment.defineLocale('he', { + months : 'ינואר_פברואר_מרץ_אפריל_מאי_יוני_יולי_אוגוסט_ספטמבר_אוקטובר_נובמבר_דצמבר'.split('_'), + monthsShort : 'ינו׳_פבר׳_מרץ_אפר׳_מאי_יוני_יולי_אוג׳_ספט׳_אוק׳_נוב׳_דצמ׳'.split('_'), + weekdays : 'ראשון_שני_שלישי_רביעי_חמישי_שישי_שבת'.split('_'), + weekdaysShort : 'א׳_ב׳_ג׳_ד׳_ה׳_ו׳_ש׳'.split('_'), + weekdaysMin : 'א_ב_ג_ד_ה_ו_ש'.split('_'), + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D [ב]MMMM YYYY', + LLL : 'D [ב]MMMM YYYY HH:mm', + LLLL : 'dddd, D [ב]MMMM YYYY HH:mm', + l : 'D/M/YYYY', + ll : 'D MMM YYYY', + lll : 'D MMM YYYY HH:mm', + llll : 'ddd, D MMM YYYY HH:mm' + }, + calendar : { + sameDay : '[היום ב־]LT', + nextDay : '[מחר ב־]LT', + nextWeek : 'dddd [בשעה] LT', + lastDay : '[אתמול ב־]LT', + lastWeek : '[ביום] dddd [האחרון בשעה] LT', + sameElse : 'L' + }, + relativeTime : { + future : 'בעוד %s', + past : 'לפני %s', + s : 'מספר שניות', + ss : '%d שניות', + m : 'דקה', + mm : '%d דקות', + h : 'שעה', + hh : function (number) { + if (number === 2) { + return 'שעתיים'; + } + return number + ' שעות'; + }, + d : 'יום', + dd : function (number) { + if (number === 2) { + return 'יומיים'; + } + return number + ' ימים'; + }, + M : 'חודש', + MM : function (number) { + if (number === 2) { + return 'חודשיים'; + } + return number + ' חודשים'; + }, + y : 'שנה', + yy : function (number) { + if (number === 2) { + return 'שנתיים'; + } else if (number % 10 === 0 && number !== 10) { + return number + ' שנה'; + } + return number + ' שנים'; + } + }, + meridiemParse: /אחה"צ|לפנה"צ|אחרי הצהריים|לפני הצהריים|לפנות בוקר|בבוקר|בערב/i, + isPM : function (input) { + return /^(אחה"צ|אחרי הצהריים|בערב)$/.test(input); + }, + meridiem : function (hour, minute, isLower) { + if (hour < 5) { + return 'לפנות בוקר'; + } else if (hour < 10) { + return 'בבוקר'; + } else if (hour < 12) { + return isLower ? 'לפנה"צ' : 'לפני הצהריים'; + } else if (hour < 18) { + return isLower ? 'אחה"צ' : 'אחרי הצהריים'; + } else { + return 'בערב'; + } } }); - // Side effect imports - - hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale); - hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale); - - var mathAbs = Math.abs; - - function abs () { - var data = this._data; - - this._milliseconds = mathAbs(this._milliseconds); - this._days = mathAbs(this._days); - this._months = mathAbs(this._months); - - data.milliseconds = mathAbs(data.milliseconds); - data.seconds = mathAbs(data.seconds); - data.minutes = mathAbs(data.minutes); - data.hours = mathAbs(data.hours); - data.months = mathAbs(data.months); - data.years = mathAbs(data.years); - - return this; - } + return he; - function addSubtract$1 (duration, input, value, direction) { - var other = createDuration(input, value); +}))); - duration._milliseconds += direction * other._milliseconds; - duration._days += direction * other._days; - duration._months += direction * other._months; - return duration._bubble(); - } +/***/ }), +/* 65 */ +/***/ (function(module, exports, __webpack_require__) { - // supports only 2.0-style add(1, 's') or add(duration) - function add$1 (input, value) { - return addSubtract$1(this, input, value, 1); - } +//! moment.js locale configuration - // supports only 2.0-style subtract(1, 's') or subtract(duration) - function subtract$1 (input, value) { - return addSubtract$1(this, input, value, -1); - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - function absCeil (number) { - if (number < 0) { - return Math.floor(number); - } else { - return Math.ceil(number); - } - } - function bubble () { - var milliseconds = this._milliseconds; - var days = this._days; - var months = this._months; - var data = this._data; - var seconds, minutes, hours, years, monthsFromDays; + var symbolMap = { + '1': '१', + '2': '२', + '3': '३', + '4': '४', + '5': '५', + '6': '६', + '7': '७', + '8': '८', + '9': '९', + '0': '०' + }, + numberMap = { + '१': '1', + '२': '2', + '३': '3', + '४': '4', + '५': '5', + '६': '6', + '७': '7', + '८': '8', + '९': '9', + '०': '0' + }; - // if we have a mix of positive and negative values, bubble down first - // check: https://github.com/moment/moment/issues/2166 - if (!((milliseconds >= 0 && days >= 0 && months >= 0) || - (milliseconds <= 0 && days <= 0 && months <= 0))) { - milliseconds += absCeil(monthsToDays(months) + days) * 864e5; - days = 0; - months = 0; + var hi = moment.defineLocale('hi', { + months : 'जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर'.split('_'), + monthsShort : 'जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.'.split('_'), + monthsParseExact: true, + weekdays : 'रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'), + weekdaysShort : 'रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि'.split('_'), + weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split('_'), + longDateFormat : { + LT : 'A h:mm बजे', + LTS : 'A h:mm:ss बजे', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY, A h:mm बजे', + LLLL : 'dddd, D MMMM YYYY, A h:mm बजे' + }, + calendar : { + sameDay : '[आज] LT', + nextDay : '[कल] LT', + nextWeek : 'dddd, LT', + lastDay : '[कल] LT', + lastWeek : '[पिछले] dddd, LT', + sameElse : 'L' + }, + relativeTime : { + future : '%s में', + past : '%s पहले', + s : 'कुछ ही क्षण', + ss : '%d सेकंड', + m : 'एक मिनट', + mm : '%d मिनट', + h : 'एक घंटा', + hh : '%d घंटे', + d : 'एक दिन', + dd : '%d दिन', + M : 'एक महीने', + MM : '%d महीने', + y : 'एक वर्ष', + yy : '%d वर्ष' + }, + preparse: function (string) { + return string.replace(/[१२३४५६७८९०]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + // Hindi notation for meridiems are quite fuzzy in practice. While there exists + // a rigid notion of a 'Pahar' it is not used as rigidly in modern Hindi. + meridiemParse: /रात|सुबह|दोपहर|शाम/, + meridiemHour : function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'रात') { + return hour < 4 ? hour : hour + 12; + } else if (meridiem === 'सुबह') { + return hour; + } else if (meridiem === 'दोपहर') { + return hour >= 10 ? hour : hour + 12; + } else if (meridiem === 'शाम') { + return hour + 12; + } + }, + meridiem : function (hour, minute, isLower) { + if (hour < 4) { + return 'रात'; + } else if (hour < 10) { + return 'सुबह'; + } else if (hour < 17) { + return 'दोपहर'; + } else if (hour < 20) { + return 'शाम'; + } else { + return 'रात'; + } + }, + week : { + dow : 0, // Sunday is the first day of the week. + doy : 6 // The week that contains Jan 6th is the first week of the year. } + }); - // The following code bubbles up values, see the tests for - // examples of what that means. - data.milliseconds = milliseconds % 1000; - - seconds = absFloor(milliseconds / 1000); - data.seconds = seconds % 60; - - minutes = absFloor(seconds / 60); - data.minutes = minutes % 60; - - hours = absFloor(minutes / 60); - data.hours = hours % 24; + return hi; - days += absFloor(hours / 24); +}))); - // convert days to months - monthsFromDays = absFloor(daysToMonths(days)); - months += monthsFromDays; - days -= absCeil(monthsToDays(monthsFromDays)); - // 12 months -> 1 year - years = absFloor(months / 12); - months %= 12; +/***/ }), +/* 66 */ +/***/ (function(module, exports, __webpack_require__) { - data.days = days; - data.months = months; - data.years = years; +//! moment.js locale configuration - return this; - } +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - function daysToMonths (days) { - // 400 years have 146097 days (taking into account leap year rules) - // 400 years have 12 months === 4800 - return days * 4800 / 146097; - } - function monthsToDays (months) { - // the reverse of daysToMonths - return months * 146097 / 4800; + function translate(number, withoutSuffix, key) { + var result = number + ' '; + switch (key) { + case 'ss': + if (number === 1) { + result += 'sekunda'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'sekunde'; + } else { + result += 'sekundi'; + } + return result; + case 'm': + return withoutSuffix ? 'jedna minuta' : 'jedne minute'; + case 'mm': + if (number === 1) { + result += 'minuta'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'minute'; + } else { + result += 'minuta'; + } + return result; + case 'h': + return withoutSuffix ? 'jedan sat' : 'jednog sata'; + case 'hh': + if (number === 1) { + result += 'sat'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'sata'; + } else { + result += 'sati'; + } + return result; + case 'dd': + if (number === 1) { + result += 'dan'; + } else { + result += 'dana'; + } + return result; + case 'MM': + if (number === 1) { + result += 'mjesec'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'mjeseca'; + } else { + result += 'mjeseci'; + } + return result; + case 'yy': + if (number === 1) { + result += 'godina'; + } else if (number === 2 || number === 3 || number === 4) { + result += 'godine'; + } else { + result += 'godina'; + } + return result; + } } - function as (units) { - if (!this.isValid()) { - return NaN; - } - var days; - var months; - var milliseconds = this._milliseconds; - - units = normalizeUnits(units); - - if (units === 'month' || units === 'quarter' || units === 'year') { - days = this._days + milliseconds / 864e5; - months = this._months + daysToMonths(days); - switch (units) { - case 'month': return months; - case 'quarter': return months / 3; - case 'year': return months / 12; - } - } else { - // handle milliseconds separately because of floating point math errors (issue #1867) - days = this._days + Math.round(monthsToDays(this._months)); - switch (units) { - case 'week' : return days / 7 + milliseconds / 6048e5; - case 'day' : return days + milliseconds / 864e5; - case 'hour' : return days * 24 + milliseconds / 36e5; - case 'minute' : return days * 1440 + milliseconds / 6e4; - case 'second' : return days * 86400 + milliseconds / 1000; - // Math.floor prevents floating point math errors here - case 'millisecond': return Math.floor(days * 864e5) + milliseconds; - default: throw new Error('Unknown unit ' + units); - } - } - } - - // TODO: Use this.as('ms')? - function valueOf$1 () { - if (!this.isValid()) { - return NaN; + var hr = moment.defineLocale('hr', { + months : { + format: 'siječnja_veljače_ožujka_travnja_svibnja_lipnja_srpnja_kolovoza_rujna_listopada_studenoga_prosinca'.split('_'), + standalone: 'siječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac'.split('_') + }, + monthsShort : 'sij._velj._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.'.split('_'), + monthsParseExact: true, + weekdays : 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'), + weekdaysShort : 'ned._pon._uto._sri._čet._pet._sub.'.split('_'), + weekdaysMin : 'ne_po_ut_sr_če_pe_su'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'H:mm', + LTS : 'H:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D. MMMM YYYY', + LLL : 'D. MMMM YYYY H:mm', + LLLL : 'dddd, D. MMMM YYYY H:mm' + }, + calendar : { + sameDay : '[danas u] LT', + nextDay : '[sutra u] LT', + nextWeek : function () { + switch (this.day()) { + case 0: + return '[u] [nedjelju] [u] LT'; + case 3: + return '[u] [srijedu] [u] LT'; + case 6: + return '[u] [subotu] [u] LT'; + case 1: + case 2: + case 4: + case 5: + return '[u] dddd [u] LT'; + } + }, + lastDay : '[jučer u] LT', + lastWeek : function () { + switch (this.day()) { + case 0: + case 3: + return '[prošlu] dddd [u] LT'; + case 6: + return '[prošle] [subote] [u] LT'; + case 1: + case 2: + case 4: + case 5: + return '[prošli] dddd [u] LT'; + } + }, + sameElse : 'L' + }, + relativeTime : { + future : 'za %s', + past : 'prije %s', + s : 'par sekundi', + ss : translate, + m : translate, + mm : translate, + h : translate, + hh : translate, + d : 'dan', + dd : translate, + M : 'mjesec', + MM : translate, + y : 'godinu', + yy : translate + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', + week : { + dow : 1, // Monday is the first day of the week. + doy : 7 // The week that contains Jan 7th is the first week of the year. } - return ( - this._milliseconds + - this._days * 864e5 + - (this._months % 12) * 2592e6 + - toInt(this._months / 12) * 31536e6 - ); - } - - function makeAs (alias) { - return function () { - return this.as(alias); - }; - } - - var asMilliseconds = makeAs('ms'); - var asSeconds = makeAs('s'); - var asMinutes = makeAs('m'); - var asHours = makeAs('h'); - var asDays = makeAs('d'); - var asWeeks = makeAs('w'); - var asMonths = makeAs('M'); - var asQuarters = makeAs('Q'); - var asYears = makeAs('y'); - - function clone$1 () { - return createDuration(this); - } - - function get$2 (units) { - units = normalizeUnits(units); - return this.isValid() ? this[units + 's']() : NaN; - } - - function makeGetter(name) { - return function () { - return this.isValid() ? this._data[name] : NaN; - }; - } + }); - var milliseconds = makeGetter('milliseconds'); - var seconds = makeGetter('seconds'); - var minutes = makeGetter('minutes'); - var hours = makeGetter('hours'); - var days = makeGetter('days'); - var months = makeGetter('months'); - var years = makeGetter('years'); + return hr; - function weeks () { - return absFloor(this.days() / 7); - } +}))); - var round = Math.round; - var thresholds = { - ss: 44, // a few seconds to seconds - s : 45, // seconds to minute - m : 45, // minutes to hour - h : 22, // hours to day - d : 26, // days to month - M : 11 // months to year - }; - // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize - function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { - return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); - } +/***/ }), +/* 67 */ +/***/ (function(module, exports, __webpack_require__) { - function relativeTime$1 (posNegDuration, withoutSuffix, locale) { - var duration = createDuration(posNegDuration).abs(); - var seconds = round(duration.as('s')); - var minutes = round(duration.as('m')); - var hours = round(duration.as('h')); - var days = round(duration.as('d')); - var months = round(duration.as('M')); - var years = round(duration.as('y')); +//! moment.js locale configuration - var a = seconds <= thresholds.ss && ['s', seconds] || - seconds < thresholds.s && ['ss', seconds] || - minutes <= 1 && ['m'] || - minutes < thresholds.m && ['mm', minutes] || - hours <= 1 && ['h'] || - hours < thresholds.h && ['hh', hours] || - days <= 1 && ['d'] || - days < thresholds.d && ['dd', days] || - months <= 1 && ['M'] || - months < thresholds.M && ['MM', months] || - years <= 1 && ['y'] || ['yy', years]; +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - a[2] = withoutSuffix; - a[3] = +posNegDuration > 0; - a[4] = locale; - return substituteTimeAgo.apply(null, a); - } - // This function allows you to set the rounding function for relative time strings - function getSetRelativeTimeRounding (roundingFunction) { - if (roundingFunction === undefined) { - return round; - } - if (typeof(roundingFunction) === 'function') { - round = roundingFunction; - return true; + var weekEndings = 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' '); + function translate(number, withoutSuffix, key, isFuture) { + var num = number; + switch (key) { + case 's': + return (isFuture || withoutSuffix) ? 'néhány másodperc' : 'néhány másodperce'; + case 'ss': + return num + (isFuture || withoutSuffix) ? ' másodperc' : ' másodperce'; + case 'm': + return 'egy' + (isFuture || withoutSuffix ? ' perc' : ' perce'); + case 'mm': + return num + (isFuture || withoutSuffix ? ' perc' : ' perce'); + case 'h': + return 'egy' + (isFuture || withoutSuffix ? ' óra' : ' órája'); + case 'hh': + return num + (isFuture || withoutSuffix ? ' óra' : ' órája'); + case 'd': + return 'egy' + (isFuture || withoutSuffix ? ' nap' : ' napja'); + case 'dd': + return num + (isFuture || withoutSuffix ? ' nap' : ' napja'); + case 'M': + return 'egy' + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); + case 'MM': + return num + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); + case 'y': + return 'egy' + (isFuture || withoutSuffix ? ' év' : ' éve'); + case 'yy': + return num + (isFuture || withoutSuffix ? ' év' : ' éve'); } - return false; + return ''; } - - // This function allows you to set a threshold for relative time strings - function getSetRelativeTimeThreshold (threshold, limit) { - if (thresholds[threshold] === undefined) { - return false; - } - if (limit === undefined) { - return thresholds[threshold]; - } - thresholds[threshold] = limit; - if (threshold === 's') { - thresholds.ss = limit - 1; - } - return true; + function week(isFuture) { + return (isFuture ? '' : '[múlt] ') + '[' + weekEndings[this.day()] + '] LT[-kor]'; } - function humanize (withSuffix) { - if (!this.isValid()) { - return this.localeData().invalidDate(); + var hu = moment.defineLocale('hu', { + months : 'január_február_március_április_május_június_július_augusztus_szeptember_október_november_december'.split('_'), + monthsShort : 'jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec'.split('_'), + weekdays : 'vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat'.split('_'), + weekdaysShort : 'vas_hét_kedd_sze_csüt_pén_szo'.split('_'), + weekdaysMin : 'v_h_k_sze_cs_p_szo'.split('_'), + longDateFormat : { + LT : 'H:mm', + LTS : 'H:mm:ss', + L : 'YYYY.MM.DD.', + LL : 'YYYY. MMMM D.', + LLL : 'YYYY. MMMM D. H:mm', + LLLL : 'YYYY. MMMM D., dddd H:mm' + }, + meridiemParse: /de|du/i, + isPM: function (input) { + return input.charAt(1).toLowerCase() === 'u'; + }, + meridiem : function (hours, minutes, isLower) { + if (hours < 12) { + return isLower === true ? 'de' : 'DE'; + } else { + return isLower === true ? 'du' : 'DU'; + } + }, + calendar : { + sameDay : '[ma] LT[-kor]', + nextDay : '[holnap] LT[-kor]', + nextWeek : function () { + return week.call(this, true); + }, + lastDay : '[tegnap] LT[-kor]', + lastWeek : function () { + return week.call(this, false); + }, + sameElse : 'L' + }, + relativeTime : { + future : '%s múlva', + past : '%s', + s : translate, + ss : translate, + m : translate, + mm : translate, + h : translate, + hh : translate, + d : translate, + dd : translate, + M : translate, + MM : translate, + y : translate, + yy : translate + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } + }); - var locale = this.localeData(); - var output = relativeTime$1(this, !withSuffix, locale); - - if (withSuffix) { - output = locale.pastFuture(+this, output); - } + return hu; - return locale.postformat(output); - } +}))); - var abs$1 = Math.abs; - function sign(x) { - return ((x > 0) - (x < 0)) || +x; - } +/***/ }), +/* 68 */ +/***/ (function(module, exports, __webpack_require__) { - function toISOString$1() { - // for ISO strings we do not use the normal bubbling rules: - // * milliseconds bubble up until they become hours - // * days do not bubble at all - // * months bubble up until they become years - // This is because there is no context-free conversion between hours and days - // (think of clock changes) - // and also not between days and months (28-31 days per month) - if (!this.isValid()) { - return this.localeData().invalidDate(); - } +//! moment.js locale configuration - var seconds = abs$1(this._milliseconds) / 1000; - var days = abs$1(this._days); - var months = abs$1(this._months); - var minutes, hours, years; +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - // 3600 seconds -> 60 minutes -> 1 hour - minutes = absFloor(seconds / 60); - hours = absFloor(minutes / 60); - seconds %= 60; - minutes %= 60; - // 12 months -> 1 year - years = absFloor(months / 12); - months %= 12; + var hyAm = moment.defineLocale('hy-am', { + months : { + format: 'հունվարի_փետրվարի_մարտի_ապրիլի_մայիսի_հունիսի_հուլիսի_օգոստոսի_սեպտեմբերի_հոկտեմբերի_նոյեմբերի_դեկտեմբերի'.split('_'), + standalone: 'հունվար_փետրվար_մարտ_ապրիլ_մայիս_հունիս_հուլիս_օգոստոս_սեպտեմբեր_հոկտեմբեր_նոյեմբեր_դեկտեմբեր'.split('_') + }, + monthsShort : 'հնվ_փտր_մրտ_ապր_մյս_հնս_հլս_օգս_սպտ_հկտ_նմբ_դկտ'.split('_'), + weekdays : 'կիրակի_երկուշաբթի_երեքշաբթի_չորեքշաբթի_հինգշաբթի_ուրբաթ_շաբաթ'.split('_'), + weekdaysShort : 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'), + weekdaysMin : 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'), + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D MMMM YYYY թ.', + LLL : 'D MMMM YYYY թ., HH:mm', + LLLL : 'dddd, D MMMM YYYY թ., HH:mm' + }, + calendar : { + sameDay: '[այսօր] LT', + nextDay: '[վաղը] LT', + lastDay: '[երեկ] LT', + nextWeek: function () { + return 'dddd [օրը ժամը] LT'; + }, + lastWeek: function () { + return '[անցած] dddd [օրը ժամը] LT'; + }, + sameElse: 'L' + }, + relativeTime : { + future : '%s հետո', + past : '%s առաջ', + s : 'մի քանի վայրկյան', + ss : '%d վայրկյան', + m : 'րոպե', + mm : '%d րոպե', + h : 'ժամ', + hh : '%d ժամ', + d : 'օր', + dd : '%d օր', + M : 'ամիս', + MM : '%d ամիս', + y : 'տարի', + yy : '%d տարի' + }, + meridiemParse: /գիշերվա|առավոտվա|ցերեկվա|երեկոյան/, + isPM: function (input) { + return /^(ցերեկվա|երեկոյան)$/.test(input); + }, + meridiem : function (hour) { + if (hour < 4) { + return 'գիշերվա'; + } else if (hour < 12) { + return 'առավոտվա'; + } else if (hour < 17) { + return 'ցերեկվա'; + } else { + return 'երեկոյան'; + } + }, + dayOfMonthOrdinalParse: /\d{1,2}|\d{1,2}-(ին|րդ)/, + ordinal: function (number, period) { + switch (period) { + case 'DDD': + case 'w': + case 'W': + case 'DDDo': + if (number === 1) { + return number + '-ին'; + } + return number + '-րդ'; + default: + return number; + } + }, + week : { + dow : 1, // Monday is the first day of the week. + doy : 7 // The week that contains Jan 7th is the first week of the year. + } + }); + return hyAm; - // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js - var Y = years; - var M = months; - var D = days; - var h = hours; - var m = minutes; - var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : ''; - var total = this.asSeconds(); +}))); - if (!total) { - // this is the same as C#'s (Noda) and python (isodate)... - // but not other JS (goog.date) - return 'P0D'; - } - var totalSign = total < 0 ? '-' : ''; - var ymSign = sign(this._months) !== sign(total) ? '-' : ''; - var daysSign = sign(this._days) !== sign(total) ? '-' : ''; - var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : ''; +/***/ }), +/* 69 */ +/***/ (function(module, exports, __webpack_require__) { - return totalSign + 'P' + - (Y ? ymSign + Y + 'Y' : '') + - (M ? ymSign + M + 'M' : '') + - (D ? daysSign + D + 'D' : '') + - ((h || m || s) ? 'T' : '') + - (h ? hmsSign + h + 'H' : '') + - (m ? hmsSign + m + 'M' : '') + - (s ? hmsSign + s + 'S' : ''); - } +//! moment.js locale configuration - var proto$2 = Duration.prototype; +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; - proto$2.isValid = isValid$1; - proto$2.abs = abs; - proto$2.add = add$1; - proto$2.subtract = subtract$1; - proto$2.as = as; - proto$2.asMilliseconds = asMilliseconds; - proto$2.asSeconds = asSeconds; - proto$2.asMinutes = asMinutes; - proto$2.asHours = asHours; - proto$2.asDays = asDays; - proto$2.asWeeks = asWeeks; - proto$2.asMonths = asMonths; - proto$2.asQuarters = asQuarters; - proto$2.asYears = asYears; - proto$2.valueOf = valueOf$1; - proto$2._bubble = bubble; - proto$2.clone = clone$1; - proto$2.get = get$2; - proto$2.milliseconds = milliseconds; - proto$2.seconds = seconds; - proto$2.minutes = minutes; - proto$2.hours = hours; - proto$2.days = days; - proto$2.weeks = weeks; - proto$2.months = months; - proto$2.years = years; - proto$2.humanize = humanize; - proto$2.toISOString = toISOString$1; - proto$2.toString = toISOString$1; - proto$2.toJSON = toISOString$1; - proto$2.locale = locale; - proto$2.localeData = localeData; - proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1); - proto$2.lang = lang; - - // Side effect imports - - // FORMATTING - - addFormatToken('X', 0, 0, 'unix'); - addFormatToken('x', 0, 0, 'valueOf'); - - // PARSING - - addRegexToken('x', matchSigned); - addRegexToken('X', matchTimestamp); - addParseToken('X', function (input, array, config) { - config._d = new Date(parseFloat(input, 10) * 1000); - }); - addParseToken('x', function (input, array, config) { - config._d = new Date(toInt(input)); - }); - - // Side effect imports - - - hooks.version = '2.24.0'; - - setHookCallback(createLocal); - - hooks.fn = proto; - hooks.min = min; - hooks.max = max; - hooks.now = now; - hooks.utc = createUTC; - hooks.unix = createUnix; - hooks.months = listMonths; - hooks.isDate = isDate; - hooks.locale = getSetGlobalLocale; - hooks.invalid = createInvalid; - hooks.duration = createDuration; - hooks.isMoment = isMoment; - hooks.weekdays = listWeekdays; - hooks.parseZone = createInZone; - hooks.localeData = getLocale; - hooks.isDuration = isDuration; - hooks.monthsShort = listMonthsShort; - hooks.weekdaysMin = listWeekdaysMin; - hooks.defineLocale = defineLocale; - hooks.updateLocale = updateLocale; - hooks.locales = listLocales; - hooks.weekdaysShort = listWeekdaysShort; - hooks.normalizeUnits = normalizeUnits; - hooks.relativeTimeRounding = getSetRelativeTimeRounding; - hooks.relativeTimeThreshold = getSetRelativeTimeThreshold; - hooks.calendarFormat = getCalendarFormat; - hooks.prototype = proto; - - // currently HTML5 input type only supports 24-hour formats - hooks.HTML5_FMT = { - DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // - DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // - DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // - DATE: 'YYYY-MM-DD', // - TIME: 'HH:mm', // - TIME_SECONDS: 'HH:mm:ss', // - TIME_MS: 'HH:mm:ss.SSS', // - WEEK: 'GGGG-[W]WW', // - MONTH: 'YYYY-MM' // - }; - - return hooks; - -}))); - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(5)(module))) - -/***/ }), -/* 41 */ -/***/ (function(module, exports, __webpack_require__) { - -var map = { - "./af": 42, - "./af.js": 42, - "./ar": 43, - "./ar-dz": 44, - "./ar-dz.js": 44, - "./ar-kw": 45, - "./ar-kw.js": 45, - "./ar-ly": 46, - "./ar-ly.js": 46, - "./ar-ma": 47, - "./ar-ma.js": 47, - "./ar-sa": 48, - "./ar-sa.js": 48, - "./ar-tn": 49, - "./ar-tn.js": 49, - "./ar.js": 43, - "./az": 50, - "./az.js": 50, - "./be": 51, - "./be.js": 51, - "./bg": 52, - "./bg.js": 52, - "./bm": 53, - "./bm.js": 53, - "./bn": 54, - "./bn.js": 54, - "./bo": 55, - "./bo.js": 55, - "./br": 56, - "./br.js": 56, - "./bs": 57, - "./bs.js": 57, - "./ca": 58, - "./ca.js": 58, - "./cs": 59, - "./cs.js": 59, - "./cv": 60, - "./cv.js": 60, - "./cy": 61, - "./cy.js": 61, - "./da": 62, - "./da.js": 62, - "./de": 63, - "./de-at": 64, - "./de-at.js": 64, - "./de-ch": 65, - "./de-ch.js": 65, - "./de.js": 63, - "./dv": 66, - "./dv.js": 66, - "./el": 67, - "./el.js": 67, - "./en-SG": 68, - "./en-SG.js": 68, - "./en-au": 69, - "./en-au.js": 69, - "./en-ca": 70, - "./en-ca.js": 70, - "./en-gb": 71, - "./en-gb.js": 71, - "./en-ie": 72, - "./en-ie.js": 72, - "./en-il": 73, - "./en-il.js": 73, - "./en-nz": 74, - "./en-nz.js": 74, - "./eo": 75, - "./eo.js": 75, - "./es": 76, - "./es-do": 77, - "./es-do.js": 77, - "./es-us": 78, - "./es-us.js": 78, - "./es.js": 76, - "./et": 79, - "./et.js": 79, - "./eu": 80, - "./eu.js": 80, - "./fa": 81, - "./fa.js": 81, - "./fi": 82, - "./fi.js": 82, - "./fo": 83, - "./fo.js": 83, - "./fr": 84, - "./fr-ca": 85, - "./fr-ca.js": 85, - "./fr-ch": 86, - "./fr-ch.js": 86, - "./fr.js": 84, - "./fy": 87, - "./fy.js": 87, - "./ga": 88, - "./ga.js": 88, - "./gd": 89, - "./gd.js": 89, - "./gl": 90, - "./gl.js": 90, - "./gom-latn": 91, - "./gom-latn.js": 91, - "./gu": 92, - "./gu.js": 92, - "./he": 93, - "./he.js": 93, - "./hi": 94, - "./hi.js": 94, - "./hr": 95, - "./hr.js": 95, - "./hu": 96, - "./hu.js": 96, - "./hy-am": 97, - "./hy-am.js": 97, - "./id": 98, - "./id.js": 98, - "./is": 99, - "./is.js": 99, - "./it": 100, - "./it-ch": 101, - "./it-ch.js": 101, - "./it.js": 100, - "./ja": 102, - "./ja.js": 102, - "./jv": 103, - "./jv.js": 103, - "./ka": 104, - "./ka.js": 104, - "./kk": 105, - "./kk.js": 105, - "./km": 106, - "./km.js": 106, - "./kn": 107, - "./kn.js": 107, - "./ko": 108, - "./ko.js": 108, - "./ku": 109, - "./ku.js": 109, - "./ky": 110, - "./ky.js": 110, - "./lb": 111, - "./lb.js": 111, - "./lo": 112, - "./lo.js": 112, - "./lt": 113, - "./lt.js": 113, - "./lv": 114, - "./lv.js": 114, - "./me": 115, - "./me.js": 115, - "./mi": 116, - "./mi.js": 116, - "./mk": 117, - "./mk.js": 117, - "./ml": 118, - "./ml.js": 118, - "./mn": 119, - "./mn.js": 119, - "./mr": 120, - "./mr.js": 120, - "./ms": 121, - "./ms-my": 122, - "./ms-my.js": 122, - "./ms.js": 121, - "./mt": 123, - "./mt.js": 123, - "./my": 124, - "./my.js": 124, - "./nb": 125, - "./nb.js": 125, - "./ne": 126, - "./ne.js": 126, - "./nl": 127, - "./nl-be": 128, - "./nl-be.js": 128, - "./nl.js": 127, - "./nn": 129, - "./nn.js": 129, - "./pa-in": 130, - "./pa-in.js": 130, - "./pl": 131, - "./pl.js": 131, - "./pt": 132, - "./pt-br": 133, - "./pt-br.js": 133, - "./pt.js": 132, - "./ro": 134, - "./ro.js": 134, - "./ru": 135, - "./ru.js": 135, - "./sd": 136, - "./sd.js": 136, - "./se": 137, - "./se.js": 137, - "./si": 138, - "./si.js": 138, - "./sk": 139, - "./sk.js": 139, - "./sl": 140, - "./sl.js": 140, - "./sq": 141, - "./sq.js": 141, - "./sr": 142, - "./sr-cyrl": 143, - "./sr-cyrl.js": 143, - "./sr.js": 142, - "./ss": 144, - "./ss.js": 144, - "./sv": 145, - "./sv.js": 145, - "./sw": 146, - "./sw.js": 146, - "./ta": 147, - "./ta.js": 147, - "./te": 148, - "./te.js": 148, - "./tet": 149, - "./tet.js": 149, - "./tg": 150, - "./tg.js": 150, - "./th": 151, - "./th.js": 151, - "./tl-ph": 152, - "./tl-ph.js": 152, - "./tlh": 153, - "./tlh.js": 153, - "./tr": 154, - "./tr.js": 154, - "./tzl": 155, - "./tzl.js": 155, - "./tzm": 156, - "./tzm-latn": 157, - "./tzm-latn.js": 157, - "./tzm.js": 156, - "./ug-cn": 158, - "./ug-cn.js": 158, - "./uk": 159, - "./uk.js": 159, - "./ur": 160, - "./ur.js": 160, - "./uz": 161, - "./uz-latn": 162, - "./uz-latn.js": 162, - "./uz.js": 161, - "./vi": 163, - "./vi.js": 163, - "./x-pseudo": 164, - "./x-pseudo.js": 164, - "./yo": 165, - "./yo.js": 165, - "./zh-cn": 166, - "./zh-cn.js": 166, - "./zh-hk": 167, - "./zh-hk.js": 167, - "./zh-tw": 168, - "./zh-tw.js": 168 -}; - - -function webpackContext(req) { - var id = webpackContextResolve(req); - return __webpack_require__(id); -} -function webpackContextResolve(req) { - if(!__webpack_require__.o(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } - return map[req]; -} -webpackContext.keys = function webpackContextKeys() { - return Object.keys(map); -}; -webpackContext.resolve = webpackContextResolve; -module.exports = webpackContext; -webpackContext.id = 41; - -/***/ }), -/* 42 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js locale configuration - -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - - - var af = moment.defineLocale('af', { - months : 'Januarie_Februarie_Maart_April_Mei_Junie_Julie_Augustus_September_Oktober_November_Desember'.split('_'), - monthsShort : 'Jan_Feb_Mrt_Apr_Mei_Jun_Jul_Aug_Sep_Okt_Nov_Des'.split('_'), - weekdays : 'Sondag_Maandag_Dinsdag_Woensdag_Donderdag_Vrydag_Saterdag'.split('_'), - weekdaysShort : 'Son_Maa_Din_Woe_Don_Vry_Sat'.split('_'), - weekdaysMin : 'So_Ma_Di_Wo_Do_Vr_Sa'.split('_'), - meridiemParse: /vm|nm/i, - isPM : function (input) { - return /^nm$/i.test(input); + var id = moment.defineLocale('id', { + months : 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember'.split('_'), + monthsShort : 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Agt_Sep_Okt_Nov_Des'.split('_'), + weekdays : 'Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu'.split('_'), + weekdaysShort : 'Min_Sen_Sel_Rab_Kam_Jum_Sab'.split('_'), + weekdaysMin : 'Mg_Sn_Sl_Rb_Km_Jm_Sb'.split('_'), + longDateFormat : { + LT : 'HH.mm', + LTS : 'HH.mm.ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY [pukul] HH.mm', + LLLL : 'dddd, D MMMM YYYY [pukul] HH.mm' + }, + meridiemParse: /pagi|siang|sore|malam/, + meridiemHour : function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'pagi') { + return hour; + } else if (meridiem === 'siang') { + return hour >= 11 ? hour : hour + 12; + } else if (meridiem === 'sore' || meridiem === 'malam') { + return hour + 12; + } }, meridiem : function (hours, minutes, isLower) { - if (hours < 12) { - return isLower ? 'vm' : 'VM'; + if (hours < 11) { + return 'pagi'; + } else if (hours < 15) { + return 'siang'; + } else if (hours < 19) { + return 'sore'; } else { - return isLower ? 'nm' : 'NM'; + return 'malam'; } }, - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd, D MMMM YYYY HH:mm' - }, calendar : { - sameDay : '[Vandag om] LT', - nextDay : '[Môre om] LT', - nextWeek : 'dddd [om] LT', - lastDay : '[Gister om] LT', - lastWeek : '[Laas] dddd [om] LT', + sameDay : '[Hari ini pukul] LT', + nextDay : '[Besok pukul] LT', + nextWeek : 'dddd [pukul] LT', + lastDay : '[Kemarin pukul] LT', + lastWeek : 'dddd [lalu pukul] LT', sameElse : 'L' }, relativeTime : { - future : 'oor %s', - past : '%s gelede', - s : '\'n paar sekondes', - ss : '%d sekondes', - m : '\'n minuut', - mm : '%d minute', - h : '\'n uur', - hh : '%d ure', - d : '\'n dag', - dd : '%d dae', - M : '\'n maand', - MM : '%d maande', - y : '\'n jaar', - yy : '%d jaar' - }, - dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, - ordinal : function (number) { - return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); // Thanks to Joris Röling : https://github.com/jjupiter + future : 'dalam %s', + past : '%s yang lalu', + s : 'beberapa detik', + ss : '%d detik', + m : 'semenit', + mm : '%d menit', + h : 'sejam', + hh : '%d jam', + d : 'sehari', + dd : '%d hari', + M : 'sebulan', + MM : '%d bulan', + y : 'setahun', + yy : '%d tahun' }, week : { - dow : 1, // Maandag is die eerste dag van die week. - doy : 4 // Die week wat die 4de Januarie bevat is die eerste week van die jaar. + dow : 1, // Monday is the first day of the week. + doy : 7 // The week that contains Jan 7th is the first week of the year. } }); - return af; + return id; }))); /***/ }), -/* 43 */ +/* 70 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var symbolMap = { - '1': '١', - '2': '٢', - '3': '٣', - '4': '٤', - '5': '٥', - '6': '٦', - '7': '٧', - '8': '٨', - '9': '٩', - '0': '٠' - }, numberMap = { - '١': '1', - '٢': '2', - '٣': '3', - '٤': '4', - '٥': '5', - '٦': '6', - '٧': '7', - '٨': '8', - '٩': '9', - '٠': '0' - }, pluralForm = function (n) { - return n === 0 ? 0 : n === 1 ? 1 : n === 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5; - }, plurals = { - s : ['أقل من ثانية', 'ثانية واحدة', ['ثانيتان', 'ثانيتين'], '%d ثوان', '%d ثانية', '%d ثانية'], - m : ['أقل من دقيقة', 'دقيقة واحدة', ['دقيقتان', 'دقيقتين'], '%d دقائق', '%d دقيقة', '%d دقيقة'], - h : ['أقل من ساعة', 'ساعة واحدة', ['ساعتان', 'ساعتين'], '%d ساعات', '%d ساعة', '%d ساعة'], - d : ['أقل من يوم', 'يوم واحد', ['يومان', 'يومين'], '%d أيام', '%d يومًا', '%d يوم'], - M : ['أقل من شهر', 'شهر واحد', ['شهران', 'شهرين'], '%d أشهر', '%d شهرا', '%d شهر'], - y : ['أقل من عام', 'عام واحد', ['عامان', 'عامين'], '%d أعوام', '%d عامًا', '%d عام'] - }, pluralize = function (u) { - return function (number, withoutSuffix, string, isFuture) { - var f = pluralForm(number), - str = plurals[u][pluralForm(number)]; - if (f === 2) { - str = str[withoutSuffix ? 0 : 1]; - } - return str.replace(/%d/i, number); - }; - }, months = [ - 'يناير', - 'فبراير', - 'مارس', - 'أبريل', - 'مايو', - 'يونيو', - 'يوليو', - 'أغسطس', - 'سبتمبر', - 'أكتوبر', - 'نوفمبر', - 'ديسمبر' - ]; + function plural(n) { + if (n % 100 === 11) { + return true; + } else if (n % 10 === 1) { + return false; + } + return true; + } + function translate(number, withoutSuffix, key, isFuture) { + var result = number + ' '; + switch (key) { + case 's': + return withoutSuffix || isFuture ? 'nokkrar sekúndur' : 'nokkrum sekúndum'; + case 'ss': + if (plural(number)) { + return result + (withoutSuffix || isFuture ? 'sekúndur' : 'sekúndum'); + } + return result + 'sekúnda'; + case 'm': + return withoutSuffix ? 'mínúta' : 'mínútu'; + case 'mm': + if (plural(number)) { + return result + (withoutSuffix || isFuture ? 'mínútur' : 'mínútum'); + } else if (withoutSuffix) { + return result + 'mínúta'; + } + return result + 'mínútu'; + case 'hh': + if (plural(number)) { + return result + (withoutSuffix || isFuture ? 'klukkustundir' : 'klukkustundum'); + } + return result + 'klukkustund'; + case 'd': + if (withoutSuffix) { + return 'dagur'; + } + return isFuture ? 'dag' : 'degi'; + case 'dd': + if (plural(number)) { + if (withoutSuffix) { + return result + 'dagar'; + } + return result + (isFuture ? 'daga' : 'dögum'); + } else if (withoutSuffix) { + return result + 'dagur'; + } + return result + (isFuture ? 'dag' : 'degi'); + case 'M': + if (withoutSuffix) { + return 'mánuður'; + } + return isFuture ? 'mánuð' : 'mánuði'; + case 'MM': + if (plural(number)) { + if (withoutSuffix) { + return result + 'mánuðir'; + } + return result + (isFuture ? 'mánuði' : 'mánuðum'); + } else if (withoutSuffix) { + return result + 'mánuður'; + } + return result + (isFuture ? 'mánuð' : 'mánuði'); + case 'y': + return withoutSuffix || isFuture ? 'ár' : 'ári'; + case 'yy': + if (plural(number)) { + return result + (withoutSuffix || isFuture ? 'ár' : 'árum'); + } + return result + (withoutSuffix || isFuture ? 'ár' : 'ári'); + } + } - var ar = moment.defineLocale('ar', { - months : months, - monthsShort : months, - weekdays : 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), - weekdaysShort : 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), - weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'), - weekdaysParseExact : true, + var is = moment.defineLocale('is', { + months : 'janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember'.split('_'), + monthsShort : 'jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des'.split('_'), + weekdays : 'sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur'.split('_'), + weekdaysShort : 'sun_mán_þri_mið_fim_fös_lau'.split('_'), + weekdaysMin : 'Su_Má_Þr_Mi_Fi_Fö_La'.split('_'), longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'D/\u200FM/\u200FYYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd D MMMM YYYY HH:mm' - }, - meridiemParse: /ص|م/, - isPM : function (input) { - return 'م' === input; - }, - meridiem : function (hour, minute, isLower) { - if (hour < 12) { - return 'ص'; - } else { - return 'م'; - } + LT : 'H:mm', + LTS : 'H:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D. MMMM YYYY', + LLL : 'D. MMMM YYYY [kl.] H:mm', + LLLL : 'dddd, D. MMMM YYYY [kl.] H:mm' }, calendar : { - sameDay: '[اليوم عند الساعة] LT', - nextDay: '[غدًا عند الساعة] LT', - nextWeek: 'dddd [عند الساعة] LT', - lastDay: '[أمس عند الساعة] LT', - lastWeek: 'dddd [عند الساعة] LT', - sameElse: 'L' + sameDay : '[í dag kl.] LT', + nextDay : '[á morgun kl.] LT', + nextWeek : 'dddd [kl.] LT', + lastDay : '[í gær kl.] LT', + lastWeek : '[síðasta] dddd [kl.] LT', + sameElse : 'L' }, relativeTime : { - future : 'بعد %s', - past : 'منذ %s', - s : pluralize('s'), - ss : pluralize('s'), - m : pluralize('m'), - mm : pluralize('m'), - h : pluralize('h'), - hh : pluralize('h'), - d : pluralize('d'), - dd : pluralize('d'), - M : pluralize('M'), - MM : pluralize('M'), - y : pluralize('y'), - yy : pluralize('y') - }, - preparse: function (string) { - return string.replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) { - return numberMap[match]; - }).replace(/،/g, ','); - }, - postformat: function (string) { - return string.replace(/\d/g, function (match) { - return symbolMap[match]; - }).replace(/,/g, '،'); + future : 'eftir %s', + past : 'fyrir %s síðan', + s : translate, + ss : translate, + m : translate, + mm : translate, + h : 'klukkustund', + hh : translate, + d : translate, + dd : translate, + M : translate, + MM : translate, + y : translate, + yy : translate }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', week : { - dow : 6, // Saturday is the first day of the week. - doy : 12 // The week that contains Jan 12th is the first week of the year. + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return ar; + return is; }))); /***/ }), -/* 44 */ +/* 71 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var arDz = moment.defineLocale('ar-dz', { - months : 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), - monthsShort : 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), - weekdays : 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), - weekdaysShort : 'احد_اثنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'), - weekdaysMin : 'أح_إث_ثلا_أر_خم_جم_سب'.split('_'), - weekdaysParseExact : true, + var it = moment.defineLocale('it', { + months : 'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre'.split('_'), + monthsShort : 'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic'.split('_'), + weekdays : 'domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato'.split('_'), + weekdaysShort : 'dom_lun_mar_mer_gio_ven_sab'.split('_'), + weekdaysMin : 'do_lu_ma_me_gi_ve_sa'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', @@ -10130,446 +11445,586 @@ webpackContext.id = 41; LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { - sameDay: '[اليوم على الساعة] LT', - nextDay: '[غدا على الساعة] LT', - nextWeek: 'dddd [على الساعة] LT', - lastDay: '[أمس على الساعة] LT', - lastWeek: 'dddd [على الساعة] LT', + sameDay: '[Oggi alle] LT', + nextDay: '[Domani alle] LT', + nextWeek: 'dddd [alle] LT', + lastDay: '[Ieri alle] LT', + lastWeek: function () { + switch (this.day()) { + case 0: + return '[la scorsa] dddd [alle] LT'; + default: + return '[lo scorso] dddd [alle] LT'; + } + }, sameElse: 'L' }, relativeTime : { - future : 'في %s', - past : 'منذ %s', - s : 'ثوان', - ss : '%d ثانية', - m : 'دقيقة', - mm : '%d دقائق', - h : 'ساعة', - hh : '%d ساعات', - d : 'يوم', - dd : '%d أيام', - M : 'شهر', - MM : '%d أشهر', - y : 'سنة', - yy : '%d سنوات' + future : function (s) { + return ((/^[0-9].+$/).test(s) ? 'tra' : 'in') + ' ' + s; + }, + past : '%s fa', + s : 'alcuni secondi', + ss : '%d secondi', + m : 'un minuto', + mm : '%d minuti', + h : 'un\'ora', + hh : '%d ore', + d : 'un giorno', + dd : '%d giorni', + M : 'un mese', + MM : '%d mesi', + y : 'un anno', + yy : '%d anni' }, + dayOfMonthOrdinalParse : /\d{1,2}º/, + ordinal: '%dº', week : { - dow : 0, // Sunday is the first day of the week. + dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return arDz; + return it; }))); /***/ }), -/* 45 */ +/* 72 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var arKw = moment.defineLocale('ar-kw', { - months : 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'), - monthsShort : 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'), - weekdays : 'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), - weekdaysShort : 'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'), - weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'), - weekdaysParseExact : true, - longDateFormat : { - LT : 'HH:mm', + var itCh = moment.defineLocale('it-ch', { + months : 'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre'.split('_'), + monthsShort : 'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic'.split('_'), + weekdays : 'domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato'.split('_'), + weekdaysShort : 'dom_lun_mar_mer_gio_ven_sab'.split('_'), + weekdaysMin : 'do_lu_ma_me_gi_ve_sa'.split('_'), + longDateFormat : { + LT : 'HH:mm', LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', + L : 'DD.MM.YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { - sameDay: '[اليوم على الساعة] LT', - nextDay: '[غدا على الساعة] LT', - nextWeek: 'dddd [على الساعة] LT', - lastDay: '[أمس على الساعة] LT', - lastWeek: 'dddd [على الساعة] LT', + sameDay: '[Oggi alle] LT', + nextDay: '[Domani alle] LT', + nextWeek: 'dddd [alle] LT', + lastDay: '[Ieri alle] LT', + lastWeek: function () { + switch (this.day()) { + case 0: + return '[la scorsa] dddd [alle] LT'; + default: + return '[lo scorso] dddd [alle] LT'; + } + }, sameElse: 'L' }, relativeTime : { - future : 'في %s', - past : 'منذ %s', - s : 'ثوان', - ss : '%d ثانية', - m : 'دقيقة', - mm : '%d دقائق', - h : 'ساعة', - hh : '%d ساعات', - d : 'يوم', - dd : '%d أيام', - M : 'شهر', - MM : '%d أشهر', - y : 'سنة', - yy : '%d سنوات' + future : function (s) { + return ((/^[0-9].+$/).test(s) ? 'tra' : 'in') + ' ' + s; + }, + past : '%s fa', + s : 'alcuni secondi', + ss : '%d secondi', + m : 'un minuto', + mm : '%d minuti', + h : 'un\'ora', + hh : '%d ore', + d : 'un giorno', + dd : '%d giorni', + M : 'un mese', + MM : '%d mesi', + y : 'un anno', + yy : '%d anni' }, + dayOfMonthOrdinalParse : /\d{1,2}º/, + ordinal: '%dº', week : { - dow : 0, // Sunday is the first day of the week. - doy : 12 // The week that contains Jan 12th is the first week of the year. + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return arKw; + return itCh; }))); /***/ }), -/* 46 */ +/* 73 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var symbolMap = { - '1': '1', - '2': '2', - '3': '3', - '4': '4', - '5': '5', - '6': '6', - '7': '7', - '8': '8', - '9': '9', - '0': '0' - }, pluralForm = function (n) { - return n === 0 ? 0 : n === 1 ? 1 : n === 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5; - }, plurals = { - s : ['أقل من ثانية', 'ثانية واحدة', ['ثانيتان', 'ثانيتين'], '%d ثوان', '%d ثانية', '%d ثانية'], - m : ['أقل من دقيقة', 'دقيقة واحدة', ['دقيقتان', 'دقيقتين'], '%d دقائق', '%d دقيقة', '%d دقيقة'], - h : ['أقل من ساعة', 'ساعة واحدة', ['ساعتان', 'ساعتين'], '%d ساعات', '%d ساعة', '%d ساعة'], - d : ['أقل من يوم', 'يوم واحد', ['يومان', 'يومين'], '%d أيام', '%d يومًا', '%d يوم'], - M : ['أقل من شهر', 'شهر واحد', ['شهران', 'شهرين'], '%d أشهر', '%d شهرا', '%d شهر'], - y : ['أقل من عام', 'عام واحد', ['عامان', 'عامين'], '%d أعوام', '%d عامًا', '%d عام'] - }, pluralize = function (u) { - return function (number, withoutSuffix, string, isFuture) { - var f = pluralForm(number), - str = plurals[u][pluralForm(number)]; - if (f === 2) { - str = str[withoutSuffix ? 0 : 1]; - } - return str.replace(/%d/i, number); - }; - }, months = [ - 'يناير', - 'فبراير', - 'مارس', - 'أبريل', - 'مايو', - 'يونيو', - 'يوليو', - 'أغسطس', - 'سبتمبر', - 'أكتوبر', - 'نوفمبر', - 'ديسمبر' - ]; - - var arLy = moment.defineLocale('ar-ly', { - months : months, - monthsShort : months, - weekdays : 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), - weekdaysShort : 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), - weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'), - weekdaysParseExact : true, + var ja = moment.defineLocale('ja', { + months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), + monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), + weekdays : '日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日'.split('_'), + weekdaysShort : '日_月_火_水_木_金_土'.split('_'), + weekdaysMin : '日_月_火_水_木_金_土'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', - L : 'D/\u200FM/\u200FYYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd D MMMM YYYY HH:mm' + L : 'YYYY/MM/DD', + LL : 'YYYY年M月D日', + LLL : 'YYYY年M月D日 HH:mm', + LLLL : 'YYYY年M月D日 dddd HH:mm', + l : 'YYYY/MM/DD', + ll : 'YYYY年M月D日', + lll : 'YYYY年M月D日 HH:mm', + llll : 'YYYY年M月D日(ddd) HH:mm' }, - meridiemParse: /ص|م/, + meridiemParse: /午前|午後/i, isPM : function (input) { - return 'م' === input; + return input === '午後'; }, meridiem : function (hour, minute, isLower) { if (hour < 12) { - return 'ص'; + return '午前'; } else { - return 'م'; + return '午後'; } }, calendar : { - sameDay: '[اليوم عند الساعة] LT', - nextDay: '[غدًا عند الساعة] LT', - nextWeek: 'dddd [عند الساعة] LT', - lastDay: '[أمس عند الساعة] LT', - lastWeek: 'dddd [عند الساعة] LT', - sameElse: 'L' - }, - relativeTime : { - future : 'بعد %s', - past : 'منذ %s', - s : pluralize('s'), - ss : pluralize('s'), - m : pluralize('m'), - mm : pluralize('m'), - h : pluralize('h'), - hh : pluralize('h'), - d : pluralize('d'), - dd : pluralize('d'), - M : pluralize('M'), - MM : pluralize('M'), - y : pluralize('y'), - yy : pluralize('y') - }, - preparse: function (string) { - return string.replace(/،/g, ','); + sameDay : '[今日] LT', + nextDay : '[明日] LT', + nextWeek : function (now) { + if (now.week() < this.week()) { + return '[来週]dddd LT'; + } else { + return 'dddd LT'; + } + }, + lastDay : '[昨日] LT', + lastWeek : function (now) { + if (this.week() < now.week()) { + return '[先週]dddd LT'; + } else { + return 'dddd LT'; + } + }, + sameElse : 'L' }, - postformat: function (string) { - return string.replace(/\d/g, function (match) { - return symbolMap[match]; - }).replace(/,/g, '،'); + dayOfMonthOrdinalParse : /\d{1,2}日/, + ordinal : function (number, period) { + switch (period) { + case 'd': + case 'D': + case 'DDD': + return number + '日'; + default: + return number; + } }, - week : { - dow : 6, // Saturday is the first day of the week. - doy : 12 // The week that contains Jan 12th is the first week of the year. + relativeTime : { + future : '%s後', + past : '%s前', + s : '数秒', + ss : '%d秒', + m : '1分', + mm : '%d分', + h : '1時間', + hh : '%d時間', + d : '1日', + dd : '%d日', + M : '1ヶ月', + MM : '%dヶ月', + y : '1年', + yy : '%d年' } }); - return arLy; + return ja; }))); /***/ }), -/* 47 */ +/* 74 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var arMa = moment.defineLocale('ar-ma', { - months : 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'), - monthsShort : 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'), - weekdays : 'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), - weekdaysShort : 'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'), - weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'), - weekdaysParseExact : true, + var jv = moment.defineLocale('jv', { + months : 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_Nopember_Desember'.split('_'), + monthsShort : 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nop_Des'.split('_'), + weekdays : 'Minggu_Senen_Seloso_Rebu_Kemis_Jemuwah_Septu'.split('_'), + weekdaysShort : 'Min_Sen_Sel_Reb_Kem_Jem_Sep'.split('_'), + weekdaysMin : 'Mg_Sn_Sl_Rb_Km_Jm_Sp'.split('_'), longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', + LT : 'HH.mm', + LTS : 'HH.mm.ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd D MMMM YYYY HH:mm' + LLL : 'D MMMM YYYY [pukul] HH.mm', + LLLL : 'dddd, D MMMM YYYY [pukul] HH.mm' + }, + meridiemParse: /enjing|siyang|sonten|ndalu/, + meridiemHour : function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'enjing') { + return hour; + } else if (meridiem === 'siyang') { + return hour >= 11 ? hour : hour + 12; + } else if (meridiem === 'sonten' || meridiem === 'ndalu') { + return hour + 12; + } + }, + meridiem : function (hours, minutes, isLower) { + if (hours < 11) { + return 'enjing'; + } else if (hours < 15) { + return 'siyang'; + } else if (hours < 19) { + return 'sonten'; + } else { + return 'ndalu'; + } }, calendar : { - sameDay: '[اليوم على الساعة] LT', - nextDay: '[غدا على الساعة] LT', - nextWeek: 'dddd [على الساعة] LT', - lastDay: '[أمس على الساعة] LT', - lastWeek: 'dddd [على الساعة] LT', - sameElse: 'L' + sameDay : '[Dinten puniko pukul] LT', + nextDay : '[Mbenjang pukul] LT', + nextWeek : 'dddd [pukul] LT', + lastDay : '[Kala wingi pukul] LT', + lastWeek : 'dddd [kepengker pukul] LT', + sameElse : 'L' }, relativeTime : { - future : 'في %s', - past : 'منذ %s', - s : 'ثوان', - ss : '%d ثانية', - m : 'دقيقة', - mm : '%d دقائق', - h : 'ساعة', - hh : '%d ساعات', - d : 'يوم', - dd : '%d أيام', - M : 'شهر', - MM : '%d أشهر', - y : 'سنة', - yy : '%d سنوات' + future : 'wonten ing %s', + past : '%s ingkang kepengker', + s : 'sawetawis detik', + ss : '%d detik', + m : 'setunggal menit', + mm : '%d menit', + h : 'setunggal jam', + hh : '%d jam', + d : 'sedinten', + dd : '%d dinten', + M : 'sewulan', + MM : '%d wulan', + y : 'setaun', + yy : '%d taun' }, week : { - dow : 6, // Saturday is the first day of the week. - doy : 12 // The week that contains Jan 12th is the first week of the year. + dow : 1, // Monday is the first day of the week. + doy : 7 // The week that contains Jan 7th is the first week of the year. } }); - return arMa; + return jv; }))); /***/ }), -/* 48 */ +/* 75 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var symbolMap = { - '1': '١', - '2': '٢', - '3': '٣', - '4': '٤', - '5': '٥', - '6': '٦', - '7': '٧', - '8': '٨', - '9': '٩', - '0': '٠' - }, numberMap = { - '١': '1', - '٢': '2', - '٣': '3', - '٤': '4', - '٥': '5', - '٦': '6', - '٧': '7', - '٨': '8', - '٩': '9', - '٠': '0' - }; - - var arSa = moment.defineLocale('ar-sa', { - months : 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), - monthsShort : 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), - weekdays : 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), - weekdaysShort : 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), - weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'), - weekdaysParseExact : true, + var ka = moment.defineLocale('ka', { + months : { + standalone: 'იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი'.split('_'), + format: 'იანვარს_თებერვალს_მარტს_აპრილის_მაისს_ივნისს_ივლისს_აგვისტს_სექტემბერს_ოქტომბერს_ნოემბერს_დეკემბერს'.split('_') + }, + monthsShort : 'იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ'.split('_'), + weekdays : { + standalone: 'კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი'.split('_'), + format: 'კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს'.split('_'), + isFormat: /(წინა|შემდეგ)/ + }, + weekdaysShort : 'კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ'.split('_'), + weekdaysMin : 'კვ_ორ_სა_ოთ_ხუ_პა_შა'.split('_'), longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', + LT : 'h:mm A', + LTS : 'h:mm:ss A', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd D MMMM YYYY HH:mm' - }, - meridiemParse: /ص|م/, - isPM : function (input) { - return 'م' === input; - }, - meridiem : function (hour, minute, isLower) { - if (hour < 12) { - return 'ص'; - } else { - return 'م'; - } + LLL : 'D MMMM YYYY h:mm A', + LLLL : 'dddd, D MMMM YYYY h:mm A' }, calendar : { - sameDay: '[اليوم على الساعة] LT', - nextDay: '[غدا على الساعة] LT', - nextWeek: 'dddd [على الساعة] LT', - lastDay: '[أمس على الساعة] LT', - lastWeek: 'dddd [على الساعة] LT', - sameElse: 'L' + sameDay : '[დღეს] LT[-ზე]', + nextDay : '[ხვალ] LT[-ზე]', + lastDay : '[გუშინ] LT[-ზე]', + nextWeek : '[შემდეგ] dddd LT[-ზე]', + lastWeek : '[წინა] dddd LT-ზე', + sameElse : 'L' }, relativeTime : { - future : 'في %s', - past : 'منذ %s', - s : 'ثوان', - ss : '%d ثانية', - m : 'دقيقة', - mm : '%d دقائق', - h : 'ساعة', - hh : '%d ساعات', - d : 'يوم', - dd : '%d أيام', - M : 'شهر', - MM : '%d أشهر', - y : 'سنة', - yy : '%d سنوات' - }, - preparse: function (string) { - return string.replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) { - return numberMap[match]; - }).replace(/،/g, ','); + future : function (s) { + return (/(წამი|წუთი|საათი|წელი)/).test(s) ? + s.replace(/ი$/, 'ში') : + s + 'ში'; + }, + past : function (s) { + if ((/(წამი|წუთი|საათი|დღე|თვე)/).test(s)) { + return s.replace(/(ი|ე)$/, 'ის წინ'); + } + if ((/წელი/).test(s)) { + return s.replace(/წელი$/, 'წლის წინ'); + } + }, + s : 'რამდენიმე წამი', + ss : '%d წამი', + m : 'წუთი', + mm : '%d წუთი', + h : 'საათი', + hh : '%d საათი', + d : 'დღე', + dd : '%d დღე', + M : 'თვე', + MM : '%d თვე', + y : 'წელი', + yy : '%d წელი' }, - postformat: function (string) { - return string.replace(/\d/g, function (match) { - return symbolMap[match]; - }).replace(/,/g, '،'); + dayOfMonthOrdinalParse: /0|1-ლი|მე-\d{1,2}|\d{1,2}-ე/, + ordinal : function (number) { + if (number === 0) { + return number; + } + if (number === 1) { + return number + '-ლი'; + } + if ((number < 20) || (number <= 100 && (number % 20 === 0)) || (number % 100 === 0)) { + return 'მე-' + number; + } + return number + '-ე'; }, week : { - dow : 0, // Sunday is the first day of the week. - doy : 6 // The week that contains Jan 6th is the first week of the year. + dow : 1, + doy : 7 } }); - return arSa; + return ka; }))); /***/ }), -/* 49 */ +/* 76 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var arTn = moment.defineLocale('ar-tn', { - months: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), - monthsShort: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), - weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), - weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), - weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), - weekdaysParseExact : true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm' + var suffixes = { + 0: '-ші', + 1: '-ші', + 2: '-ші', + 3: '-ші', + 4: '-ші', + 5: '-ші', + 6: '-шы', + 7: '-ші', + 8: '-ші', + 9: '-шы', + 10: '-шы', + 20: '-шы', + 30: '-шы', + 40: '-шы', + 50: '-ші', + 60: '-шы', + 70: '-ші', + 80: '-ші', + 90: '-шы', + 100: '-ші' + }; + + var kk = moment.defineLocale('kk', { + months : 'қаңтар_ақпан_наурыз_сәуір_мамыр_маусым_шілде_тамыз_қыркүйек_қазан_қараша_желтоқсан'.split('_'), + monthsShort : 'қаң_ақп_нау_сәу_мам_мау_шіл_там_қыр_қаз_қар_жел'.split('_'), + weekdays : 'жексенбі_дүйсенбі_сейсенбі_сәрсенбі_бейсенбі_жұма_сенбі'.split('_'), + weekdaysShort : 'жек_дүй_сей_сәр_бей_жұм_сен'.split('_'), + weekdaysMin : 'жк_дй_сй_ср_бй_жм_сн'.split('_'), + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd, D MMMM YYYY HH:mm' }, - calendar: { - sameDay: '[اليوم على الساعة] LT', - nextDay: '[غدا على الساعة] LT', - nextWeek: 'dddd [على الساعة] LT', - lastDay: '[أمس على الساعة] LT', - lastWeek: 'dddd [على الساعة] LT', + calendar : { + sameDay : '[Бүгін сағат] LT', + nextDay : '[Ертең сағат] LT', + nextWeek : 'dddd [сағат] LT', + lastDay : '[Кеше сағат] LT', + lastWeek : '[Өткен аптаның] dddd [сағат] LT', + sameElse : 'L' + }, + relativeTime : { + future : '%s ішінде', + past : '%s бұрын', + s : 'бірнеше секунд', + ss : '%d секунд', + m : 'бір минут', + mm : '%d минут', + h : 'бір сағат', + hh : '%d сағат', + d : 'бір күн', + dd : '%d күн', + M : 'бір ай', + MM : '%d ай', + y : 'бір жыл', + yy : '%d жыл' + }, + dayOfMonthOrdinalParse: /\d{1,2}-(ші|шы)/, + ordinal : function (number) { + var a = number % 10, + b = number >= 100 ? 100 : null; + return number + (suffixes[number] || suffixes[a] || suffixes[b]); + }, + week : { + dow : 1, // Monday is the first day of the week. + doy : 7 // The week that contains Jan 7th is the first week of the year. + } + }); + + return kk; + +}))); + + +/***/ }), +/* 77 */ +/***/ (function(module, exports, __webpack_require__) { + +//! moment.js locale configuration + +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; + + + var symbolMap = { + '1': '១', + '2': '២', + '3': '៣', + '4': '៤', + '5': '៥', + '6': '៦', + '7': '៧', + '8': '៨', + '9': '៩', + '0': '០' + }, numberMap = { + '១': '1', + '២': '2', + '៣': '3', + '៤': '4', + '៥': '5', + '៦': '6', + '៧': '7', + '៨': '8', + '៩': '9', + '០': '0' + }; + + var km = moment.defineLocale('km', { + months: 'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split( + '_' + ), + monthsShort: 'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split( + '_' + ), + weekdays: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'), + weekdaysShort: 'អា_ច_អ_ព_ព្រ_សុ_ស'.split('_'), + weekdaysMin: 'អា_ច_អ_ព_ព្រ_សុ_ស'.split('_'), + weekdaysParseExact: true, + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd, D MMMM YYYY HH:mm' + }, + meridiemParse: /ព្រឹក|ល្ងាច/, + isPM: function (input) { + return input === 'ល្ងាច'; + }, + meridiem: function (hour, minute, isLower) { + if (hour < 12) { + return 'ព្រឹក'; + } else { + return 'ល្ងាច'; + } + }, + calendar: { + sameDay: '[ថ្ងៃនេះ ម៉ោង] LT', + nextDay: '[ស្អែក ម៉ោង] LT', + nextWeek: 'dddd [ម៉ោង] LT', + lastDay: '[ម្សិលមិញ ម៉ោង] LT', + lastWeek: 'dddd [សប្តាហ៍មុន] [ម៉ោង] LT', sameElse: 'L' }, relativeTime: { - future: 'في %s', - past: 'منذ %s', - s: 'ثوان', - ss : '%d ثانية', - m: 'دقيقة', - mm: '%d دقائق', - h: 'ساعة', - hh: '%d ساعات', - d: 'يوم', - dd: '%d أيام', - M: 'شهر', - MM: '%d أشهر', - y: 'سنة', - yy: '%d سنوات' + future: '%sទៀត', + past: '%sមុន', + s: 'ប៉ុន្មានវិនាទី', + ss: '%d វិនាទី', + m: 'មួយនាទី', + mm: '%d នាទី', + h: 'មួយម៉ោង', + hh: '%d ម៉ោង', + d: 'មួយថ្ងៃ', + dd: '%d ថ្ងៃ', + M: 'មួយខែ', + MM: '%d ខែ', + y: 'មួយឆ្នាំ', + yy: '%d ឆ្នាំ' + }, + dayOfMonthOrdinalParse : /ទី\d{1,2}/, + ordinal : 'ទី%d', + preparse: function (string) { + return string.replace(/[១២៣៤៥៦៧៨៩០]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); }, week: { dow: 1, // Monday is the first day of the week. @@ -10577,857 +12032,926 @@ webpackContext.id = 41; } }); - return arTn; + return km; }))); /***/ }), -/* 50 */ +/* 78 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var suffixes = { - 1: '-inci', - 5: '-inci', - 8: '-inci', - 70: '-inci', - 80: '-inci', - 2: '-nci', - 7: '-nci', - 20: '-nci', - 50: '-nci', - 3: '-üncü', - 4: '-üncü', - 100: '-üncü', - 6: '-ncı', - 9: '-uncu', - 10: '-uncu', - 30: '-uncu', - 60: '-ıncı', - 90: '-ıncı' + var symbolMap = { + '1': '೧', + '2': '೨', + '3': '೩', + '4': '೪', + '5': '೫', + '6': '೬', + '7': '೭', + '8': '೮', + '9': '೯', + '0': '೦' + }, + numberMap = { + '೧': '1', + '೨': '2', + '೩': '3', + '೪': '4', + '೫': '5', + '೬': '6', + '೭': '7', + '೮': '8', + '೯': '9', + '೦': '0' }; - var az = moment.defineLocale('az', { - months : 'yanvar_fevral_mart_aprel_may_iyun_iyul_avqust_sentyabr_oktyabr_noyabr_dekabr'.split('_'), - monthsShort : 'yan_fev_mar_apr_may_iyn_iyl_avq_sen_okt_noy_dek'.split('_'), - weekdays : 'Bazar_Bazar ertəsi_Çərşənbə axşamı_Çərşənbə_Cümə axşamı_Cümə_Şənbə'.split('_'), - weekdaysShort : 'Baz_BzE_ÇAx_Çər_CAx_Cüm_Şən'.split('_'), - weekdaysMin : 'Bz_BE_ÇA_Çə_CA_Cü_Şə'.split('_'), - weekdaysParseExact : true, + var kn = moment.defineLocale('kn', { + months : 'ಜನವರಿ_ಫೆಬ್ರವರಿ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂಬರ್_ಅಕ್ಟೋಬರ್_ನವೆಂಬರ್_ಡಿಸೆಂಬರ್'.split('_'), + monthsShort : 'ಜನ_ಫೆಬ್ರ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂ_ಅಕ್ಟೋ_ನವೆಂ_ಡಿಸೆಂ'.split('_'), + monthsParseExact: true, + weekdays : 'ಭಾನುವಾರ_ಸೋಮವಾರ_ಮಂಗಳವಾರ_ಬುಧವಾರ_ಗುರುವಾರ_ಶುಕ್ರವಾರ_ಶನಿವಾರ'.split('_'), + weekdaysShort : 'ಭಾನು_ಸೋಮ_ಮಂಗಳ_ಬುಧ_ಗುರು_ಶುಕ್ರ_ಶನಿ'.split('_'), + weekdaysMin : 'ಭಾ_ಸೋ_ಮಂ_ಬು_ಗು_ಶು_ಶ'.split('_'), longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD.MM.YYYY', + LT : 'A h:mm', + LTS : 'A h:mm:ss', + L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd, D MMMM YYYY HH:mm' + LLL : 'D MMMM YYYY, A h:mm', + LLLL : 'dddd, D MMMM YYYY, A h:mm' }, calendar : { - sameDay : '[bugün saat] LT', - nextDay : '[sabah saat] LT', - nextWeek : '[gələn həftə] dddd [saat] LT', - lastDay : '[dünən] LT', - lastWeek : '[keçən həftə] dddd [saat] LT', + sameDay : '[ಇಂದು] LT', + nextDay : '[ನಾಳೆ] LT', + nextWeek : 'dddd, LT', + lastDay : '[ನಿನ್ನೆ] LT', + lastWeek : '[ಕೊನೆಯ] dddd, LT', sameElse : 'L' }, relativeTime : { - future : '%s sonra', - past : '%s əvvəl', - s : 'birneçə saniyə', - ss : '%d saniyə', - m : 'bir dəqiqə', - mm : '%d dəqiqə', - h : 'bir saat', - hh : '%d saat', - d : 'bir gün', - dd : '%d gün', - M : 'bir ay', - MM : '%d ay', - y : 'bir il', - yy : '%d il' + future : '%s ನಂತರ', + past : '%s ಹಿಂದೆ', + s : 'ಕೆಲವು ಕ್ಷಣಗಳು', + ss : '%d ಸೆಕೆಂಡುಗಳು', + m : 'ಒಂದು ನಿಮಿಷ', + mm : '%d ನಿಮಿಷ', + h : 'ಒಂದು ಗಂಟೆ', + hh : '%d ಗಂಟೆ', + d : 'ಒಂದು ದಿನ', + dd : '%d ದಿನ', + M : 'ಒಂದು ತಿಂಗಳು', + MM : '%d ತಿಂಗಳು', + y : 'ಒಂದು ವರ್ಷ', + yy : '%d ವರ್ಷ' }, - meridiemParse: /gecə|səhər|gündüz|axşam/, - isPM : function (input) { - return /^(gündüz|axşam)$/.test(input); + preparse: function (string) { + return string.replace(/[೧೨೩೪೫೬೭೮೯೦]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + meridiemParse: /ರಾತ್ರಿ|ಬೆಳಿಗ್ಗೆ|ಮಧ್ಯಾಹ್ನ|ಸಂಜೆ/, + meridiemHour : function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'ರಾತ್ರಿ') { + return hour < 4 ? hour : hour + 12; + } else if (meridiem === 'ಬೆಳಿಗ್ಗೆ') { + return hour; + } else if (meridiem === 'ಮಧ್ಯಾಹ್ನ') { + return hour >= 10 ? hour : hour + 12; + } else if (meridiem === 'ಸಂಜೆ') { + return hour + 12; + } }, meridiem : function (hour, minute, isLower) { if (hour < 4) { - return 'gecə'; - } else if (hour < 12) { - return 'səhər'; + return 'ರಾತ್ರಿ'; + } else if (hour < 10) { + return 'ಬೆಳಿಗ್ಗೆ'; } else if (hour < 17) { - return 'gündüz'; + return 'ಮಧ್ಯಾಹ್ನ'; + } else if (hour < 20) { + return 'ಸಂಜೆ'; } else { - return 'axşam'; + return 'ರಾತ್ರಿ'; } }, - dayOfMonthOrdinalParse: /\d{1,2}-(ıncı|inci|nci|üncü|ncı|uncu)/, + dayOfMonthOrdinalParse: /\d{1,2}(ನೇ)/, ordinal : function (number) { - if (number === 0) { // special case for zero - return number + '-ıncı'; - } - var a = number % 10, - b = number % 100 - a, - c = number >= 100 ? 100 : null; - return number + (suffixes[a] || suffixes[b] || suffixes[c]); + return number + 'ನೇ'; }, week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. + dow : 0, // Sunday is the first day of the week. + doy : 6 // The week that contains Jan 6th is the first week of the year. } }); - return az; + return kn; }))); /***/ }), -/* 51 */ +/* 79 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - function plural(word, num) { - var forms = word.split('_'); - return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); - } - function relativeTimeWithPlural(number, withoutSuffix, key) { - var format = { - 'ss': withoutSuffix ? 'секунда_секунды_секунд' : 'секунду_секунды_секунд', - 'mm': withoutSuffix ? 'хвіліна_хвіліны_хвілін' : 'хвіліну_хвіліны_хвілін', - 'hh': withoutSuffix ? 'гадзіна_гадзіны_гадзін' : 'гадзіну_гадзіны_гадзін', - 'dd': 'дзень_дні_дзён', - 'MM': 'месяц_месяцы_месяцаў', - 'yy': 'год_гады_гадоў' - }; - if (key === 'm') { - return withoutSuffix ? 'хвіліна' : 'хвіліну'; - } - else if (key === 'h') { - return withoutSuffix ? 'гадзіна' : 'гадзіну'; - } - else { - return number + ' ' + plural(format[key], +number); - } - } - - var be = moment.defineLocale('be', { - months : { - format: 'студзеня_лютага_сакавіка_красавіка_траўня_чэрвеня_ліпеня_жніўня_верасня_кастрычніка_лістапада_снежня'.split('_'), - standalone: 'студзень_люты_сакавік_красавік_травень_чэрвень_ліпень_жнівень_верасень_кастрычнік_лістапад_снежань'.split('_') - }, - monthsShort : 'студ_лют_сак_крас_трав_чэрв_ліп_жнів_вер_каст_ліст_снеж'.split('_'), - weekdays : { - format: 'нядзелю_панядзелак_аўторак_сераду_чацвер_пятніцу_суботу'.split('_'), - standalone: 'нядзеля_панядзелак_аўторак_серада_чацвер_пятніца_субота'.split('_'), - isFormat: /\[ ?[Ууў] ?(?:мінулую|наступную)? ?\] ?dddd/ - }, - weekdaysShort : 'нд_пн_ат_ср_чц_пт_сб'.split('_'), - weekdaysMin : 'нд_пн_ат_ср_чц_пт_сб'.split('_'), + var ko = moment.defineLocale('ko', { + months : '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'), + monthsShort : '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'), + weekdays : '일요일_월요일_화요일_수요일_목요일_금요일_토요일'.split('_'), + weekdaysShort : '일_월_화_수_목_금_토'.split('_'), + weekdaysMin : '일_월_화_수_목_금_토'.split('_'), longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D MMMM YYYY г.', - LLL : 'D MMMM YYYY г., HH:mm', - LLLL : 'dddd, D MMMM YYYY г., HH:mm' + LT : 'A h:mm', + LTS : 'A h:mm:ss', + L : 'YYYY.MM.DD.', + LL : 'YYYY년 MMMM D일', + LLL : 'YYYY년 MMMM D일 A h:mm', + LLLL : 'YYYY년 MMMM D일 dddd A h:mm', + l : 'YYYY.MM.DD.', + ll : 'YYYY년 MMMM D일', + lll : 'YYYY년 MMMM D일 A h:mm', + llll : 'YYYY년 MMMM D일 dddd A h:mm' }, calendar : { - sameDay: '[Сёння ў] LT', - nextDay: '[Заўтра ў] LT', - lastDay: '[Учора ў] LT', - nextWeek: function () { - return '[У] dddd [ў] LT'; - }, - lastWeek: function () { - switch (this.day()) { - case 0: - case 3: - case 5: - case 6: - return '[У мінулую] dddd [ў] LT'; - case 1: - case 2: - case 4: - return '[У мінулы] dddd [ў] LT'; - } - }, - sameElse: 'L' + sameDay : '오늘 LT', + nextDay : '내일 LT', + nextWeek : 'dddd LT', + lastDay : '어제 LT', + lastWeek : '지난주 dddd LT', + sameElse : 'L' }, relativeTime : { - future : 'праз %s', - past : '%s таму', - s : 'некалькі секунд', - m : relativeTimeWithPlural, - mm : relativeTimeWithPlural, - h : relativeTimeWithPlural, - hh : relativeTimeWithPlural, - d : 'дзень', - dd : relativeTimeWithPlural, - M : 'месяц', - MM : relativeTimeWithPlural, - y : 'год', - yy : relativeTimeWithPlural - }, - meridiemParse: /ночы|раніцы|дня|вечара/, - isPM : function (input) { - return /^(дня|вечара)$/.test(input); - }, - meridiem : function (hour, minute, isLower) { - if (hour < 4) { - return 'ночы'; - } else if (hour < 12) { - return 'раніцы'; - } else if (hour < 17) { - return 'дня'; - } else { - return 'вечара'; - } + future : '%s 후', + past : '%s 전', + s : '몇 초', + ss : '%d초', + m : '1분', + mm : '%d분', + h : '한 시간', + hh : '%d시간', + d : '하루', + dd : '%d일', + M : '한 달', + MM : '%d달', + y : '일 년', + yy : '%d년' }, - dayOfMonthOrdinalParse: /\d{1,2}-(і|ы|га)/, - ordinal: function (number, period) { + dayOfMonthOrdinalParse : /\d{1,2}(일|월|주)/, + ordinal : function (number, period) { switch (period) { - case 'M': case 'd': + case 'D': case 'DDD': + return number + '일'; + case 'M': + return number + '월'; case 'w': case 'W': - return (number % 10 === 2 || number % 10 === 3) && (number % 100 !== 12 && number % 100 !== 13) ? number + '-і' : number + '-ы'; - case 'D': - return number + '-га'; + return number + '주'; default: return number; } }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. + meridiemParse : /오전|오후/, + isPM : function (token) { + return token === '오후'; + }, + meridiem : function (hour, minute, isUpper) { + return hour < 12 ? '오전' : '오후'; } }); - return be; + return ko; }))); /***/ }), -/* 52 */ +/* 80 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var bg = moment.defineLocale('bg', { - months : 'януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември'.split('_'), - monthsShort : 'янр_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек'.split('_'), - weekdays : 'неделя_понеделник_вторник_сряда_четвъртък_петък_събота'.split('_'), - weekdaysShort : 'нед_пон_вто_сря_чет_пет_съб'.split('_'), - weekdaysMin : 'нд_пн_вт_ср_чт_пт_сб'.split('_'), - longDateFormat : { - LT : 'H:mm', - LTS : 'H:mm:ss', - L : 'D.MM.YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY H:mm', - LLLL : 'dddd, D MMMM YYYY H:mm' - }, - calendar : { - sameDay : '[Днес в] LT', - nextDay : '[Утре в] LT', - nextWeek : 'dddd [в] LT', - lastDay : '[Вчера в] LT', - lastWeek : function () { - switch (this.day()) { - case 0: - case 3: - case 6: - return '[В изминалата] dddd [в] LT'; - case 1: - case 2: - case 4: - case 5: - return '[В изминалия] dddd [в] LT'; - } - }, - sameElse : 'L' - }, - relativeTime : { - future : 'след %s', - past : 'преди %s', - s : 'няколко секунди', - ss : '%d секунди', - m : 'минута', - mm : '%d минути', - h : 'час', - hh : '%d часа', - d : 'ден', - dd : '%d дни', - M : 'месец', - MM : '%d месеца', - y : 'година', - yy : '%d години' + var symbolMap = { + '1': '١', + '2': '٢', + '3': '٣', + '4': '٤', + '5': '٥', + '6': '٦', + '7': '٧', + '8': '٨', + '9': '٩', + '0': '٠' + }, numberMap = { + '١': '1', + '٢': '2', + '٣': '3', + '٤': '4', + '٥': '5', + '٦': '6', + '٧': '7', + '٨': '8', + '٩': '9', + '٠': '0' + }, + months = [ + 'کانونی دووەم', + 'شوبات', + 'ئازار', + 'نیسان', + 'ئایار', + 'حوزەیران', + 'تەمموز', + 'ئاب', + 'ئەیلوول', + 'تشرینی یەكەم', + 'تشرینی دووەم', + 'كانونی یەکەم' + ]; + + + var ku = moment.defineLocale('ku', { + months : months, + monthsShort : months, + weekdays : 'یه‌كشه‌ممه‌_دووشه‌ممه‌_سێشه‌ممه‌_چوارشه‌ممه‌_پێنجشه‌ممه‌_هه‌ینی_شه‌ممه‌'.split('_'), + weekdaysShort : 'یه‌كشه‌م_دووشه‌م_سێشه‌م_چوارشه‌م_پێنجشه‌م_هه‌ینی_شه‌ممه‌'.split('_'), + weekdaysMin : 'ی_د_س_چ_پ_ه_ش'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd, D MMMM YYYY HH:mm' }, - dayOfMonthOrdinalParse: /\d{1,2}-(ев|ен|ти|ви|ри|ми)/, - ordinal : function (number) { - var lastDigit = number % 10, - last2Digits = number % 100; - if (number === 0) { - return number + '-ев'; - } else if (last2Digits === 0) { - return number + '-ен'; - } else if (last2Digits > 10 && last2Digits < 20) { - return number + '-ти'; - } else if (lastDigit === 1) { - return number + '-ви'; - } else if (lastDigit === 2) { - return number + '-ри'; - } else if (lastDigit === 7 || lastDigit === 8) { - return number + '-ми'; + meridiemParse: /ئێواره‌|به‌یانی/, + isPM: function (input) { + return /ئێواره‌/.test(input); + }, + meridiem : function (hour, minute, isLower) { + if (hour < 12) { + return 'به‌یانی'; } else { - return number + '-ти'; + return 'ئێواره‌'; } }, + calendar : { + sameDay : '[ئه‌مرۆ كاتژمێر] LT', + nextDay : '[به‌یانی كاتژمێر] LT', + nextWeek : 'dddd [كاتژمێر] LT', + lastDay : '[دوێنێ كاتژمێر] LT', + lastWeek : 'dddd [كاتژمێر] LT', + sameElse : 'L' + }, + relativeTime : { + future : 'له‌ %s', + past : '%s', + s : 'چه‌ند چركه‌یه‌ك', + ss : 'چركه‌ %d', + m : 'یه‌ك خوله‌ك', + mm : '%d خوله‌ك', + h : 'یه‌ك كاتژمێر', + hh : '%d كاتژمێر', + d : 'یه‌ك ڕۆژ', + dd : '%d ڕۆژ', + M : 'یه‌ك مانگ', + MM : '%d مانگ', + y : 'یه‌ك ساڵ', + yy : '%d ساڵ' + }, + preparse: function (string) { + return string.replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) { + return numberMap[match]; + }).replace(/،/g, ','); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }).replace(/,/g, '،'); + }, week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. + dow : 6, // Saturday is the first day of the week. + doy : 12 // The week that contains Jan 12th is the first week of the year. } }); - return bg; + return ku; }))); /***/ }), -/* 53 */ +/* 81 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var bm = moment.defineLocale('bm', { - months : 'Zanwuyekalo_Fewuruyekalo_Marisikalo_Awirilikalo_Mɛkalo_Zuwɛnkalo_Zuluyekalo_Utikalo_Sɛtanburukalo_ɔkutɔburukalo_Nowanburukalo_Desanburukalo'.split('_'), - monthsShort : 'Zan_Few_Mar_Awi_Mɛ_Zuw_Zul_Uti_Sɛt_ɔku_Now_Des'.split('_'), - weekdays : 'Kari_Ntɛnɛn_Tarata_Araba_Alamisa_Juma_Sibiri'.split('_'), - weekdaysShort : 'Kar_Ntɛ_Tar_Ara_Ala_Jum_Sib'.split('_'), - weekdaysMin : 'Ka_Nt_Ta_Ar_Al_Ju_Si'.split('_'), + var suffixes = { + 0: '-чү', + 1: '-чи', + 2: '-чи', + 3: '-чү', + 4: '-чү', + 5: '-чи', + 6: '-чы', + 7: '-чи', + 8: '-чи', + 9: '-чу', + 10: '-чу', + 20: '-чы', + 30: '-чу', + 40: '-чы', + 50: '-чү', + 60: '-чы', + 70: '-чи', + 80: '-чи', + 90: '-чу', + 100: '-чү' + }; + + var ky = moment.defineLocale('ky', { + months : 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'), + monthsShort : 'янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_'), + weekdays : 'Жекшемби_Дүйшөмбү_Шейшемби_Шаршемби_Бейшемби_Жума_Ишемби'.split('_'), + weekdaysShort : 'Жек_Дүй_Шей_Шар_Бей_Жум_Ише'.split('_'), + weekdaysMin : 'Жк_Дй_Шй_Шр_Бй_Жм_Иш'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'MMMM [tile] D [san] YYYY', - LLL : 'MMMM [tile] D [san] YYYY [lɛrɛ] HH:mm', - LLLL : 'dddd MMMM [tile] D [san] YYYY [lɛrɛ] HH:mm' + L : 'DD.MM.YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { - sameDay : '[Bi lɛrɛ] LT', - nextDay : '[Sini lɛrɛ] LT', - nextWeek : 'dddd [don lɛrɛ] LT', - lastDay : '[Kunu lɛrɛ] LT', - lastWeek : 'dddd [tɛmɛnen lɛrɛ] LT', + sameDay : '[Бүгүн саат] LT', + nextDay : '[Эртең саат] LT', + nextWeek : 'dddd [саат] LT', + lastDay : '[Кечээ саат] LT', + lastWeek : '[Өткөн аптанын] dddd [күнү] [саат] LT', sameElse : 'L' }, relativeTime : { - future : '%s kɔnɔ', - past : 'a bɛ %s bɔ', - s : 'sanga dama dama', - ss : 'sekondi %d', - m : 'miniti kelen', - mm : 'miniti %d', - h : 'lɛrɛ kelen', - hh : 'lɛrɛ %d', - d : 'tile kelen', - dd : 'tile %d', - M : 'kalo kelen', - MM : 'kalo %d', - y : 'san kelen', - yy : 'san %d' + future : '%s ичинде', + past : '%s мурун', + s : 'бирнече секунд', + ss : '%d секунд', + m : 'бир мүнөт', + mm : '%d мүнөт', + h : 'бир саат', + hh : '%d саат', + d : 'бир күн', + dd : '%d күн', + M : 'бир ай', + MM : '%d ай', + y : 'бир жыл', + yy : '%d жыл' + }, + dayOfMonthOrdinalParse: /\d{1,2}-(чи|чы|чү|чу)/, + ordinal : function (number) { + var a = number % 10, + b = number >= 100 ? 100 : null; + return number + (suffixes[number] || suffixes[a] || suffixes[b]); }, week : { dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + doy : 7 // The week that contains Jan 7th is the first week of the year. } }); - return bm; + return ky; }))); /***/ }), -/* 54 */ +/* 82 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var symbolMap = { - '1': '১', - '2': '২', - '3': '৩', - '4': '৪', - '5': '৫', - '6': '৬', - '7': '৭', - '8': '৮', - '9': '৯', - '0': '০' - }, - numberMap = { - '১': '1', - '২': '2', - '৩': '3', - '৪': '4', - '৫': '5', - '৬': '6', - '৭': '7', - '৮': '8', - '৯': '9', - '০': '0' - }; - - var bn = moment.defineLocale('bn', { - months : 'জানুয়ারী_ফেব্রুয়ারি_মার্চ_এপ্রিল_মে_জুন_জুলাই_আগস্ট_সেপ্টেম্বর_অক্টোবর_নভেম্বর_ডিসেম্বর'.split('_'), - monthsShort : 'জানু_ফেব_মার্চ_এপ্র_মে_জুন_জুল_আগ_সেপ্ট_অক্টো_নভে_ডিসে'.split('_'), - weekdays : 'রবিবার_সোমবার_মঙ্গলবার_বুধবার_বৃহস্পতিবার_শুক্রবার_শনিবার'.split('_'), - weekdaysShort : 'রবি_সোম_মঙ্গল_বুধ_বৃহস্পতি_শুক্র_শনি'.split('_'), - weekdaysMin : 'রবি_সোম_মঙ্গ_বুধ_বৃহঃ_শুক্র_শনি'.split('_'), - longDateFormat : { - LT : 'A h:mm সময়', - LTS : 'A h:mm:ss সময়', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY, A h:mm সময়', - LLLL : 'dddd, D MMMM YYYY, A h:mm সময়' - }, - calendar : { - sameDay : '[আজ] LT', - nextDay : '[আগামীকাল] LT', - nextWeek : 'dddd, LT', - lastDay : '[গতকাল] LT', - lastWeek : '[গত] dddd, LT', - sameElse : 'L' - }, - relativeTime : { - future : '%s পরে', - past : '%s আগে', - s : 'কয়েক সেকেন্ড', - ss : '%d সেকেন্ড', - m : 'এক মিনিট', - mm : '%d মিনিট', - h : 'এক ঘন্টা', - hh : '%d ঘন্টা', - d : 'এক দিন', - dd : '%d দিন', - M : 'এক মাস', - MM : '%d মাস', - y : 'এক বছর', - yy : '%d বছর' - }, - preparse: function (string) { - return string.replace(/[১২৩৪৫৬৭৮৯০]/g, function (match) { - return numberMap[match]; - }); - }, - postformat: function (string) { - return string.replace(/\d/g, function (match) { - return symbolMap[match]; - }); - }, - meridiemParse: /রাত|সকাল|দুপুর|বিকাল|রাত/, - meridiemHour : function (hour, meridiem) { - if (hour === 12) { - hour = 0; + function processRelativeTime(number, withoutSuffix, key, isFuture) { + var format = { + 'm': ['eng Minutt', 'enger Minutt'], + 'h': ['eng Stonn', 'enger Stonn'], + 'd': ['een Dag', 'engem Dag'], + 'M': ['ee Mount', 'engem Mount'], + 'y': ['ee Joer', 'engem Joer'] + }; + return withoutSuffix ? format[key][0] : format[key][1]; + } + function processFutureTime(string) { + var number = string.substr(0, string.indexOf(' ')); + if (eifelerRegelAppliesToNumber(number)) { + return 'a ' + string; + } + return 'an ' + string; + } + function processPastTime(string) { + var number = string.substr(0, string.indexOf(' ')); + if (eifelerRegelAppliesToNumber(number)) { + return 'viru ' + string; + } + return 'virun ' + string; + } + /** + * Returns true if the word before the given number loses the '-n' ending. + * e.g. 'an 10 Deeg' but 'a 5 Deeg' + * + * @param number {integer} + * @returns {boolean} + */ + function eifelerRegelAppliesToNumber(number) { + number = parseInt(number, 10); + if (isNaN(number)) { + return false; + } + if (number < 0) { + // Negative Number --> always true + return true; + } else if (number < 10) { + // Only 1 digit + if (4 <= number && number <= 7) { + return true; } - if ((meridiem === 'রাত' && hour >= 4) || - (meridiem === 'দুপুর' && hour < 5) || - meridiem === 'বিকাল') { - return hour + 12; - } else { - return hour; + return false; + } else if (number < 100) { + // 2 digits + var lastDigit = number % 10, firstDigit = number / 10; + if (lastDigit === 0) { + return eifelerRegelAppliesToNumber(firstDigit); + } + return eifelerRegelAppliesToNumber(lastDigit); + } else if (number < 10000) { + // 3 or 4 digits --> recursively check first digit + while (number >= 10) { + number = number / 10; } + return eifelerRegelAppliesToNumber(number); + } else { + // Anything larger than 4 digits: recursively check first n-3 digits + number = number / 1000; + return eifelerRegelAppliesToNumber(number); + } + } + + var lb = moment.defineLocale('lb', { + months: 'Januar_Februar_Mäerz_Abrëll_Mee_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), + monthsShort: 'Jan._Febr._Mrz._Abr._Mee_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'), + monthsParseExact : true, + weekdays: 'Sonndeg_Méindeg_Dënschdeg_Mëttwoch_Donneschdeg_Freideg_Samschdeg'.split('_'), + weekdaysShort: 'So._Mé._Dë._Më._Do._Fr._Sa.'.split('_'), + weekdaysMin: 'So_Mé_Dë_Më_Do_Fr_Sa'.split('_'), + weekdaysParseExact : true, + longDateFormat: { + LT: 'H:mm [Auer]', + LTS: 'H:mm:ss [Auer]', + L: 'DD.MM.YYYY', + LL: 'D. MMMM YYYY', + LLL: 'D. MMMM YYYY H:mm [Auer]', + LLLL: 'dddd, D. MMMM YYYY H:mm [Auer]' }, - meridiem : function (hour, minute, isLower) { - if (hour < 4) { - return 'রাত'; - } else if (hour < 10) { - return 'সকাল'; - } else if (hour < 17) { - return 'দুপুর'; - } else if (hour < 20) { - return 'বিকাল'; - } else { - return 'রাত'; + calendar: { + sameDay: '[Haut um] LT', + sameElse: 'L', + nextDay: '[Muer um] LT', + nextWeek: 'dddd [um] LT', + lastDay: '[Gëschter um] LT', + lastWeek: function () { + // Different date string for 'Dënschdeg' (Tuesday) and 'Donneschdeg' (Thursday) due to phonological rule + switch (this.day()) { + case 2: + case 4: + return '[Leschten] dddd [um] LT'; + default: + return '[Leschte] dddd [um] LT'; + } } }, - week : { - dow : 0, // Sunday is the first day of the week. - doy : 6 // The week that contains Jan 6th is the first week of the year. + relativeTime : { + future : processFutureTime, + past : processPastTime, + s : 'e puer Sekonnen', + ss : '%d Sekonnen', + m : processRelativeTime, + mm : '%d Minutten', + h : processRelativeTime, + hh : '%d Stonnen', + d : processRelativeTime, + dd : '%d Deeg', + M : processRelativeTime, + MM : '%d Méint', + y : processRelativeTime, + yy : '%d Joer' + }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal: '%d.', + week: { + dow: 1, // Monday is the first day of the week. + doy: 4 // The week that contains Jan 4th is the first week of the year. } }); - return bn; + return lb; }))); /***/ }), -/* 55 */ +/* 83 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var symbolMap = { - '1': '༡', - '2': '༢', - '3': '༣', - '4': '༤', - '5': '༥', - '6': '༦', - '7': '༧', - '8': '༨', - '9': '༩', - '0': '༠' - }, - numberMap = { - '༡': '1', - '༢': '2', - '༣': '3', - '༤': '4', - '༥': '5', - '༦': '6', - '༧': '7', - '༨': '8', - '༩': '9', - '༠': '0' - }; - - var bo = moment.defineLocale('bo', { - months : 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split('_'), - monthsShort : 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split('_'), - weekdays : 'གཟའ་ཉི་མ་_གཟའ་ཟླ་བ་_གཟའ་མིག་དམར་_གཟའ་ལྷག་པ་_གཟའ་ཕུར་བུ_གཟའ་པ་སངས་_གཟའ་སྤེན་པ་'.split('_'), - weekdaysShort : 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split('_'), - weekdaysMin : 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split('_'), + var lo = moment.defineLocale('lo', { + months : 'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split('_'), + monthsShort : 'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split('_'), + weekdays : 'ອາທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'), + weekdaysShort : 'ທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'), + weekdaysMin : 'ທ_ຈ_ອຄ_ພ_ພຫ_ສກ_ສ'.split('_'), + weekdaysParseExact : true, longDateFormat : { - LT : 'A h:mm', - LTS : 'A h:mm:ss', + LT : 'HH:mm', + LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY, A h:mm', - LLLL : 'dddd, D MMMM YYYY, A h:mm' + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'ວັນdddd D MMMM YYYY HH:mm' + }, + meridiemParse: /ຕອນເຊົ້າ|ຕອນແລງ/, + isPM: function (input) { + return input === 'ຕອນແລງ'; + }, + meridiem : function (hour, minute, isLower) { + if (hour < 12) { + return 'ຕອນເຊົ້າ'; + } else { + return 'ຕອນແລງ'; + } }, calendar : { - sameDay : '[དི་རིང] LT', - nextDay : '[སང་ཉིན] LT', - nextWeek : '[བདུན་ཕྲག་རྗེས་མ], LT', - lastDay : '[ཁ་སང] LT', - lastWeek : '[བདུན་ཕྲག་མཐའ་མ] dddd, LT', + sameDay : '[ມື້ນີ້ເວລາ] LT', + nextDay : '[ມື້ອື່ນເວລາ] LT', + nextWeek : '[ວັນ]dddd[ໜ້າເວລາ] LT', + lastDay : '[ມື້ວານນີ້ເວລາ] LT', + lastWeek : '[ວັນ]dddd[ແລ້ວນີ້ເວລາ] LT', sameElse : 'L' }, relativeTime : { - future : '%s ལ་', - past : '%s སྔན་ལ', - s : 'ལམ་སང', - ss : '%d སྐར་ཆ།', - m : 'སྐར་མ་གཅིག', - mm : '%d སྐར་མ', - h : 'ཆུ་ཚོད་གཅིག', - hh : '%d ཆུ་ཚོད', - d : 'ཉིན་གཅིག', - dd : '%d ཉིན་', - M : 'ཟླ་བ་གཅིག', - MM : '%d ཟླ་བ', - y : 'ལོ་གཅིག', - yy : '%d ལོ' - }, - preparse: function (string) { - return string.replace(/[༡༢༣༤༥༦༧༨༩༠]/g, function (match) { - return numberMap[match]; - }); - }, - postformat: function (string) { - return string.replace(/\d/g, function (match) { - return symbolMap[match]; - }); + future : 'ອີກ %s', + past : '%sຜ່ານມາ', + s : 'ບໍ່ເທົ່າໃດວິນາທີ', + ss : '%d ວິນາທີ' , + m : '1 ນາທີ', + mm : '%d ນາທີ', + h : '1 ຊົ່ວໂມງ', + hh : '%d ຊົ່ວໂມງ', + d : '1 ມື້', + dd : '%d ມື້', + M : '1 ເດືອນ', + MM : '%d ເດືອນ', + y : '1 ປີ', + yy : '%d ປີ' }, - meridiemParse: /མཚན་མོ|ཞོགས་ཀས|ཉིན་གུང|དགོང་དག|མཚན་མོ/, - meridiemHour : function (hour, meridiem) { - if (hour === 12) { - hour = 0; - } - if ((meridiem === 'མཚན་མོ' && hour >= 4) || - (meridiem === 'ཉིན་གུང' && hour < 5) || - meridiem === 'དགོང་དག') { - return hour + 12; + dayOfMonthOrdinalParse: /(ທີ່)\d{1,2}/, + ordinal : function (number) { + return 'ທີ່' + number; + } + }); + + return lo; + +}))); + + +/***/ }), +/* 84 */ +/***/ (function(module, exports, __webpack_require__) { + +//! moment.js locale configuration + +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; + + + var units = { + 'ss' : 'sekundė_sekundžių_sekundes', + 'm' : 'minutė_minutės_minutę', + 'mm': 'minutės_minučių_minutes', + 'h' : 'valanda_valandos_valandą', + 'hh': 'valandos_valandų_valandas', + 'd' : 'diena_dienos_dieną', + 'dd': 'dienos_dienų_dienas', + 'M' : 'mėnuo_mėnesio_mėnesį', + 'MM': 'mėnesiai_mėnesių_mėnesius', + 'y' : 'metai_metų_metus', + 'yy': 'metai_metų_metus' + }; + function translateSeconds(number, withoutSuffix, key, isFuture) { + if (withoutSuffix) { + return 'kelios sekundės'; + } else { + return isFuture ? 'kelių sekundžių' : 'kelias sekundes'; + } + } + function translateSingular(number, withoutSuffix, key, isFuture) { + return withoutSuffix ? forms(key)[0] : (isFuture ? forms(key)[1] : forms(key)[2]); + } + function special(number) { + return number % 10 === 0 || (number > 10 && number < 20); + } + function forms(key) { + return units[key].split('_'); + } + function translate(number, withoutSuffix, key, isFuture) { + var result = number + ' '; + if (number === 1) { + return result + translateSingular(number, withoutSuffix, key[0], isFuture); + } else if (withoutSuffix) { + return result + (special(number) ? forms(key)[1] : forms(key)[0]); + } else { + if (isFuture) { + return result + forms(key)[1]; } else { - return hour; + return result + (special(number) ? forms(key)[1] : forms(key)[2]); } + } + } + var lt = moment.defineLocale('lt', { + months : { + format: 'sausio_vasario_kovo_balandžio_gegužės_birželio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio'.split('_'), + standalone: 'sausis_vasaris_kovas_balandis_gegužė_birželis_liepa_rugpjūtis_rugsėjis_spalis_lapkritis_gruodis'.split('_'), + isFormat: /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?|MMMM?(\[[^\[\]]*\]|\s)+D[oD]?/ }, - meridiem : function (hour, minute, isLower) { - if (hour < 4) { - return 'མཚན་མོ'; - } else if (hour < 10) { - return 'ཞོགས་ཀས'; - } else if (hour < 17) { - return 'ཉིན་གུང'; - } else if (hour < 20) { - return 'དགོང་དག'; - } else { - return 'མཚན་མོ'; - } + monthsShort : 'sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd'.split('_'), + weekdays : { + format: 'sekmadienį_pirmadienį_antradienį_trečiadienį_ketvirtadienį_penktadienį_šeštadienį'.split('_'), + standalone: 'sekmadienis_pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis'.split('_'), + isFormat: /dddd HH:mm/ + }, + weekdaysShort : 'Sek_Pir_Ant_Tre_Ket_Pen_Šeš'.split('_'), + weekdaysMin : 'S_P_A_T_K_Pn_Š'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'YYYY-MM-DD', + LL : 'YYYY [m.] MMMM D [d.]', + LLL : 'YYYY [m.] MMMM D [d.], HH:mm [val.]', + LLLL : 'YYYY [m.] MMMM D [d.], dddd, HH:mm [val.]', + l : 'YYYY-MM-DD', + ll : 'YYYY [m.] MMMM D [d.]', + lll : 'YYYY [m.] MMMM D [d.], HH:mm [val.]', + llll : 'YYYY [m.] MMMM D [d.], ddd, HH:mm [val.]' + }, + calendar : { + sameDay : '[Šiandien] LT', + nextDay : '[Rytoj] LT', + nextWeek : 'dddd LT', + lastDay : '[Vakar] LT', + lastWeek : '[Praėjusį] dddd LT', + sameElse : 'L' + }, + relativeTime : { + future : 'po %s', + past : 'prieš %s', + s : translateSeconds, + ss : translate, + m : translateSingular, + mm : translate, + h : translateSingular, + hh : translate, + d : translateSingular, + dd : translate, + M : translateSingular, + MM : translate, + y : translateSingular, + yy : translate + }, + dayOfMonthOrdinalParse: /\d{1,2}-oji/, + ordinal : function (number) { + return number + '-oji'; }, week : { - dow : 0, // Sunday is the first day of the week. - doy : 6 // The week that contains Jan 6th is the first week of the year. + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return bo; + return lt; }))); /***/ }), -/* 56 */ +/* 85 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - function relativeTimeWithMutation(number, withoutSuffix, key) { - var format = { - 'mm': 'munutenn', - 'MM': 'miz', - 'dd': 'devezh' - }; - return number + ' ' + mutation(format[key], number); - } - function specialMutationForYears(number) { - switch (lastNumber(number)) { - case 1: - case 3: - case 4: - case 5: - case 9: - return number + ' bloaz'; - default: - return number + ' vloaz'; + var units = { + 'ss': 'sekundes_sekundēm_sekunde_sekundes'.split('_'), + 'm': 'minūtes_minūtēm_minūte_minūtes'.split('_'), + 'mm': 'minūtes_minūtēm_minūte_minūtes'.split('_'), + 'h': 'stundas_stundām_stunda_stundas'.split('_'), + 'hh': 'stundas_stundām_stunda_stundas'.split('_'), + 'd': 'dienas_dienām_diena_dienas'.split('_'), + 'dd': 'dienas_dienām_diena_dienas'.split('_'), + 'M': 'mēneša_mēnešiem_mēnesis_mēneši'.split('_'), + 'MM': 'mēneša_mēnešiem_mēnesis_mēneši'.split('_'), + 'y': 'gada_gadiem_gads_gadi'.split('_'), + 'yy': 'gada_gadiem_gads_gadi'.split('_') + }; + /** + * @param withoutSuffix boolean true = a length of time; false = before/after a period of time. + */ + function format(forms, number, withoutSuffix) { + if (withoutSuffix) { + // E.g. "21 minūte", "3 minūtes". + return number % 10 === 1 && number % 100 !== 11 ? forms[2] : forms[3]; + } else { + // E.g. "21 minūtes" as in "pēc 21 minūtes". + // E.g. "3 minūtēm" as in "pēc 3 minūtēm". + return number % 10 === 1 && number % 100 !== 11 ? forms[0] : forms[1]; } } - function lastNumber(number) { - if (number > 9) { - return lastNumber(number % 10); - } - return number; + function relativeTimeWithPlural(number, withoutSuffix, key) { + return number + ' ' + format(units[key], number, withoutSuffix); } - function mutation(text, number) { - if (number === 2) { - return softMutation(text); - } - return text; + function relativeTimeWithSingular(number, withoutSuffix, key) { + return format(units[key], number, withoutSuffix); } - function softMutation(text) { - var mutationTable = { - 'm': 'v', - 'b': 'v', - 'd': 'z' - }; - if (mutationTable[text.charAt(0)] === undefined) { - return text; - } - return mutationTable[text.charAt(0)] + text.substring(1); + function relativeSeconds(number, withoutSuffix) { + return withoutSuffix ? 'dažas sekundes' : 'dažām sekundēm'; } - var br = moment.defineLocale('br', { - months : 'Genver_C\'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu'.split('_'), - monthsShort : 'Gen_C\'hwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker'.split('_'), - weekdays : 'Sul_Lun_Meurzh_Merc\'her_Yaou_Gwener_Sadorn'.split('_'), - weekdaysShort : 'Sul_Lun_Meu_Mer_Yao_Gwe_Sad'.split('_'), - weekdaysMin : 'Su_Lu_Me_Mer_Ya_Gw_Sa'.split('_'), + var lv = moment.defineLocale('lv', { + months : 'janvāris_februāris_marts_aprīlis_maijs_jūnijs_jūlijs_augusts_septembris_oktobris_novembris_decembris'.split('_'), + monthsShort : 'jan_feb_mar_apr_mai_jūn_jūl_aug_sep_okt_nov_dec'.split('_'), + weekdays : 'svētdiena_pirmdiena_otrdiena_trešdiena_ceturtdiena_piektdiena_sestdiena'.split('_'), + weekdaysShort : 'Sv_P_O_T_C_Pk_S'.split('_'), + weekdaysMin : 'Sv_P_O_T_C_Pk_S'.split('_'), weekdaysParseExact : true, longDateFormat : { - LT : 'h[e]mm A', - LTS : 'h[e]mm:ss A', - L : 'DD/MM/YYYY', - LL : 'D [a viz] MMMM YYYY', - LLL : 'D [a viz] MMMM YYYY h[e]mm A', - LLLL : 'dddd, D [a viz] MMMM YYYY h[e]mm A' + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD.MM.YYYY.', + LL : 'YYYY. [gada] D. MMMM', + LLL : 'YYYY. [gada] D. MMMM, HH:mm', + LLLL : 'YYYY. [gada] D. MMMM, dddd, HH:mm' }, calendar : { - sameDay : '[Hiziv da] LT', - nextDay : '[Warc\'hoazh da] LT', - nextWeek : 'dddd [da] LT', - lastDay : '[Dec\'h da] LT', - lastWeek : 'dddd [paset da] LT', + sameDay : '[Šodien pulksten] LT', + nextDay : '[Rīt pulksten] LT', + nextWeek : 'dddd [pulksten] LT', + lastDay : '[Vakar pulksten] LT', + lastWeek : '[Pagājušā] dddd [pulksten] LT', sameElse : 'L' }, relativeTime : { - future : 'a-benn %s', - past : '%s \'zo', - s : 'un nebeud segondennoù', - ss : '%d eilenn', - m : 'ur vunutenn', - mm : relativeTimeWithMutation, - h : 'un eur', - hh : '%d eur', - d : 'un devezh', - dd : relativeTimeWithMutation, - M : 'ur miz', - MM : relativeTimeWithMutation, - y : 'ur bloaz', - yy : specialMutationForYears - }, - dayOfMonthOrdinalParse: /\d{1,2}(añ|vet)/, - ordinal : function (number) { - var output = (number === 1) ? 'añ' : 'vet'; - return number + output; + future : 'pēc %s', + past : 'pirms %s', + s : relativeSeconds, + ss : relativeTimeWithPlural, + m : relativeTimeWithSingular, + mm : relativeTimeWithPlural, + h : relativeTimeWithSingular, + hh : relativeTimeWithPlural, + d : relativeTimeWithSingular, + dd : relativeTimeWithPlural, + M : relativeTimeWithSingular, + MM : relativeTimeWithPlural, + y : relativeTimeWithSingular, + yy : relativeTimeWithPlural }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return br; + return lv; }))); /***/ }), -/* 57 */ +/* 86 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - function translate(number, withoutSuffix, key) { - var result = number + ' '; - switch (key) { - case 'ss': - if (number === 1) { - result += 'sekunda'; - } else if (number === 2 || number === 3 || number === 4) { - result += 'sekunde'; - } else { - result += 'sekundi'; - } - return result; - case 'm': - return withoutSuffix ? 'jedna minuta' : 'jedne minute'; - case 'mm': - if (number === 1) { - result += 'minuta'; - } else if (number === 2 || number === 3 || number === 4) { - result += 'minute'; - } else { - result += 'minuta'; - } - return result; - case 'h': - return withoutSuffix ? 'jedan sat' : 'jednog sata'; - case 'hh': - if (number === 1) { - result += 'sat'; - } else if (number === 2 || number === 3 || number === 4) { - result += 'sata'; - } else { - result += 'sati'; - } - return result; - case 'dd': - if (number === 1) { - result += 'dan'; - } else { - result += 'dana'; - } - return result; - case 'MM': - if (number === 1) { - result += 'mjesec'; - } else if (number === 2 || number === 3 || number === 4) { - result += 'mjeseca'; - } else { - result += 'mjeseci'; - } - return result; - case 'yy': - if (number === 1) { - result += 'godina'; - } else if (number === 2 || number === 3 || number === 4) { - result += 'godine'; - } else { - result += 'godina'; - } - return result; + var translator = { + words: { //Different grammatical cases + ss: ['sekund', 'sekunda', 'sekundi'], + m: ['jedan minut', 'jednog minuta'], + mm: ['minut', 'minuta', 'minuta'], + h: ['jedan sat', 'jednog sata'], + hh: ['sat', 'sata', 'sati'], + dd: ['dan', 'dana', 'dana'], + MM: ['mjesec', 'mjeseca', 'mjeseci'], + yy: ['godina', 'godine', 'godina'] + }, + correctGrammaticalCase: function (number, wordKey) { + return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]); + }, + translate: function (number, withoutSuffix, key) { + var wordKey = translator.words[key]; + if (key.length === 1) { + return withoutSuffix ? wordKey[0] : wordKey[1]; + } else { + return number + ' ' + translator.correctGrammaticalCase(number, wordKey); + } } - } + }; - var bs = moment.defineLocale('bs', { - months : 'januar_februar_mart_april_maj_juni_juli_august_septembar_oktobar_novembar_decembar'.split('_'), - monthsShort : 'jan._feb._mar._apr._maj._jun._jul._aug._sep._okt._nov._dec.'.split('_'), - monthsParseExact: true, - weekdays : 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'), - weekdaysShort : 'ned._pon._uto._sri._čet._pet._sub.'.split('_'), - weekdaysMin : 'ne_po_ut_sr_če_pe_su'.split('_'), + var me = moment.defineLocale('me', { + months: 'januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar'.split('_'), + monthsShort: 'jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.'.split('_'), + monthsParseExact : true, + weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'), + weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'), + weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'), weekdaysParseExact : true, - longDateFormat : { - LT : 'H:mm', + longDateFormat: { + LT: 'H:mm', LTS : 'H:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D. MMMM YYYY', - LLL : 'D. MMMM YYYY H:mm', - LLLL : 'dddd, D. MMMM YYYY H:mm' + L: 'DD.MM.YYYY', + LL: 'D. MMMM YYYY', + LLL: 'D. MMMM YYYY H:mm', + LLLL: 'dddd, D. MMMM YYYY H:mm' }, - calendar : { - sameDay : '[danas u] LT', - nextDay : '[sutra u] LT', - nextWeek : function () { + calendar: { + sameDay: '[danas u] LT', + nextDay: '[sjutra u] LT', + + nextWeek: function () { switch (this.day()) { case 0: return '[u] [nedjelju] [u] LT'; @@ -11442,38 +12966,36 @@ webpackContext.id = 41; return '[u] dddd [u] LT'; } }, - lastDay : '[jučer u] LT', + lastDay : '[juče u] LT', lastWeek : function () { - switch (this.day()) { - case 0: - case 3: - return '[prošlu] dddd [u] LT'; - case 6: - return '[prošle] [subote] [u] LT'; - case 1: - case 2: - case 4: - case 5: - return '[prošli] dddd [u] LT'; - } + var lastWeekDays = [ + '[prošle] [nedjelje] [u] LT', + '[prošlog] [ponedjeljka] [u] LT', + '[prošlog] [utorka] [u] LT', + '[prošle] [srijede] [u] LT', + '[prošlog] [četvrtka] [u] LT', + '[prošlog] [petka] [u] LT', + '[prošle] [subote] [u] LT' + ]; + return lastWeekDays[this.day()]; }, sameElse : 'L' }, relativeTime : { future : 'za %s', past : 'prije %s', - s : 'par sekundi', - ss : translate, - m : translate, - mm : translate, - h : translate, - hh : translate, + s : 'nekoliko sekundi', + ss : translator.translate, + m : translator.translate, + mm : translator.translate, + h : translator.translate, + hh : translator.translate, d : 'dan', - dd : translate, + dd : translator.translate, M : 'mjesec', - MM : translate, + MM : translator.translate, y : 'godinu', - yy : translate + yy : translator.translate }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', @@ -11483,1059 +13005,1123 @@ webpackContext.id = 41; } }); - return bs; + return me; }))); /***/ }), -/* 58 */ +/* 87 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var ca = moment.defineLocale('ca', { - months : { - standalone: 'gener_febrer_març_abril_maig_juny_juliol_agost_setembre_octubre_novembre_desembre'.split('_'), - format: 'de gener_de febrer_de març_d\'abril_de maig_de juny_de juliol_d\'agost_de setembre_d\'octubre_de novembre_de desembre'.split('_'), - isFormat: /D[oD]?(\s)+MMMM/ + var mi = moment.defineLocale('mi', { + months: 'Kohi-tāte_Hui-tanguru_Poutū-te-rangi_Paenga-whāwhā_Haratua_Pipiri_Hōngoingoi_Here-turi-kōkā_Mahuru_Whiringa-ā-nuku_Whiringa-ā-rangi_Hakihea'.split('_'), + monthsShort: 'Kohi_Hui_Pou_Pae_Hara_Pipi_Hōngoi_Here_Mahu_Whi-nu_Whi-ra_Haki'.split('_'), + monthsRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i, + monthsStrictRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i, + monthsShortRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i, + monthsShortStrictRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,2}/i, + weekdays: 'Rātapu_Mane_Tūrei_Wenerei_Tāite_Paraire_Hātarei'.split('_'), + weekdaysShort: 'Ta_Ma_Tū_We_Tāi_Pa_Hā'.split('_'), + weekdaysMin: 'Ta_Ma_Tū_We_Tāi_Pa_Hā'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY [i] HH:mm', + LLLL: 'dddd, D MMMM YYYY [i] HH:mm' }, - monthsShort : 'gen._febr._març_abr._maig_juny_jul._ag._set._oct._nov._des.'.split('_'), - monthsParseExact : true, - weekdays : 'diumenge_dilluns_dimarts_dimecres_dijous_divendres_dissabte'.split('_'), - weekdaysShort : 'dg._dl._dt._dc._dj._dv._ds.'.split('_'), - weekdaysMin : 'dg_dl_dt_dc_dj_dv_ds'.split('_'), - weekdaysParseExact : true, - longDateFormat : { - LT : 'H:mm', - LTS : 'H:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM [de] YYYY', - ll : 'D MMM YYYY', - LLL : 'D MMMM [de] YYYY [a les] H:mm', - lll : 'D MMM YYYY, H:mm', - LLLL : 'dddd D MMMM [de] YYYY [a les] H:mm', - llll : 'ddd D MMM YYYY, H:mm' - }, - calendar : { - sameDay : function () { - return '[avui a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; - }, - nextDay : function () { - return '[demà a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; - }, - nextWeek : function () { - return 'dddd [a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; - }, - lastDay : function () { - return '[ahir a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; - }, - lastWeek : function () { - return '[el] dddd [passat a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; - }, - sameElse : 'L' - }, - relativeTime : { - future : 'd\'aquí %s', - past : 'fa %s', - s : 'uns segons', - ss : '%d segons', - m : 'un minut', - mm : '%d minuts', - h : 'una hora', - hh : '%d hores', - d : 'un dia', - dd : '%d dies', - M : 'un mes', - MM : '%d mesos', - y : 'un any', - yy : '%d anys' + calendar: { + sameDay: '[i teie mahana, i] LT', + nextDay: '[apopo i] LT', + nextWeek: 'dddd [i] LT', + lastDay: '[inanahi i] LT', + lastWeek: 'dddd [whakamutunga i] LT', + sameElse: 'L' }, - dayOfMonthOrdinalParse: /\d{1,2}(r|n|t|è|a)/, - ordinal : function (number, period) { - var output = (number === 1) ? 'r' : - (number === 2) ? 'n' : - (number === 3) ? 'r' : - (number === 4) ? 't' : 'è'; - if (period === 'w' || period === 'W') { - output = 'a'; - } - return number + output; + relativeTime: { + future: 'i roto i %s', + past: '%s i mua', + s: 'te hēkona ruarua', + ss: '%d hēkona', + m: 'he meneti', + mm: '%d meneti', + h: 'te haora', + hh: '%d haora', + d: 'he ra', + dd: '%d ra', + M: 'he marama', + MM: '%d marama', + y: 'he tau', + yy: '%d tau' }, + dayOfMonthOrdinalParse: /\d{1,2}º/, + ordinal: '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return ca; + return mi; }))); /***/ }), -/* 59 */ +/* 88 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var months = 'leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec'.split('_'), - monthsShort = 'led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro'.split('_'); - - var monthsParse = [/^led/i, /^úno/i, /^bře/i, /^dub/i, /^kvě/i, /^(čvn|červen$|června)/i, /^(čvc|červenec|července)/i, /^srp/i, /^zář/i, /^říj/i, /^lis/i, /^pro/i]; - // NOTE: 'červen' is substring of 'červenec'; therefore 'červenec' must precede 'červen' in the regex to be fully matched. - // Otherwise parser matches '1. červenec' as '1. červen' + 'ec'. - var monthsRegex = /^(leden|únor|březen|duben|květen|červenec|července|červen|června|srpen|září|říjen|listopad|prosinec|led|úno|bře|dub|kvě|čvn|čvc|srp|zář|říj|lis|pro)/i; - - function plural(n) { - return (n > 1) && (n < 5) && (~~(n / 10) !== 1); - } - function translate(number, withoutSuffix, key, isFuture) { - var result = number + ' '; - switch (key) { - case 's': // a few seconds / in a few seconds / a few seconds ago - return (withoutSuffix || isFuture) ? 'pár sekund' : 'pár sekundami'; - case 'ss': // 9 seconds / in 9 seconds / 9 seconds ago - if (withoutSuffix || isFuture) { - return result + (plural(number) ? 'sekundy' : 'sekund'); - } else { - return result + 'sekundami'; - } - break; - case 'm': // a minute / in a minute / a minute ago - return withoutSuffix ? 'minuta' : (isFuture ? 'minutu' : 'minutou'); - case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago - if (withoutSuffix || isFuture) { - return result + (plural(number) ? 'minuty' : 'minut'); - } else { - return result + 'minutami'; - } - break; - case 'h': // an hour / in an hour / an hour ago - return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou'); - case 'hh': // 9 hours / in 9 hours / 9 hours ago - if (withoutSuffix || isFuture) { - return result + (plural(number) ? 'hodiny' : 'hodin'); - } else { - return result + 'hodinami'; - } - break; - case 'd': // a day / in a day / a day ago - return (withoutSuffix || isFuture) ? 'den' : 'dnem'; - case 'dd': // 9 days / in 9 days / 9 days ago - if (withoutSuffix || isFuture) { - return result + (plural(number) ? 'dny' : 'dní'); - } else { - return result + 'dny'; - } - break; - case 'M': // a month / in a month / a month ago - return (withoutSuffix || isFuture) ? 'měsíc' : 'měsícem'; - case 'MM': // 9 months / in 9 months / 9 months ago - if (withoutSuffix || isFuture) { - return result + (plural(number) ? 'měsíce' : 'měsíců'); - } else { - return result + 'měsíci'; - } - break; - case 'y': // a year / in a year / a year ago - return (withoutSuffix || isFuture) ? 'rok' : 'rokem'; - case 'yy': // 9 years / in 9 years / 9 years ago - if (withoutSuffix || isFuture) { - return result + (plural(number) ? 'roky' : 'let'); - } else { - return result + 'lety'; - } - break; - } - } - - var cs = moment.defineLocale('cs', { - months : months, - monthsShort : monthsShort, - monthsRegex : monthsRegex, - monthsShortRegex : monthsRegex, - // NOTE: 'červen' is substring of 'červenec'; therefore 'červenec' must precede 'červen' in the regex to be fully matched. - // Otherwise parser matches '1. červenec' as '1. červen' + 'ec'. - monthsStrictRegex : /^(leden|ledna|února|únor|březen|března|duben|dubna|květen|května|červenec|července|červen|června|srpen|srpna|září|říjen|října|listopadu|listopad|prosinec|prosince)/i, - monthsShortStrictRegex : /^(led|úno|bře|dub|kvě|čvn|čvc|srp|zář|říj|lis|pro)/i, - monthsParse : monthsParse, - longMonthsParse : monthsParse, - shortMonthsParse : monthsParse, - weekdays : 'neděle_pondělí_úterý_středa_čtvrtek_pátek_sobota'.split('_'), - weekdaysShort : 'ne_po_út_st_čt_pá_so'.split('_'), - weekdaysMin : 'ne_po_út_st_čt_pá_so'.split('_'), + var mk = moment.defineLocale('mk', { + months : 'јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември'.split('_'), + monthsShort : 'јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек'.split('_'), + weekdays : 'недела_понеделник_вторник_среда_четврток_петок_сабота'.split('_'), + weekdaysShort : 'нед_пон_вто_сре_чет_пет_саб'.split('_'), + weekdaysMin : 'нe_пo_вт_ср_че_пе_сa'.split('_'), longDateFormat : { - LT: 'H:mm', + LT : 'H:mm', LTS : 'H:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D. MMMM YYYY', - LLL : 'D. MMMM YYYY H:mm', - LLLL : 'dddd D. MMMM YYYY H:mm', - l : 'D. M. YYYY' + L : 'D.MM.YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY H:mm', + LLLL : 'dddd, D MMMM YYYY H:mm' }, calendar : { - sameDay: '[dnes v] LT', - nextDay: '[zítra v] LT', - nextWeek: function () { + sameDay : '[Денес во] LT', + nextDay : '[Утре во] LT', + nextWeek : '[Во] dddd [во] LT', + lastDay : '[Вчера во] LT', + lastWeek : function () { switch (this.day()) { case 0: - return '[v neděli v] LT'; - case 1: - case 2: - return '[v] dddd [v] LT'; case 3: - return '[ve středu v] LT'; - case 4: - return '[ve čtvrtek v] LT'; - case 5: - return '[v pátek v] LT'; case 6: - return '[v sobotu v] LT'; - } - }, - lastDay: '[včera v] LT', - lastWeek: function () { - switch (this.day()) { - case 0: - return '[minulou neděli v] LT'; + return '[Изминатата] dddd [во] LT'; case 1: case 2: - return '[minulé] dddd [v] LT'; - case 3: - return '[minulou středu v] LT'; case 4: case 5: - return '[minulý] dddd [v] LT'; - case 6: - return '[minulou sobotu v] LT'; + return '[Изминатиот] dddd [во] LT'; } }, - sameElse: 'L' + sameElse : 'L' }, relativeTime : { - future : 'za %s', - past : 'před %s', - s : translate, - ss : translate, - m : translate, - mm : translate, - h : translate, - hh : translate, - d : translate, - dd : translate, - M : translate, - MM : translate, - y : translate, - yy : translate + future : 'после %s', + past : 'пред %s', + s : 'неколку секунди', + ss : '%d секунди', + m : 'минута', + mm : '%d минути', + h : 'час', + hh : '%d часа', + d : 'ден', + dd : '%d дена', + M : 'месец', + MM : '%d месеци', + y : 'година', + yy : '%d години' + }, + dayOfMonthOrdinalParse: /\d{1,2}-(ев|ен|ти|ви|ри|ми)/, + ordinal : function (number) { + var lastDigit = number % 10, + last2Digits = number % 100; + if (number === 0) { + return number + '-ев'; + } else if (last2Digits === 0) { + return number + '-ен'; + } else if (last2Digits > 10 && last2Digits < 20) { + return number + '-ти'; + } else if (lastDigit === 1) { + return number + '-ви'; + } else if (lastDigit === 2) { + return number + '-ри'; + } else if (lastDigit === 7 || lastDigit === 8) { + return number + '-ми'; + } else { + return number + '-ти'; + } }, - dayOfMonthOrdinalParse : /\d{1,2}\./, - ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + doy : 7 // The week that contains Jan 7th is the first week of the year. } }); - return cs; + return mk; }))); /***/ }), -/* 60 */ +/* 89 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var cv = moment.defineLocale('cv', { - months : 'кӑрлач_нарӑс_пуш_ака_май_ҫӗртме_утӑ_ҫурла_авӑн_юпа_чӳк_раштав'.split('_'), - monthsShort : 'кӑр_нар_пуш_ака_май_ҫӗр_утӑ_ҫур_авн_юпа_чӳк_раш'.split('_'), - weekdays : 'вырсарникун_тунтикун_ытларикун_юнкун_кӗҫнерникун_эрнекун_шӑматкун'.split('_'), - weekdaysShort : 'выр_тун_ытл_юн_кӗҫ_эрн_шӑм'.split('_'), - weekdaysMin : 'вр_тн_ыт_юн_кҫ_эр_шм'.split('_'), + var ml = moment.defineLocale('ml', { + months : 'ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ'.split('_'), + monthsShort : 'ജനു._ഫെബ്രു._മാർ._ഏപ്രി._മേയ്_ജൂൺ_ജൂലൈ._ഓഗ._സെപ്റ്റ._ഒക്ടോ._നവം._ഡിസം.'.split('_'), + monthsParseExact : true, + weekdays : 'ഞായറാഴ്ച_തിങ്കളാഴ്ച_ചൊവ്വാഴ്ച_ബുധനാഴ്ച_വ്യാഴാഴ്ച_വെള്ളിയാഴ്ച_ശനിയാഴ്ച'.split('_'), + weekdaysShort : 'ഞായർ_തിങ്കൾ_ചൊവ്വ_ബുധൻ_വ്യാഴം_വെള്ളി_ശനി'.split('_'), + weekdaysMin : 'ഞാ_തി_ചൊ_ബു_വ്യാ_വെ_ശ'.split('_'), longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD-MM-YYYY', - LL : 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ]', - LLL : 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm', - LLLL : 'dddd, YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm' + LT : 'A h:mm -നു', + LTS : 'A h:mm:ss -നു', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY, A h:mm -നു', + LLLL : 'dddd, D MMMM YYYY, A h:mm -നു' }, calendar : { - sameDay: '[Паян] LT [сехетре]', - nextDay: '[Ыран] LT [сехетре]', - lastDay: '[Ӗнер] LT [сехетре]', - nextWeek: '[Ҫитес] dddd LT [сехетре]', - lastWeek: '[Иртнӗ] dddd LT [сехетре]', - sameElse: 'L' + sameDay : '[ഇന്ന്] LT', + nextDay : '[നാളെ] LT', + nextWeek : 'dddd, LT', + lastDay : '[ഇന്നലെ] LT', + lastWeek : '[കഴിഞ്ഞ] dddd, LT', + sameElse : 'L' }, relativeTime : { - future : function (output) { - var affix = /сехет$/i.exec(output) ? 'рен' : /ҫул$/i.exec(output) ? 'тан' : 'ран'; - return output + affix; - }, - past : '%s каялла', - s : 'пӗр-ик ҫеккунт', - ss : '%d ҫеккунт', - m : 'пӗр минут', - mm : '%d минут', - h : 'пӗр сехет', - hh : '%d сехет', - d : 'пӗр кун', - dd : '%d кун', - M : 'пӗр уйӑх', - MM : '%d уйӑх', - y : 'пӗр ҫул', - yy : '%d ҫул' - }, - dayOfMonthOrdinalParse: /\d{1,2}-мӗш/, - ordinal : '%d-мӗш', - week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. - } - }); - - return cv; - -}))); - - -/***/ }), -/* 61 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js locale configuration - -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - - - var cy = moment.defineLocale('cy', { - months: 'Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr'.split('_'), - monthsShort: 'Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag'.split('_'), - weekdays: 'Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn'.split('_'), - weekdaysShort: 'Sul_Llun_Maw_Mer_Iau_Gwe_Sad'.split('_'), - weekdaysMin: 'Su_Ll_Ma_Me_Ia_Gw_Sa'.split('_'), - weekdaysParseExact : true, - // time formats are the same as en-gb - longDateFormat: { - LT: 'HH:mm', - LTS : 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm' - }, - calendar: { - sameDay: '[Heddiw am] LT', - nextDay: '[Yfory am] LT', - nextWeek: 'dddd [am] LT', - lastDay: '[Ddoe am] LT', - lastWeek: 'dddd [diwethaf am] LT', - sameElse: 'L' - }, - relativeTime: { - future: 'mewn %s', - past: '%s yn ôl', - s: 'ychydig eiliadau', - ss: '%d eiliad', - m: 'munud', - mm: '%d munud', - h: 'awr', - hh: '%d awr', - d: 'diwrnod', - dd: '%d diwrnod', - M: 'mis', - MM: '%d mis', - y: 'blwyddyn', - yy: '%d flynedd' + future : '%s കഴിഞ്ഞ്', + past : '%s മുൻപ്', + s : 'അൽപ നിമിഷങ്ങൾ', + ss : '%d സെക്കൻഡ്', + m : 'ഒരു മിനിറ്റ്', + mm : '%d മിനിറ്റ്', + h : 'ഒരു മണിക്കൂർ', + hh : '%d മണിക്കൂർ', + d : 'ഒരു ദിവസം', + dd : '%d ദിവസം', + M : 'ഒരു മാസം', + MM : '%d മാസം', + y : 'ഒരു വർഷം', + yy : '%d വർഷം' }, - dayOfMonthOrdinalParse: /\d{1,2}(fed|ain|af|il|ydd|ed|eg)/, - // traditional ordinal numbers above 31 are not commonly used in colloquial Welsh - ordinal: function (number) { - var b = number, - output = '', - lookup = [ - '', 'af', 'il', 'ydd', 'ydd', 'ed', 'ed', 'ed', 'fed', 'fed', 'fed', // 1af to 10fed - 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'fed' // 11eg to 20fed - ]; - if (b > 20) { - if (b === 40 || b === 50 || b === 60 || b === 80 || b === 100) { - output = 'fed'; // not 30ain, 70ain or 90ain - } else { - output = 'ain'; - } - } else if (b > 0) { - output = lookup[b]; + meridiemParse: /രാത്രി|രാവിലെ|ഉച്ച കഴിഞ്ഞ്|വൈകുന്നേരം|രാത്രി/i, + meridiemHour : function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if ((meridiem === 'രാത്രി' && hour >= 4) || + meridiem === 'ഉച്ച കഴിഞ്ഞ്' || + meridiem === 'വൈകുന്നേരം') { + return hour + 12; + } else { + return hour; } - return number + output; }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + meridiem : function (hour, minute, isLower) { + if (hour < 4) { + return 'രാത്രി'; + } else if (hour < 12) { + return 'രാവിലെ'; + } else if (hour < 17) { + return 'ഉച്ച കഴിഞ്ഞ്'; + } else if (hour < 20) { + return 'വൈകുന്നേരം'; + } else { + return 'രാത്രി'; + } } }); - return cy; + return ml; }))); /***/ }), -/* 62 */ +/* 90 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var da = moment.defineLocale('da', { - months : 'januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december'.split('_'), - monthsShort : 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'), - weekdays : 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'), - weekdaysShort : 'søn_man_tir_ons_tor_fre_lør'.split('_'), - weekdaysMin : 'sø_ma_ti_on_to_fr_lø'.split('_'), + function translate(number, withoutSuffix, key, isFuture) { + switch (key) { + case 's': + return withoutSuffix ? 'хэдхэн секунд' : 'хэдхэн секундын'; + case 'ss': + return number + (withoutSuffix ? ' секунд' : ' секундын'); + case 'm': + case 'mm': + return number + (withoutSuffix ? ' минут' : ' минутын'); + case 'h': + case 'hh': + return number + (withoutSuffix ? ' цаг' : ' цагийн'); + case 'd': + case 'dd': + return number + (withoutSuffix ? ' өдөр' : ' өдрийн'); + case 'M': + case 'MM': + return number + (withoutSuffix ? ' сар' : ' сарын'); + case 'y': + case 'yy': + return number + (withoutSuffix ? ' жил' : ' жилийн'); + default: + return number; + } + } + + var mn = moment.defineLocale('mn', { + months : 'Нэгдүгээр сар_Хоёрдугаар сар_Гуравдугаар сар_Дөрөвдүгээр сар_Тавдугаар сар_Зургадугаар сар_Долдугаар сар_Наймдугаар сар_Есдүгээр сар_Аравдугаар сар_Арван нэгдүгээр сар_Арван хоёрдугаар сар'.split('_'), + monthsShort : '1 сар_2 сар_3 сар_4 сар_5 сар_6 сар_7 сар_8 сар_9 сар_10 сар_11 сар_12 сар'.split('_'), + monthsParseExact : true, + weekdays : 'Ням_Даваа_Мягмар_Лхагва_Пүрэв_Баасан_Бямба'.split('_'), + weekdaysShort : 'Ням_Дав_Мяг_Лха_Пүр_Баа_Бям'.split('_'), + weekdaysMin : 'Ня_Да_Мя_Лх_Пү_Ба_Бя'.split('_'), + weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D. MMMM YYYY', - LLL : 'D. MMMM YYYY HH:mm', - LLLL : 'dddd [d.] D. MMMM YYYY [kl.] HH:mm' + L : 'YYYY-MM-DD', + LL : 'YYYY оны MMMMын D', + LLL : 'YYYY оны MMMMын D HH:mm', + LLLL : 'dddd, YYYY оны MMMMын D HH:mm' }, - calendar : { - sameDay : '[i dag kl.] LT', - nextDay : '[i morgen kl.] LT', - nextWeek : 'på dddd [kl.] LT', - lastDay : '[i går kl.] LT', - lastWeek : '[i] dddd[s kl.] LT', - sameElse : 'L' + meridiemParse: /ҮӨ|ҮХ/i, + isPM : function (input) { + return input === 'ҮХ'; }, - relativeTime : { - future : 'om %s', - past : '%s siden', - s : 'få sekunder', - ss : '%d sekunder', - m : 'et minut', - mm : '%d minutter', - h : 'en time', - hh : '%d timer', - d : 'en dag', - dd : '%d dage', - M : 'en måned', - MM : '%d måneder', - y : 'et år', - yy : '%d år' + meridiem : function (hour, minute, isLower) { + if (hour < 12) { + return 'ҮӨ'; + } else { + return 'ҮХ'; + } }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + calendar : { + sameDay : '[Өнөөдөр] LT', + nextDay : '[Маргааш] LT', + nextWeek : '[Ирэх] dddd LT', + lastDay : '[Өчигдөр] LT', + lastWeek : '[Өнгөрсөн] dddd LT', + sameElse : 'L' + }, + relativeTime : { + future : '%s дараа', + past : '%s өмнө', + s : translate, + ss : translate, + m : translate, + mm : translate, + h : translate, + hh : translate, + d : translate, + dd : translate, + M : translate, + MM : translate, + y : translate, + yy : translate + }, + dayOfMonthOrdinalParse: /\d{1,2} өдөр/, + ordinal : function (number, period) { + switch (period) { + case 'd': + case 'D': + case 'DDD': + return number + ' өдөр'; + default: + return number; + } } }); - return da; + return mn; }))); /***/ }), -/* 63 */ +/* 91 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - function processRelativeTime(number, withoutSuffix, key, isFuture) { - var format = { - 'm': ['eine Minute', 'einer Minute'], - 'h': ['eine Stunde', 'einer Stunde'], - 'd': ['ein Tag', 'einem Tag'], - 'dd': [number + ' Tage', number + ' Tagen'], - 'M': ['ein Monat', 'einem Monat'], - 'MM': [number + ' Monate', number + ' Monaten'], - 'y': ['ein Jahr', 'einem Jahr'], - 'yy': [number + ' Jahre', number + ' Jahren'] - }; - return withoutSuffix ? format[key][0] : format[key][1]; + var symbolMap = { + '1': '१', + '2': '२', + '3': '३', + '4': '४', + '5': '५', + '6': '६', + '7': '७', + '8': '८', + '9': '९', + '0': '०' + }, + numberMap = { + '१': '1', + '२': '2', + '३': '3', + '४': '4', + '५': '5', + '६': '6', + '७': '7', + '८': '8', + '९': '9', + '०': '0' + }; + + function relativeTimeMr(number, withoutSuffix, string, isFuture) + { + var output = ''; + if (withoutSuffix) { + switch (string) { + case 's': output = 'काही सेकंद'; break; + case 'ss': output = '%d सेकंद'; break; + case 'm': output = 'एक मिनिट'; break; + case 'mm': output = '%d मिनिटे'; break; + case 'h': output = 'एक तास'; break; + case 'hh': output = '%d तास'; break; + case 'd': output = 'एक दिवस'; break; + case 'dd': output = '%d दिवस'; break; + case 'M': output = 'एक महिना'; break; + case 'MM': output = '%d महिने'; break; + case 'y': output = 'एक वर्ष'; break; + case 'yy': output = '%d वर्षे'; break; + } + } + else { + switch (string) { + case 's': output = 'काही सेकंदां'; break; + case 'ss': output = '%d सेकंदां'; break; + case 'm': output = 'एका मिनिटा'; break; + case 'mm': output = '%d मिनिटां'; break; + case 'h': output = 'एका तासा'; break; + case 'hh': output = '%d तासां'; break; + case 'd': output = 'एका दिवसा'; break; + case 'dd': output = '%d दिवसां'; break; + case 'M': output = 'एका महिन्या'; break; + case 'MM': output = '%d महिन्यां'; break; + case 'y': output = 'एका वर्षा'; break; + case 'yy': output = '%d वर्षां'; break; + } + } + return output.replace(/%d/i, number); } - var de = moment.defineLocale('de', { - months : 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), - monthsShort : 'Jan._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'), + var mr = moment.defineLocale('mr', { + months : 'जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split('_'), + monthsShort: 'जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split('_'), monthsParseExact : true, - weekdays : 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'), - weekdaysShort : 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'), - weekdaysMin : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), - weekdaysParseExact : true, + weekdays : 'रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'), + weekdaysShort : 'रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि'.split('_'), + weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split('_'), longDateFormat : { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D. MMMM YYYY', - LLL : 'D. MMMM YYYY HH:mm', - LLLL : 'dddd, D. MMMM YYYY HH:mm' + LT : 'A h:mm वाजता', + LTS : 'A h:mm:ss वाजता', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY, A h:mm वाजता', + LLLL : 'dddd, D MMMM YYYY, A h:mm वाजता' }, calendar : { - sameDay: '[heute um] LT [Uhr]', - sameElse: 'L', - nextDay: '[morgen um] LT [Uhr]', - nextWeek: 'dddd [um] LT [Uhr]', - lastDay: '[gestern um] LT [Uhr]', - lastWeek: '[letzten] dddd [um] LT [Uhr]' + sameDay : '[आज] LT', + nextDay : '[उद्या] LT', + nextWeek : 'dddd, LT', + lastDay : '[काल] LT', + lastWeek: '[मागील] dddd, LT', + sameElse : 'L' }, relativeTime : { - future : 'in %s', - past : 'vor %s', - s : 'ein paar Sekunden', - ss : '%d Sekunden', - m : processRelativeTime, - mm : '%d Minuten', - h : processRelativeTime, - hh : '%d Stunden', - d : processRelativeTime, - dd : processRelativeTime, - M : processRelativeTime, - MM : processRelativeTime, - y : processRelativeTime, - yy : processRelativeTime + future: '%sमध्ये', + past: '%sपूर्वी', + s: relativeTimeMr, + ss: relativeTimeMr, + m: relativeTimeMr, + mm: relativeTimeMr, + h: relativeTimeMr, + hh: relativeTimeMr, + d: relativeTimeMr, + dd: relativeTimeMr, + M: relativeTimeMr, + MM: relativeTimeMr, + y: relativeTimeMr, + yy: relativeTimeMr + }, + preparse: function (string) { + return string.replace(/[१२३४५६७८९०]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + meridiemParse: /रात्री|सकाळी|दुपारी|सायंकाळी/, + meridiemHour : function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'रात्री') { + return hour < 4 ? hour : hour + 12; + } else if (meridiem === 'सकाळी') { + return hour; + } else if (meridiem === 'दुपारी') { + return hour >= 10 ? hour : hour + 12; + } else if (meridiem === 'सायंकाळी') { + return hour + 12; + } + }, + meridiem: function (hour, minute, isLower) { + if (hour < 4) { + return 'रात्री'; + } else if (hour < 10) { + return 'सकाळी'; + } else if (hour < 17) { + return 'दुपारी'; + } else if (hour < 20) { + return 'सायंकाळी'; + } else { + return 'रात्री'; + } }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + dow : 0, // Sunday is the first day of the week. + doy : 6 // The week that contains Jan 6th is the first week of the year. } }); - return de; + return mr; }))); /***/ }), -/* 64 */ +/* 92 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - function processRelativeTime(number, withoutSuffix, key, isFuture) { - var format = { - 'm': ['eine Minute', 'einer Minute'], - 'h': ['eine Stunde', 'einer Stunde'], - 'd': ['ein Tag', 'einem Tag'], - 'dd': [number + ' Tage', number + ' Tagen'], - 'M': ['ein Monat', 'einem Monat'], - 'MM': [number + ' Monate', number + ' Monaten'], - 'y': ['ein Jahr', 'einem Jahr'], - 'yy': [number + ' Jahre', number + ' Jahren'] - }; - return withoutSuffix ? format[key][0] : format[key][1]; - } - - var deAt = moment.defineLocale('de-at', { - months : 'Jänner_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), - monthsShort : 'Jän._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'), - monthsParseExact : true, - weekdays : 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'), - weekdaysShort : 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'), - weekdaysMin : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), - weekdaysParseExact : true, + var ms = moment.defineLocale('ms', { + months : 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split('_'), + monthsShort : 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'), + weekdays : 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'), + weekdaysShort : 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'), + weekdaysMin : 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'), longDateFormat : { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D. MMMM YYYY', - LLL : 'D. MMMM YYYY HH:mm', - LLLL : 'dddd, D. MMMM YYYY HH:mm' + LT : 'HH.mm', + LTS : 'HH.mm.ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY [pukul] HH.mm', + LLLL : 'dddd, D MMMM YYYY [pukul] HH.mm' + }, + meridiemParse: /pagi|tengahari|petang|malam/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'pagi') { + return hour; + } else if (meridiem === 'tengahari') { + return hour >= 11 ? hour : hour + 12; + } else if (meridiem === 'petang' || meridiem === 'malam') { + return hour + 12; + } + }, + meridiem : function (hours, minutes, isLower) { + if (hours < 11) { + return 'pagi'; + } else if (hours < 15) { + return 'tengahari'; + } else if (hours < 19) { + return 'petang'; + } else { + return 'malam'; + } }, calendar : { - sameDay: '[heute um] LT [Uhr]', - sameElse: 'L', - nextDay: '[morgen um] LT [Uhr]', - nextWeek: 'dddd [um] LT [Uhr]', - lastDay: '[gestern um] LT [Uhr]', - lastWeek: '[letzten] dddd [um] LT [Uhr]' + sameDay : '[Hari ini pukul] LT', + nextDay : '[Esok pukul] LT', + nextWeek : 'dddd [pukul] LT', + lastDay : '[Kelmarin pukul] LT', + lastWeek : 'dddd [lepas pukul] LT', + sameElse : 'L' }, relativeTime : { - future : 'in %s', - past : 'vor %s', - s : 'ein paar Sekunden', - ss : '%d Sekunden', - m : processRelativeTime, - mm : '%d Minuten', - h : processRelativeTime, - hh : '%d Stunden', - d : processRelativeTime, - dd : processRelativeTime, - M : processRelativeTime, - MM : processRelativeTime, - y : processRelativeTime, - yy : processRelativeTime + future : 'dalam %s', + past : '%s yang lepas', + s : 'beberapa saat', + ss : '%d saat', + m : 'seminit', + mm : '%d minit', + h : 'sejam', + hh : '%d jam', + d : 'sehari', + dd : '%d hari', + M : 'sebulan', + MM : '%d bulan', + y : 'setahun', + yy : '%d tahun' }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + doy : 7 // The week that contains Jan 7th is the first week of the year. } }); - return deAt; + return ms; }))); /***/ }), -/* 65 */ +/* 93 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - function processRelativeTime(number, withoutSuffix, key, isFuture) { - var format = { - 'm': ['eine Minute', 'einer Minute'], - 'h': ['eine Stunde', 'einer Stunde'], - 'd': ['ein Tag', 'einem Tag'], - 'dd': [number + ' Tage', number + ' Tagen'], - 'M': ['ein Monat', 'einem Monat'], - 'MM': [number + ' Monate', number + ' Monaten'], - 'y': ['ein Jahr', 'einem Jahr'], - 'yy': [number + ' Jahre', number + ' Jahren'] - }; - return withoutSuffix ? format[key][0] : format[key][1]; - } - - var deCh = moment.defineLocale('de-ch', { - months : 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), - monthsShort : 'Jan._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'), - monthsParseExact : true, - weekdays : 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'), - weekdaysShort : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), - weekdaysMin : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), - weekdaysParseExact : true, + var msMy = moment.defineLocale('ms-my', { + months : 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split('_'), + monthsShort : 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'), + weekdays : 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'), + weekdaysShort : 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'), + weekdaysMin : 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'), longDateFormat : { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D. MMMM YYYY', - LLL : 'D. MMMM YYYY HH:mm', - LLLL : 'dddd, D. MMMM YYYY HH:mm' + LT : 'HH.mm', + LTS : 'HH.mm.ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY [pukul] HH.mm', + LLLL : 'dddd, D MMMM YYYY [pukul] HH.mm' + }, + meridiemParse: /pagi|tengahari|petang|malam/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'pagi') { + return hour; + } else if (meridiem === 'tengahari') { + return hour >= 11 ? hour : hour + 12; + } else if (meridiem === 'petang' || meridiem === 'malam') { + return hour + 12; + } + }, + meridiem : function (hours, minutes, isLower) { + if (hours < 11) { + return 'pagi'; + } else if (hours < 15) { + return 'tengahari'; + } else if (hours < 19) { + return 'petang'; + } else { + return 'malam'; + } }, calendar : { - sameDay: '[heute um] LT [Uhr]', - sameElse: 'L', - nextDay: '[morgen um] LT [Uhr]', - nextWeek: 'dddd [um] LT [Uhr]', - lastDay: '[gestern um] LT [Uhr]', - lastWeek: '[letzten] dddd [um] LT [Uhr]' + sameDay : '[Hari ini pukul] LT', + nextDay : '[Esok pukul] LT', + nextWeek : 'dddd [pukul] LT', + lastDay : '[Kelmarin pukul] LT', + lastWeek : 'dddd [lepas pukul] LT', + sameElse : 'L' }, relativeTime : { - future : 'in %s', - past : 'vor %s', - s : 'ein paar Sekunden', - ss : '%d Sekunden', - m : processRelativeTime, - mm : '%d Minuten', - h : processRelativeTime, - hh : '%d Stunden', - d : processRelativeTime, - dd : processRelativeTime, - M : processRelativeTime, - MM : processRelativeTime, - y : processRelativeTime, - yy : processRelativeTime + future : 'dalam %s', + past : '%s yang lepas', + s : 'beberapa saat', + ss : '%d saat', + m : 'seminit', + mm : '%d minit', + h : 'sejam', + hh : '%d jam', + d : 'sehari', + dd : '%d hari', + M : 'sebulan', + MM : '%d bulan', + y : 'setahun', + yy : '%d tahun' }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + doy : 7 // The week that contains Jan 7th is the first week of the year. } }); - return deCh; + return msMy; }))); /***/ }), -/* 66 */ +/* 94 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var months = [ - 'ޖެނުއަރީ', - 'ފެބްރުއަރީ', - 'މާރިޗު', - 'އޭޕްރީލު', - 'މޭ', - 'ޖޫން', - 'ޖުލައި', - 'އޯގަސްޓު', - 'ސެޕްޓެމްބަރު', - 'އޮކްޓޯބަރު', - 'ނޮވެމްބަރު', - 'ޑިސެމްބަރު' - ], weekdays = [ - 'އާދިއްތަ', - 'ހޯމަ', - 'އަންގާރަ', - 'ބުދަ', - 'ބުރާސްފަތި', - 'ހުކުރު', - 'ހޮނިހިރު' - ]; - - var dv = moment.defineLocale('dv', { - months : months, - monthsShort : months, - weekdays : weekdays, - weekdaysShort : weekdays, - weekdaysMin : 'އާދި_ހޯމަ_އަން_ބުދަ_ބުރާ_ހުކު_ހޮނި'.split('_'), + var mt = moment.defineLocale('mt', { + months : 'Jannar_Frar_Marzu_April_Mejju_Ġunju_Lulju_Awwissu_Settembru_Ottubru_Novembru_Diċembru'.split('_'), + monthsShort : 'Jan_Fra_Mar_Apr_Mej_Ġun_Lul_Aww_Set_Ott_Nov_Diċ'.split('_'), + weekdays : 'Il-Ħadd_It-Tnejn_It-Tlieta_L-Erbgħa_Il-Ħamis_Il-Ġimgħa_Is-Sibt'.split('_'), + weekdaysShort : 'Ħad_Tne_Tli_Erb_Ħam_Ġim_Sib'.split('_'), + weekdaysMin : 'Ħa_Tn_Tl_Er_Ħa_Ġi_Si'.split('_'), longDateFormat : { - LT : 'HH:mm', LTS : 'HH:mm:ss', - L : 'D/M/YYYY', + L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd D MMMM YYYY HH:mm' - }, - meridiemParse: /މކ|މފ/, - isPM : function (input) { - return 'މފ' === input; - }, - meridiem : function (hour, minute, isLower) { - if (hour < 12) { - return 'މކ'; - } else { - return 'މފ'; - } + LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { - sameDay : '[މިއަދު] LT', - nextDay : '[މާދަމާ] LT', - nextWeek : 'dddd LT', - lastDay : '[އިއްޔެ] LT', - lastWeek : '[ފާއިތުވި] dddd LT', + sameDay : '[Illum fil-]LT', + nextDay : '[Għada fil-]LT', + nextWeek : 'dddd [fil-]LT', + lastDay : '[Il-bieraħ fil-]LT', + lastWeek : 'dddd [li għadda] [fil-]LT', sameElse : 'L' }, relativeTime : { - future : 'ތެރޭގައި %s', - past : 'ކުރިން %s', - s : 'ސިކުންތުކޮޅެއް', - ss : 'd% ސިކުންތު', - m : 'މިނިޓެއް', - mm : 'މިނިޓު %d', - h : 'ގަޑިއިރެއް', - hh : 'ގަޑިއިރު %d', - d : 'ދުވަހެއް', - dd : 'ދުވަސް %d', - M : 'މަހެއް', - MM : 'މަސް %d', - y : 'އަހަރެއް', - yy : 'އަހަރު %d' - }, - preparse: function (string) { - return string.replace(/،/g, ','); - }, - postformat: function (string) { - return string.replace(/,/g, '،'); + future : 'f’ %s', + past : '%s ilu', + s : 'ftit sekondi', + ss : '%d sekondi', + m : 'minuta', + mm : '%d minuti', + h : 'siegħa', + hh : '%d siegħat', + d : 'ġurnata', + dd : '%d ġranet', + M : 'xahar', + MM : '%d xhur', + y : 'sena', + yy : '%d sni' }, + dayOfMonthOrdinalParse : /\d{1,2}º/, + ordinal: '%dº', week : { - dow : 7, // Sunday is the first day of the week. - doy : 12 // The week that contains Jan 12th is the first week of the year. + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return dv; + return mt; }))); /***/ }), -/* 67 */ +/* 95 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - function isFunction(input) { - return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]'; - } + var symbolMap = { + '1': '၁', + '2': '၂', + '3': '၃', + '4': '၄', + '5': '၅', + '6': '၆', + '7': '၇', + '8': '၈', + '9': '၉', + '0': '၀' + }, numberMap = { + '၁': '1', + '၂': '2', + '၃': '3', + '၄': '4', + '၅': '5', + '၆': '6', + '၇': '7', + '၈': '8', + '၉': '9', + '၀': '0' + }; - var el = moment.defineLocale('el', { - monthsNominativeEl : 'Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος'.split('_'), - monthsGenitiveEl : 'Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου'.split('_'), - months : function (momentToFormat, format) { - if (!momentToFormat) { - return this._monthsNominativeEl; - } else if (typeof format === 'string' && /D/.test(format.substring(0, format.indexOf('MMMM')))) { // if there is a day number before 'MMMM' - return this._monthsGenitiveEl[momentToFormat.month()]; - } else { - return this._monthsNominativeEl[momentToFormat.month()]; - } + var my = moment.defineLocale('my', { + months: 'ဇန်နဝါရီ_ဖေဖော်ဝါရီ_မတ်_ဧပြီ_မေ_ဇွန်_ဇူလိုင်_သြဂုတ်_စက်တင်ဘာ_အောက်တိုဘာ_နိုဝင်ဘာ_ဒီဇင်ဘာ'.split('_'), + monthsShort: 'ဇန်_ဖေ_မတ်_ပြီ_မေ_ဇွန်_လိုင်_သြ_စက်_အောက်_နို_ဒီ'.split('_'), + weekdays: 'တနင်္ဂနွေ_တနင်္လာ_အင်္ဂါ_ဗုဒ္ဓဟူး_ကြာသပတေး_သောကြာ_စနေ'.split('_'), + weekdaysShort: 'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'), + weekdaysMin: 'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'), + + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'DD/MM/YYYY', + LL: 'D MMMM YYYY', + LLL: 'D MMMM YYYY HH:mm', + LLLL: 'dddd D MMMM YYYY HH:mm' }, - monthsShort : 'Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ'.split('_'), - weekdays : 'Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο'.split('_'), - weekdaysShort : 'Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ'.split('_'), - weekdaysMin : 'Κυ_Δε_Τρ_Τε_Πε_Πα_Σα'.split('_'), - meridiem : function (hours, minutes, isLower) { - if (hours > 11) { - return isLower ? 'μμ' : 'ΜΜ'; - } else { - return isLower ? 'πμ' : 'ΠΜ'; - } + calendar: { + sameDay: '[ယနေ.] LT [မှာ]', + nextDay: '[မနက်ဖြန်] LT [မှာ]', + nextWeek: 'dddd LT [မှာ]', + lastDay: '[မနေ.က] LT [မှာ]', + lastWeek: '[ပြီးခဲ့သော] dddd LT [မှာ]', + sameElse: 'L' }, - isPM : function (input) { - return ((input + '').toLowerCase()[0] === 'μ'); + relativeTime: { + future: 'လာမည့် %s မှာ', + past: 'လွန်ခဲ့သော %s က', + s: 'စက္ကန်.အနည်းငယ်', + ss : '%d စက္ကန့်', + m: 'တစ်မိနစ်', + mm: '%d မိနစ်', + h: 'တစ်နာရီ', + hh: '%d နာရီ', + d: 'တစ်ရက်', + dd: '%d ရက်', + M: 'တစ်လ', + MM: '%d လ', + y: 'တစ်နှစ်', + yy: '%d နှစ်' }, - meridiemParse : /[ΠΜ]\.?Μ?\.?/i, - longDateFormat : { - LT : 'h:mm A', - LTS : 'h:mm:ss A', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY h:mm A', - LLLL : 'dddd, D MMMM YYYY h:mm A' + preparse: function (string) { + return string.replace(/[၁၂၃၄၅၆၇၈၉၀]/g, function (match) { + return numberMap[match]; + }); }, - calendarEl : { - sameDay : '[Σήμερα {}] LT', - nextDay : '[Αύριο {}] LT', - nextWeek : 'dddd [{}] LT', - lastDay : '[Χθες {}] LT', - lastWeek : function () { - switch (this.day()) { - case 6: - return '[το προηγούμενο] dddd [{}] LT'; - default: - return '[την προηγούμενη] dddd [{}] LT'; - } - }, - sameElse : 'L' + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); }, - calendar : function (key, mom) { - var output = this._calendarEl[key], - hours = mom && mom.hours(); - if (isFunction(output)) { - output = output.apply(mom); - } - return output.replace('{}', (hours % 12 === 1 ? 'στη' : 'στις')); + week: { + dow: 1, // Monday is the first day of the week. + doy: 4 // The week that contains Jan 4th is the first week of the year. + } + }); + + return my; + +}))); + + +/***/ }), +/* 96 */ +/***/ (function(module, exports, __webpack_require__) { + +//! moment.js locale configuration + +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; + + + var nb = moment.defineLocale('nb', { + months : 'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split('_'), + monthsShort : 'jan._feb._mars_april_mai_juni_juli_aug._sep._okt._nov._des.'.split('_'), + monthsParseExact : true, + weekdays : 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'), + weekdaysShort : 'sø._ma._ti._on._to._fr._lø.'.split('_'), + weekdaysMin : 'sø_ma_ti_on_to_fr_lø'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D. MMMM YYYY', + LLL : 'D. MMMM YYYY [kl.] HH:mm', + LLLL : 'dddd D. MMMM YYYY [kl.] HH:mm' + }, + calendar : { + sameDay: '[i dag kl.] LT', + nextDay: '[i morgen kl.] LT', + nextWeek: 'dddd [kl.] LT', + lastDay: '[i går kl.] LT', + lastWeek: '[forrige] dddd [kl.] LT', + sameElse: 'L' }, relativeTime : { - future : 'σε %s', - past : '%s πριν', - s : 'λίγα δευτερόλεπτα', - ss : '%d δευτερόλεπτα', - m : 'ένα λεπτό', - mm : '%d λεπτά', - h : 'μία ώρα', - hh : '%d ώρες', - d : 'μία μέρα', - dd : '%d μέρες', - M : 'ένας μήνας', - MM : '%d μήνες', - y : 'ένας χρόνος', - yy : '%d χρόνια' + future : 'om %s', + past : '%s siden', + s : 'noen sekunder', + ss : '%d sekunder', + m : 'ett minutt', + mm : '%d minutter', + h : 'en time', + hh : '%d timer', + d : 'en dag', + dd : '%d dager', + M : 'en måned', + MM : '%d måneder', + y : 'ett år', + yy : '%d år' }, - dayOfMonthOrdinalParse: /\d{1,2}η/, - ordinal: '%dη', + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4st is the first week of the year. + doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return el; + return nb; }))); /***/ }), -/* 68 */ +/* 97 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var enSG = moment.defineLocale('en-SG', { - months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), - monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), - weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), - weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), - weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + var symbolMap = { + '1': '१', + '2': '२', + '3': '३', + '4': '४', + '5': '५', + '6': '६', + '7': '७', + '8': '८', + '9': '९', + '0': '०' + }, + numberMap = { + '१': '1', + '२': '2', + '३': '3', + '४': '4', + '५': '5', + '६': '6', + '७': '7', + '८': '8', + '९': '9', + '०': '0' + }; + + var ne = moment.defineLocale('ne', { + months : 'जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर'.split('_'), + monthsShort : 'जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.'.split('_'), + monthsParseExact : true, + weekdays : 'आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार'.split('_'), + weekdaysShort : 'आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.'.split('_'), + weekdaysMin : 'आ._सो._मं._बु._बि._शु._श.'.split('_'), + weekdaysParseExact : true, longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', + LT : 'Aको h:mm बजे', + LTS : 'Aको h:mm:ss बजे', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd, D MMMM YYYY HH:mm' + LLL : 'D MMMM YYYY, Aको h:mm बजे', + LLLL : 'dddd, D MMMM YYYY, Aको h:mm बजे' + }, + preparse: function (string) { + return string.replace(/[१२३४५६७८९०]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + meridiemParse: /राति|बिहान|दिउँसो|साँझ/, + meridiemHour : function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'राति') { + return hour < 4 ? hour : hour + 12; + } else if (meridiem === 'बिहान') { + return hour; + } else if (meridiem === 'दिउँसो') { + return hour >= 10 ? hour : hour + 12; + } else if (meridiem === 'साँझ') { + return hour + 12; + } + }, + meridiem : function (hour, minute, isLower) { + if (hour < 3) { + return 'राति'; + } else if (hour < 12) { + return 'बिहान'; + } else if (hour < 16) { + return 'दिउँसो'; + } else if (hour < 20) { + return 'साँझ'; + } else { + return 'राति'; + } }, calendar : { - sameDay : '[Today at] LT', - nextDay : '[Tomorrow at] LT', - nextWeek : 'dddd [at] LT', - lastDay : '[Yesterday at] LT', - lastWeek : '[Last] dddd [at] LT', + sameDay : '[आज] LT', + nextDay : '[भोलि] LT', + nextWeek : '[आउँदो] dddd[,] LT', + lastDay : '[हिजो] LT', + lastWeek : '[गएको] dddd[,] LT', sameElse : 'L' }, relativeTime : { - future : 'in %s', - past : '%s ago', - s : 'a few seconds', - ss : '%d seconds', - m : 'a minute', - mm : '%d minutes', - h : 'an hour', - hh : '%d hours', - d : 'a day', - dd : '%d days', - M : 'a month', - MM : '%d months', - y : 'a year', - yy : '%d years' - }, - dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, - ordinal : function (number) { - var b = number % 10, - output = (~~(number % 100 / 10) === 1) ? 'th' : - (b === 1) ? 'st' : - (b === 2) ? 'nd' : - (b === 3) ? 'rd' : 'th'; - return number + output; + future : '%sमा', + past : '%s अगाडि', + s : 'केही क्षण', + ss : '%d सेकेण्ड', + m : 'एक मिनेट', + mm : '%d मिनेट', + h : 'एक घण्टा', + hh : '%d घण्टा', + d : 'एक दिन', + dd : '%d दिन', + M : 'एक महिना', + MM : '%d महिना', + y : 'एक बर्ष', + yy : '%d बर्ष' }, week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + dow : 0, // Sunday is the first day of the week. + doy : 6 // The week that contains Jan 6th is the first week of the year. } }); - return enSG; + return ne; }))); /***/ }), -/* 69 */ +/* 98 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var enAu = moment.defineLocale('en-au', { - months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), - monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), - weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), - weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), - weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + var monthsShortWithDots = 'jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'), + monthsShortWithoutDots = 'jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_'); + + var monthsParse = [/^jan/i, /^feb/i, /^maart|mrt.?$/i, /^apr/i, /^mei$/i, /^jun[i.]?$/i, /^jul[i.]?$/i, /^aug/i, /^sep/i, /^okt/i, /^nov/i, /^dec/i]; + var monthsRegex = /^(januari|februari|maart|april|mei|ju[nl]i|augustus|september|oktober|november|december|jan\.?|feb\.?|mrt\.?|apr\.?|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i; + + var nl = moment.defineLocale('nl', { + months : 'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split('_'), + monthsShort : function (m, format) { + if (!m) { + return monthsShortWithDots; + } else if (/-MMM-/.test(format)) { + return monthsShortWithoutDots[m.month()]; + } else { + return monthsShortWithDots[m.month()]; + } + }, + + monthsRegex: monthsRegex, + monthsShortRegex: monthsRegex, + monthsStrictRegex: /^(januari|februari|maart|april|mei|ju[nl]i|augustus|september|oktober|november|december)/i, + monthsShortStrictRegex: /^(jan\.?|feb\.?|mrt\.?|apr\.?|mei|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i, + + monthsParse : monthsParse, + longMonthsParse : monthsParse, + shortMonthsParse : monthsParse, + + weekdays : 'zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag'.split('_'), + weekdaysShort : 'zo._ma._di._wo._do._vr._za.'.split('_'), + weekdaysMin : 'zo_ma_di_wo_do_vr_za'.split('_'), + weekdaysParseExact : true, longDateFormat : { - LT : 'h:mm A', - LTS : 'h:mm:ss A', - L : 'DD/MM/YYYY', + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD-MM-YYYY', LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY h:mm A', - LLLL : 'dddd, D MMMM YYYY h:mm A' + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { - sameDay : '[Today at] LT', - nextDay : '[Tomorrow at] LT', - nextWeek : 'dddd [at] LT', - lastDay : '[Yesterday at] LT', - lastWeek : '[Last] dddd [at] LT', - sameElse : 'L' + sameDay: '[vandaag om] LT', + nextDay: '[morgen om] LT', + nextWeek: 'dddd [om] LT', + lastDay: '[gisteren om] LT', + lastWeek: '[afgelopen] dddd [om] LT', + sameElse: 'L' }, relativeTime : { - future : 'in %s', - past : '%s ago', - s : 'a few seconds', - ss : '%d seconds', - m : 'a minute', - mm : '%d minutes', - h : 'an hour', - hh : '%d hours', - d : 'a day', - dd : '%d days', - M : 'a month', - MM : '%d months', - y : 'a year', - yy : '%d years' + future : 'over %s', + past : '%s geleden', + s : 'een paar seconden', + ss : '%d seconden', + m : 'één minuut', + mm : '%d minuten', + h : 'één uur', + hh : '%d uur', + d : 'één dag', + dd : '%d dagen', + M : 'één maand', + MM : '%d maanden', + y : 'één jaar', + yy : '%d jaar' }, - dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, + dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, ordinal : function (number) { - var b = number % 10, - output = (~~(number % 100 / 10) === 1) ? 'th' : - (b === 1) ? 'st' : - (b === 2) ? 'nd' : - (b === 3) ? 'rd' : 'th'; - return number + output; + return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); }, week : { dow : 1, // Monday is the first day of the week. @@ -12543,135 +14129,89 @@ webpackContext.id = 41; } }); - return enAu; + return nl; }))); /***/ }), -/* 70 */ +/* 99 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var enCa = moment.defineLocale('en-ca', { - months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), - monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), - weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), - weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), - weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), - longDateFormat : { - LT : 'h:mm A', - LTS : 'h:mm:ss A', - L : 'YYYY-MM-DD', - LL : 'MMMM D, YYYY', - LLL : 'MMMM D, YYYY h:mm A', - LLLL : 'dddd, MMMM D, YYYY h:mm A' - }, - calendar : { - sameDay : '[Today at] LT', - nextDay : '[Tomorrow at] LT', - nextWeek : 'dddd [at] LT', - lastDay : '[Yesterday at] LT', - lastWeek : '[Last] dddd [at] LT', - sameElse : 'L' - }, - relativeTime : { - future : 'in %s', - past : '%s ago', - s : 'a few seconds', - ss : '%d seconds', - m : 'a minute', - mm : '%d minutes', - h : 'an hour', - hh : '%d hours', - d : 'a day', - dd : '%d days', - M : 'a month', - MM : '%d months', - y : 'a year', - yy : '%d years' - }, - dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, - ordinal : function (number) { - var b = number % 10, - output = (~~(number % 100 / 10) === 1) ? 'th' : - (b === 1) ? 'st' : - (b === 2) ? 'nd' : - (b === 3) ? 'rd' : 'th'; - return number + output; - } - }); - - return enCa; - -}))); - + var monthsShortWithDots = 'jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'), + monthsShortWithoutDots = 'jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_'); -/***/ }), -/* 71 */ -/***/ (function(module, exports, __webpack_require__) { + var monthsParse = [/^jan/i, /^feb/i, /^maart|mrt.?$/i, /^apr/i, /^mei$/i, /^jun[i.]?$/i, /^jul[i.]?$/i, /^aug/i, /^sep/i, /^okt/i, /^nov/i, /^dec/i]; + var monthsRegex = /^(januari|februari|maart|april|mei|ju[nl]i|augustus|september|oktober|november|december|jan\.?|feb\.?|mrt\.?|apr\.?|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i; -//! moment.js locale configuration + var nlBe = moment.defineLocale('nl-be', { + months : 'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split('_'), + monthsShort : function (m, format) { + if (!m) { + return monthsShortWithDots; + } else if (/-MMM-/.test(format)) { + return monthsShortWithoutDots[m.month()]; + } else { + return monthsShortWithDots[m.month()]; + } + }, -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; + monthsRegex: monthsRegex, + monthsShortRegex: monthsRegex, + monthsStrictRegex: /^(januari|februari|maart|april|mei|ju[nl]i|augustus|september|oktober|november|december)/i, + monthsShortStrictRegex: /^(jan\.?|feb\.?|mrt\.?|apr\.?|mei|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i, + monthsParse : monthsParse, + longMonthsParse : monthsParse, + shortMonthsParse : monthsParse, - var enGb = moment.defineLocale('en-gb', { - months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), - monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), - weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), - weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), - weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + weekdays : 'zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag'.split('_'), + weekdaysShort : 'zo._ma._di._wo._do._vr._za.'.split('_'), + weekdaysMin : 'zo_ma_di_wo_do_vr_za'.split('_'), + weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd, D MMMM YYYY HH:mm' + LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { - sameDay : '[Today at] LT', - nextDay : '[Tomorrow at] LT', - nextWeek : 'dddd [at] LT', - lastDay : '[Yesterday at] LT', - lastWeek : '[Last] dddd [at] LT', - sameElse : 'L' + sameDay: '[vandaag om] LT', + nextDay: '[morgen om] LT', + nextWeek: 'dddd [om] LT', + lastDay: '[gisteren om] LT', + lastWeek: '[afgelopen] dddd [om] LT', + sameElse: 'L' }, relativeTime : { - future : 'in %s', - past : '%s ago', - s : 'a few seconds', - ss : '%d seconds', - m : 'a minute', - mm : '%d minutes', - h : 'an hour', - hh : '%d hours', - d : 'a day', - dd : '%d days', - M : 'a month', - MM : '%d months', - y : 'a year', - yy : '%d years' + future : 'over %s', + past : '%s geleden', + s : 'een paar seconden', + ss : '%d seconden', + m : 'één minuut', + mm : '%d minuten', + h : 'één uur', + hh : '%d uur', + d : 'één dag', + dd : '%d dagen', + M : 'één maand', + MM : '%d maanden', + y : 'één jaar', + yy : '%d jaar' }, - dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, + dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, ordinal : function (number) { - var b = number % 10, - output = (~~(number % 100 / 10) === 1) ? 'th' : - (b === 1) ? 'st' : - (b === 2) ? 'nd' : - (b === 3) ? 'rd' : 'th'; - return number + output; + return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); }, week : { dow : 1, // Monday is the first day of the week. @@ -12679,373 +14219,386 @@ webpackContext.id = 41; } }); - return enGb; + return nlBe; }))); /***/ }), -/* 72 */ +/* 100 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var enIe = moment.defineLocale('en-ie', { - months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), - monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), - weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), - weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), - weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + var nn = moment.defineLocale('nn', { + months : 'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split('_'), + monthsShort : 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'), + weekdays : 'sundag_måndag_tysdag_onsdag_torsdag_fredag_laurdag'.split('_'), + weekdaysShort : 'sun_mån_tys_ons_tor_fre_lau'.split('_'), + weekdaysMin : 'su_må_ty_on_to_fr_lø'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd D MMMM YYYY HH:mm' + L : 'DD.MM.YYYY', + LL : 'D. MMMM YYYY', + LLL : 'D. MMMM YYYY [kl.] H:mm', + LLLL : 'dddd D. MMMM YYYY [kl.] HH:mm' }, calendar : { - sameDay : '[Today at] LT', - nextDay : '[Tomorrow at] LT', - nextWeek : 'dddd [at] LT', - lastDay : '[Yesterday at] LT', - lastWeek : '[Last] dddd [at] LT', - sameElse : 'L' + sameDay: '[I dag klokka] LT', + nextDay: '[I morgon klokka] LT', + nextWeek: 'dddd [klokka] LT', + lastDay: '[I går klokka] LT', + lastWeek: '[Føregåande] dddd [klokka] LT', + sameElse: 'L' }, relativeTime : { - future : 'in %s', - past : '%s ago', - s : 'a few seconds', - ss : '%d seconds', - m : 'a minute', - mm : '%d minutes', - h : 'an hour', - hh : '%d hours', - d : 'a day', - dd : '%d days', - M : 'a month', - MM : '%d months', - y : 'a year', - yy : '%d years' - }, - dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, - ordinal : function (number) { - var b = number % 10, - output = (~~(number % 100 / 10) === 1) ? 'th' : - (b === 1) ? 'st' : - (b === 2) ? 'nd' : - (b === 3) ? 'rd' : 'th'; - return number + output; + future : 'om %s', + past : '%s sidan', + s : 'nokre sekund', + ss : '%d sekund', + m : 'eit minutt', + mm : '%d minutt', + h : 'ein time', + hh : '%d timar', + d : 'ein dag', + dd : '%d dagar', + M : 'ein månad', + MM : '%d månader', + y : 'eit år', + yy : '%d år' }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return enIe; + return nn; }))); /***/ }), -/* 73 */ +/* 101 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var enIl = moment.defineLocale('en-il', { - months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), - monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), - weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), - weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), - weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + var symbolMap = { + '1': '੧', + '2': '੨', + '3': '੩', + '4': '੪', + '5': '੫', + '6': '੬', + '7': '੭', + '8': '੮', + '9': '੯', + '0': '੦' + }, + numberMap = { + '੧': '1', + '੨': '2', + '੩': '3', + '੪': '4', + '੫': '5', + '੬': '6', + '੭': '7', + '੮': '8', + '੯': '9', + '੦': '0' + }; + + var paIn = moment.defineLocale('pa-in', { + // There are months name as per Nanakshahi Calendar but they are not used as rigidly in modern Punjabi. + months : 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'), + monthsShort : 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'), + weekdays : 'ਐਤਵਾਰ_ਸੋਮਵਾਰ_ਮੰਗਲਵਾਰ_ਬੁਧਵਾਰ_ਵੀਰਵਾਰ_ਸ਼ੁੱਕਰਵਾਰ_ਸ਼ਨੀਚਰਵਾਰ'.split('_'), + weekdaysShort : 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'), + weekdaysMin : 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'), longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', + LT : 'A h:mm ਵਜੇ', + LTS : 'A h:mm:ss ਵਜੇ', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd, D MMMM YYYY HH:mm' + LLL : 'D MMMM YYYY, A h:mm ਵਜੇ', + LLLL : 'dddd, D MMMM YYYY, A h:mm ਵਜੇ' }, calendar : { - sameDay : '[Today at] LT', - nextDay : '[Tomorrow at] LT', - nextWeek : 'dddd [at] LT', - lastDay : '[Yesterday at] LT', - lastWeek : '[Last] dddd [at] LT', + sameDay : '[ਅਜ] LT', + nextDay : '[ਕਲ] LT', + nextWeek : '[ਅਗਲਾ] dddd, LT', + lastDay : '[ਕਲ] LT', + lastWeek : '[ਪਿਛਲੇ] dddd, LT', sameElse : 'L' }, relativeTime : { - future : 'in %s', - past : '%s ago', - s : 'a few seconds', - m : 'a minute', - mm : '%d minutes', - h : 'an hour', - hh : '%d hours', - d : 'a day', - dd : '%d days', - M : 'a month', - MM : '%d months', - y : 'a year', - yy : '%d years' + future : '%s ਵਿੱਚ', + past : '%s ਪਿਛਲੇ', + s : 'ਕੁਝ ਸਕਿੰਟ', + ss : '%d ਸਕਿੰਟ', + m : 'ਇਕ ਮਿੰਟ', + mm : '%d ਮਿੰਟ', + h : 'ਇੱਕ ਘੰਟਾ', + hh : '%d ਘੰਟੇ', + d : 'ਇੱਕ ਦਿਨ', + dd : '%d ਦਿਨ', + M : 'ਇੱਕ ਮਹੀਨਾ', + MM : '%d ਮਹੀਨੇ', + y : 'ਇੱਕ ਸਾਲ', + yy : '%d ਸਾਲ' }, - dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, - ordinal : function (number) { - var b = number % 10, - output = (~~(number % 100 / 10) === 1) ? 'th' : - (b === 1) ? 'st' : - (b === 2) ? 'nd' : - (b === 3) ? 'rd' : 'th'; - return number + output; + preparse: function (string) { + return string.replace(/[੧੨੩੪੫੬੭੮੯੦]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + // Punjabi notation for meridiems are quite fuzzy in practice. While there exists + // a rigid notion of a 'Pahar' it is not used as rigidly in modern Punjabi. + meridiemParse: /ਰਾਤ|ਸਵੇਰ|ਦੁਪਹਿਰ|ਸ਼ਾਮ/, + meridiemHour : function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'ਰਾਤ') { + return hour < 4 ? hour : hour + 12; + } else if (meridiem === 'ਸਵੇਰ') { + return hour; + } else if (meridiem === 'ਦੁਪਹਿਰ') { + return hour >= 10 ? hour : hour + 12; + } else if (meridiem === 'ਸ਼ਾਮ') { + return hour + 12; + } + }, + meridiem : function (hour, minute, isLower) { + if (hour < 4) { + return 'ਰਾਤ'; + } else if (hour < 10) { + return 'ਸਵੇਰ'; + } else if (hour < 17) { + return 'ਦੁਪਹਿਰ'; + } else if (hour < 20) { + return 'ਸ਼ਾਮ'; + } else { + return 'ਰਾਤ'; + } + }, + week : { + dow : 0, // Sunday is the first day of the week. + doy : 6 // The week that contains Jan 6th is the first week of the year. } }); - return enIl; + return paIn; }))); /***/ }), -/* 74 */ +/* 102 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var enNz = moment.defineLocale('en-nz', { - months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), - monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), - weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), - weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), - weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + var monthsNominative = 'styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień'.split('_'), + monthsSubjective = 'stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia'.split('_'); + function plural(n) { + return (n % 10 < 5) && (n % 10 > 1) && ((~~(n / 10) % 10) !== 1); + } + function translate(number, withoutSuffix, key) { + var result = number + ' '; + switch (key) { + case 'ss': + return result + (plural(number) ? 'sekundy' : 'sekund'); + case 'm': + return withoutSuffix ? 'minuta' : 'minutę'; + case 'mm': + return result + (plural(number) ? 'minuty' : 'minut'); + case 'h': + return withoutSuffix ? 'godzina' : 'godzinę'; + case 'hh': + return result + (plural(number) ? 'godziny' : 'godzin'); + case 'MM': + return result + (plural(number) ? 'miesiące' : 'miesięcy'); + case 'yy': + return result + (plural(number) ? 'lata' : 'lat'); + } + } + + var pl = moment.defineLocale('pl', { + months : function (momentToFormat, format) { + if (!momentToFormat) { + return monthsNominative; + } else if (format === '') { + // Hack: if format empty we know this is used to generate + // RegExp by moment. Give then back both valid forms of months + // in RegExp ready format. + return '(' + monthsSubjective[momentToFormat.month()] + '|' + monthsNominative[momentToFormat.month()] + ')'; + } else if (/D MMMM/.test(format)) { + return monthsSubjective[momentToFormat.month()]; + } else { + return monthsNominative[momentToFormat.month()]; + } + }, + monthsShort : 'sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru'.split('_'), + weekdays : 'niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota'.split('_'), + weekdaysShort : 'ndz_pon_wt_śr_czw_pt_sob'.split('_'), + weekdaysMin : 'Nd_Pn_Wt_Śr_Cz_Pt_So'.split('_'), longDateFormat : { - LT : 'h:mm A', - LTS : 'h:mm:ss A', - L : 'DD/MM/YYYY', + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD.MM.YYYY', LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY h:mm A', - LLLL : 'dddd, D MMMM YYYY h:mm A' + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { - sameDay : '[Today at] LT', - nextDay : '[Tomorrow at] LT', - nextWeek : 'dddd [at] LT', - lastDay : '[Yesterday at] LT', - lastWeek : '[Last] dddd [at] LT', - sameElse : 'L' + sameDay: '[Dziś o] LT', + nextDay: '[Jutro o] LT', + nextWeek: function () { + switch (this.day()) { + case 0: + return '[W niedzielę o] LT'; + + case 2: + return '[We wtorek o] LT'; + + case 3: + return '[W środę o] LT'; + + case 6: + return '[W sobotę o] LT'; + + default: + return '[W] dddd [o] LT'; + } + }, + lastDay: '[Wczoraj o] LT', + lastWeek: function () { + switch (this.day()) { + case 0: + return '[W zeszłą niedzielę o] LT'; + case 3: + return '[W zeszłą środę o] LT'; + case 6: + return '[W zeszłą sobotę o] LT'; + default: + return '[W zeszły] dddd [o] LT'; + } + }, + sameElse: 'L' }, relativeTime : { - future : 'in %s', - past : '%s ago', - s : 'a few seconds', - ss : '%d seconds', - m : 'a minute', - mm : '%d minutes', - h : 'an hour', - hh : '%d hours', - d : 'a day', - dd : '%d days', - M : 'a month', - MM : '%d months', - y : 'a year', - yy : '%d years' - }, - dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, - ordinal : function (number) { - var b = number % 10, - output = (~~(number % 100 / 10) === 1) ? 'th' : - (b === 1) ? 'st' : - (b === 2) ? 'nd' : - (b === 3) ? 'rd' : 'th'; - return number + output; + future : 'za %s', + past : '%s temu', + s : 'kilka sekund', + ss : translate, + m : translate, + mm : translate, + h : translate, + hh : translate, + d : '1 dzień', + dd : '%d dni', + M : 'miesiąc', + MM : translate, + y : 'rok', + yy : translate }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return enNz; + return pl; }))); /***/ }), -/* 75 */ +/* 103 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var eo = moment.defineLocale('eo', { - months : 'januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro'.split('_'), - monthsShort : 'jan_feb_mar_apr_maj_jun_jul_aŭg_sep_okt_nov_dec'.split('_'), - weekdays : 'dimanĉo_lundo_mardo_merkredo_ĵaŭdo_vendredo_sabato'.split('_'), - weekdaysShort : 'dim_lun_mard_merk_ĵaŭ_ven_sab'.split('_'), - weekdaysMin : 'di_lu_ma_me_ĵa_ve_sa'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'YYYY-MM-DD', - LL : 'D[-a de] MMMM, YYYY', - LLL : 'D[-a de] MMMM, YYYY HH:mm', - LLLL : 'dddd, [la] D[-a de] MMMM, YYYY HH:mm' - }, - meridiemParse: /[ap]\.t\.m/i, - isPM: function (input) { - return input.charAt(0).toLowerCase() === 'p'; - }, - meridiem : function (hours, minutes, isLower) { - if (hours > 11) { - return isLower ? 'p.t.m.' : 'P.T.M.'; - } else { - return isLower ? 'a.t.m.' : 'A.T.M.'; - } - }, - calendar : { - sameDay : '[Hodiaŭ je] LT', - nextDay : '[Morgaŭ je] LT', - nextWeek : 'dddd [je] LT', - lastDay : '[Hieraŭ je] LT', - lastWeek : '[pasinta] dddd [je] LT', - sameElse : 'L' - }, - relativeTime : { - future : 'post %s', - past : 'antaŭ %s', - s : 'sekundoj', - ss : '%d sekundoj', - m : 'minuto', - mm : '%d minutoj', - h : 'horo', - hh : '%d horoj', - d : 'tago',//ne 'diurno', ĉar estas uzita por proksimumo - dd : '%d tagoj', - M : 'monato', - MM : '%d monatoj', - y : 'jaro', - yy : '%d jaroj' - }, - dayOfMonthOrdinalParse: /\d{1,2}a/, - ordinal : '%da', - week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. - } - }); - - return eo; - -}))); - - -/***/ }), -/* 76 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js locale configuration - -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - - - var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'), - monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'); - - var monthsParse = [/^ene/i, /^feb/i, /^mar/i, /^abr/i, /^may/i, /^jun/i, /^jul/i, /^ago/i, /^sep/i, /^oct/i, /^nov/i, /^dic/i]; - var monthsRegex = /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i; - - var es = moment.defineLocale('es', { - months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'), - monthsShort : function (m, format) { - if (!m) { - return monthsShortDot; - } else if (/-MMM-/.test(format)) { - return monthsShort[m.month()]; - } else { - return monthsShortDot[m.month()]; - } - }, - monthsRegex : monthsRegex, - monthsShortRegex : monthsRegex, - monthsStrictRegex : /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i, - monthsShortStrictRegex : /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i, - monthsParse : monthsParse, - longMonthsParse : monthsParse, - shortMonthsParse : monthsParse, - weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), - weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), - weekdaysMin : 'do_lu_ma_mi_ju_vi_sá'.split('_'), + var pt = moment.defineLocale('pt', { + months : 'Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro'.split('_'), + monthsShort : 'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'), + weekdays : 'Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado'.split('_'), + weekdaysShort : 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'), + weekdaysMin : 'Do_2ª_3ª_4ª_5ª_6ª_Sá'.split('_'), weekdaysParseExact : true, longDateFormat : { - LT : 'H:mm', - LTS : 'H:mm:ss', + LT : 'HH:mm', + LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D [de] MMMM [de] YYYY', - LLL : 'D [de] MMMM [de] YYYY H:mm', - LLLL : 'dddd, D [de] MMMM [de] YYYY H:mm' + LLL : 'D [de] MMMM [de] YYYY HH:mm', + LLLL : 'dddd, D [de] MMMM [de] YYYY HH:mm' }, calendar : { - sameDay : function () { - return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; - }, - nextDay : function () { - return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; - }, - nextWeek : function () { - return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; - }, - lastDay : function () { - return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; - }, - lastWeek : function () { - return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; + sameDay: '[Hoje às] LT', + nextDay: '[Amanhã às] LT', + nextWeek: 'dddd [às] LT', + lastDay: '[Ontem às] LT', + lastWeek: function () { + return (this.day() === 0 || this.day() === 6) ? + '[Último] dddd [às] LT' : // Saturday + Sunday + '[Última] dddd [às] LT'; // Monday - Friday }, - sameElse : 'L' + sameElse: 'L' }, relativeTime : { - future : 'en %s', - past : 'hace %s', - s : 'unos segundos', + future : 'em %s', + past : 'há %s', + s : 'segundos', ss : '%d segundos', - m : 'un minuto', + m : 'um minuto', mm : '%d minutos', - h : 'una hora', + h : 'uma hora', hh : '%d horas', - d : 'un día', - dd : '%d días', - M : 'un mes', + d : 'um dia', + dd : '%d dias', + M : 'um mês', MM : '%d meses', - y : 'un año', - yy : '%d años' + y : 'um ano', + yy : '%d anos' }, - dayOfMonthOrdinalParse : /\d{1,2}º/, + dayOfMonthOrdinalParse: /\d{1,2}º/, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. @@ -13053,560 +14606,488 @@ webpackContext.id = 41; } }); - return es; + return pt; }))); /***/ }), -/* 77 */ +/* 104 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'), - monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'); - - var monthsParse = [/^ene/i, /^feb/i, /^mar/i, /^abr/i, /^may/i, /^jun/i, /^jul/i, /^ago/i, /^sep/i, /^oct/i, /^nov/i, /^dic/i]; - var monthsRegex = /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i; - - var esDo = moment.defineLocale('es-do', { - months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'), - monthsShort : function (m, format) { - if (!m) { - return monthsShortDot; - } else if (/-MMM-/.test(format)) { - return monthsShort[m.month()]; - } else { - return monthsShortDot[m.month()]; - } - }, - monthsRegex: monthsRegex, - monthsShortRegex: monthsRegex, - monthsStrictRegex: /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i, - monthsShortStrictRegex: /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i, - monthsParse: monthsParse, - longMonthsParse: monthsParse, - shortMonthsParse: monthsParse, - weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), - weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), - weekdaysMin : 'do_lu_ma_mi_ju_vi_sá'.split('_'), + var ptBr = moment.defineLocale('pt-br', { + months : 'Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro'.split('_'), + monthsShort : 'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'), + weekdays : 'Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado'.split('_'), + weekdaysShort : 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'), + weekdaysMin : 'Do_2ª_3ª_4ª_5ª_6ª_Sá'.split('_'), weekdaysParseExact : true, longDateFormat : { - LT : 'h:mm A', - LTS : 'h:mm:ss A', + LT : 'HH:mm', + LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D [de] MMMM [de] YYYY', - LLL : 'D [de] MMMM [de] YYYY h:mm A', - LLLL : 'dddd, D [de] MMMM [de] YYYY h:mm A' + LLL : 'D [de] MMMM [de] YYYY [às] HH:mm', + LLLL : 'dddd, D [de] MMMM [de] YYYY [às] HH:mm' }, calendar : { - sameDay : function () { - return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; - }, - nextDay : function () { - return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; - }, - nextWeek : function () { - return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; - }, - lastDay : function () { - return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; - }, - lastWeek : function () { - return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; + sameDay: '[Hoje às] LT', + nextDay: '[Amanhã às] LT', + nextWeek: 'dddd [às] LT', + lastDay: '[Ontem às] LT', + lastWeek: function () { + return (this.day() === 0 || this.day() === 6) ? + '[Último] dddd [às] LT' : // Saturday + Sunday + '[Última] dddd [às] LT'; // Monday - Friday }, - sameElse : 'L' + sameElse: 'L' }, relativeTime : { - future : 'en %s', - past : 'hace %s', - s : 'unos segundos', + future : 'em %s', + past : 'há %s', + s : 'poucos segundos', ss : '%d segundos', - m : 'un minuto', + m : 'um minuto', mm : '%d minutos', - h : 'una hora', + h : 'uma hora', hh : '%d horas', - d : 'un día', - dd : '%d días', - M : 'un mes', + d : 'um dia', + dd : '%d dias', + M : 'um mês', MM : '%d meses', - y : 'un año', - yy : '%d años' + y : 'um ano', + yy : '%d anos' }, - dayOfMonthOrdinalParse : /\d{1,2}º/, - ordinal : '%dº', - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. - } + dayOfMonthOrdinalParse: /\d{1,2}º/, + ordinal : '%dº' }); - return esDo; + return ptBr; }))); /***/ }), -/* 78 */ +/* 105 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'), - monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'); - - var monthsParse = [/^ene/i, /^feb/i, /^mar/i, /^abr/i, /^may/i, /^jun/i, /^jul/i, /^ago/i, /^sep/i, /^oct/i, /^nov/i, /^dic/i]; - var monthsRegex = /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i; + function relativeTimeWithPlural(number, withoutSuffix, key) { + var format = { + 'ss': 'secunde', + 'mm': 'minute', + 'hh': 'ore', + 'dd': 'zile', + 'MM': 'luni', + 'yy': 'ani' + }, + separator = ' '; + if (number % 100 >= 20 || (number >= 100 && number % 100 === 0)) { + separator = ' de '; + } + return number + separator + format[key]; + } - var esUs = moment.defineLocale('es-us', { - months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'), - monthsShort : function (m, format) { - if (!m) { - return monthsShortDot; - } else if (/-MMM-/.test(format)) { - return monthsShort[m.month()]; - } else { - return monthsShortDot[m.month()]; - } - }, - monthsRegex: monthsRegex, - monthsShortRegex: monthsRegex, - monthsStrictRegex: /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i, - monthsShortStrictRegex: /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i, - monthsParse: monthsParse, - longMonthsParse: monthsParse, - shortMonthsParse: monthsParse, - weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), - weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), - weekdaysMin : 'do_lu_ma_mi_ju_vi_sá'.split('_'), - weekdaysParseExact : true, + var ro = moment.defineLocale('ro', { + months : 'ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie'.split('_'), + monthsShort : 'ian._febr._mart._apr._mai_iun._iul._aug._sept._oct._nov._dec.'.split('_'), + monthsParseExact: true, + weekdays : 'duminică_luni_marți_miercuri_joi_vineri_sâmbătă'.split('_'), + weekdaysShort : 'Dum_Lun_Mar_Mie_Joi_Vin_Sâm'.split('_'), + weekdaysMin : 'Du_Lu_Ma_Mi_Jo_Vi_Sâ'.split('_'), longDateFormat : { - LT : 'h:mm A', - LTS : 'h:mm:ss A', - L : 'MM/DD/YYYY', - LL : 'D [de] MMMM [de] YYYY', - LLL : 'D [de] MMMM [de] YYYY h:mm A', - LLLL : 'dddd, D [de] MMMM [de] YYYY h:mm A' + LT : 'H:mm', + LTS : 'H:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY H:mm', + LLLL : 'dddd, D MMMM YYYY H:mm' }, calendar : { - sameDay : function () { - return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; - }, - nextDay : function () { - return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; - }, - nextWeek : function () { - return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; - }, - lastDay : function () { - return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; - }, - lastWeek : function () { - return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; - }, - sameElse : 'L' + sameDay: '[azi la] LT', + nextDay: '[mâine la] LT', + nextWeek: 'dddd [la] LT', + lastDay: '[ieri la] LT', + lastWeek: '[fosta] dddd [la] LT', + sameElse: 'L' }, relativeTime : { - future : 'en %s', - past : 'hace %s', - s : 'unos segundos', - ss : '%d segundos', - m : 'un minuto', - mm : '%d minutos', - h : 'una hora', - hh : '%d horas', - d : 'un día', - dd : '%d días', - M : 'un mes', - MM : '%d meses', - y : 'un año', - yy : '%d años' + future : 'peste %s', + past : '%s în urmă', + s : 'câteva secunde', + ss : relativeTimeWithPlural, + m : 'un minut', + mm : relativeTimeWithPlural, + h : 'o oră', + hh : relativeTimeWithPlural, + d : 'o zi', + dd : relativeTimeWithPlural, + M : 'o lună', + MM : relativeTimeWithPlural, + y : 'un an', + yy : relativeTimeWithPlural }, - dayOfMonthOrdinalParse : /\d{1,2}º/, - ordinal : '%dº', week : { - dow : 0, // Sunday is the first day of the week. - doy : 6 // The week that contains Jan 6th is the first week of the year. + dow : 1, // Monday is the first day of the week. + doy : 7 // The week that contains Jan 7th is the first week of the year. } }); - return esUs; + return ro; }))); /***/ }), -/* 79 */ +/* 106 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - function processRelativeTime(number, withoutSuffix, key, isFuture) { + function plural(word, num) { + var forms = word.split('_'); + return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); + } + function relativeTimeWithPlural(number, withoutSuffix, key) { var format = { - 's' : ['mõne sekundi', 'mõni sekund', 'paar sekundit'], - 'ss': [number + 'sekundi', number + 'sekundit'], - 'm' : ['ühe minuti', 'üks minut'], - 'mm': [number + ' minuti', number + ' minutit'], - 'h' : ['ühe tunni', 'tund aega', 'üks tund'], - 'hh': [number + ' tunni', number + ' tundi'], - 'd' : ['ühe päeva', 'üks päev'], - 'M' : ['kuu aja', 'kuu aega', 'üks kuu'], - 'MM': [number + ' kuu', number + ' kuud'], - 'y' : ['ühe aasta', 'aasta', 'üks aasta'], - 'yy': [number + ' aasta', number + ' aastat'] + 'ss': withoutSuffix ? 'секунда_секунды_секунд' : 'секунду_секунды_секунд', + 'mm': withoutSuffix ? 'минута_минуты_минут' : 'минуту_минуты_минут', + 'hh': 'час_часа_часов', + 'dd': 'день_дня_дней', + 'MM': 'месяц_месяца_месяцев', + 'yy': 'год_года_лет' }; - if (withoutSuffix) { - return format[key][2] ? format[key][2] : format[key][1]; + if (key === 'm') { + return withoutSuffix ? 'минута' : 'минуту'; + } + else { + return number + ' ' + plural(format[key], +number); } - return isFuture ? format[key][0] : format[key][1]; } + var monthsParse = [/^янв/i, /^фев/i, /^мар/i, /^апр/i, /^ма[йя]/i, /^июн/i, /^июл/i, /^авг/i, /^сен/i, /^окт/i, /^ноя/i, /^дек/i]; - var et = moment.defineLocale('et', { - months : 'jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember'.split('_'), - monthsShort : 'jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets'.split('_'), - weekdays : 'pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev'.split('_'), - weekdaysShort : 'P_E_T_K_N_R_L'.split('_'), - weekdaysMin : 'P_E_T_K_N_R_L'.split('_'), - longDateFormat : { - LT : 'H:mm', - LTS : 'H:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D. MMMM YYYY', - LLL : 'D. MMMM YYYY H:mm', - LLLL : 'dddd, D. MMMM YYYY H:mm' + // http://new.gramota.ru/spravka/rules/139-prop : § 103 + // Сокращения месяцев: http://new.gramota.ru/spravka/buro/search-answer?s=242637 + // CLDR data: http://www.unicode.org/cldr/charts/28/summary/ru.html#1753 + var ru = moment.defineLocale('ru', { + months : { + format: 'января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря'.split('_'), + standalone: 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_') }, - calendar : { - sameDay : '[Täna,] LT', - nextDay : '[Homme,] LT', - nextWeek : '[Järgmine] dddd LT', - lastDay : '[Eile,] LT', - lastWeek : '[Eelmine] dddd LT', - sameElse : 'L' + monthsShort : { + // по CLDR именно "июл." и "июн.", но какой смысл менять букву на точку ? + format: 'янв._февр._мар._апр._мая_июня_июля_авг._сент._окт._нояб._дек.'.split('_'), + standalone: 'янв._февр._март_апр._май_июнь_июль_авг._сент._окт._нояб._дек.'.split('_') }, - relativeTime : { - future : '%s pärast', - past : '%s tagasi', - s : processRelativeTime, - ss : processRelativeTime, - m : processRelativeTime, - mm : processRelativeTime, - h : processRelativeTime, - hh : processRelativeTime, - d : processRelativeTime, - dd : '%d päeva', - M : processRelativeTime, - MM : processRelativeTime, - y : processRelativeTime, - yy : processRelativeTime + weekdays : { + standalone: 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_'), + format: 'воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу'.split('_'), + isFormat: /\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/ }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. - } - }); - - return et; - -}))); - - -/***/ }), -/* 80 */ -/***/ (function(module, exports, __webpack_require__) { + weekdaysShort : 'вс_пн_вт_ср_чт_пт_сб'.split('_'), + weekdaysMin : 'вс_пн_вт_ср_чт_пт_сб'.split('_'), + monthsParse : monthsParse, + longMonthsParse : monthsParse, + shortMonthsParse : monthsParse, -//! moment.js locale configuration + // полные названия с падежами, по три буквы, для некоторых, по 4 буквы, сокращения с точкой и без точки + monthsRegex: /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i, -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; + // копия предыдущего + monthsShortRegex: /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i, + // полные названия с падежами + monthsStrictRegex: /^(январ[яь]|феврал[яь]|марта?|апрел[яь]|ма[яй]|июн[яь]|июл[яь]|августа?|сентябр[яь]|октябр[яь]|ноябр[яь]|декабр[яь])/i, - var eu = moment.defineLocale('eu', { - months : 'urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua'.split('_'), - monthsShort : 'urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.'.split('_'), - monthsParseExact : true, - weekdays : 'igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata'.split('_'), - weekdaysShort : 'ig._al._ar._az._og._ol._lr.'.split('_'), - weekdaysMin : 'ig_al_ar_az_og_ol_lr'.split('_'), - weekdaysParseExact : true, + // Выражение, которое соотвествует только сокращённым формам + monthsShortStrictRegex: /^(янв\.|февр?\.|мар[т.]|апр\.|ма[яй]|июн[ья.]|июл[ья.]|авг\.|сент?\.|окт\.|нояб?\.|дек\.)/i, longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'YYYY-MM-DD', - LL : 'YYYY[ko] MMMM[ren] D[a]', - LLL : 'YYYY[ko] MMMM[ren] D[a] HH:mm', - LLLL : 'dddd, YYYY[ko] MMMM[ren] D[a] HH:mm', - l : 'YYYY-M-D', - ll : 'YYYY[ko] MMM D[a]', - lll : 'YYYY[ko] MMM D[a] HH:mm', - llll : 'ddd, YYYY[ko] MMM D[a] HH:mm' + LT : 'H:mm', + LTS : 'H:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D MMMM YYYY г.', + LLL : 'D MMMM YYYY г., H:mm', + LLLL : 'dddd, D MMMM YYYY г., H:mm' }, calendar : { - sameDay : '[gaur] LT[etan]', - nextDay : '[bihar] LT[etan]', - nextWeek : 'dddd LT[etan]', - lastDay : '[atzo] LT[etan]', - lastWeek : '[aurreko] dddd LT[etan]', - sameElse : 'L' + sameDay: '[Сегодня, в] LT', + nextDay: '[Завтра, в] LT', + lastDay: '[Вчера, в] LT', + nextWeek: function (now) { + if (now.week() !== this.week()) { + switch (this.day()) { + case 0: + return '[В следующее] dddd, [в] LT'; + case 1: + case 2: + case 4: + return '[В следующий] dddd, [в] LT'; + case 3: + case 5: + case 6: + return '[В следующую] dddd, [в] LT'; + } + } else { + if (this.day() === 2) { + return '[Во] dddd, [в] LT'; + } else { + return '[В] dddd, [в] LT'; + } + } + }, + lastWeek: function (now) { + if (now.week() !== this.week()) { + switch (this.day()) { + case 0: + return '[В прошлое] dddd, [в] LT'; + case 1: + case 2: + case 4: + return '[В прошлый] dddd, [в] LT'; + case 3: + case 5: + case 6: + return '[В прошлую] dddd, [в] LT'; + } + } else { + if (this.day() === 2) { + return '[Во] dddd, [в] LT'; + } else { + return '[В] dddd, [в] LT'; + } + } + }, + sameElse: 'L' }, relativeTime : { - future : '%s barru', - past : 'duela %s', - s : 'segundo batzuk', - ss : '%d segundo', - m : 'minutu bat', - mm : '%d minutu', - h : 'ordu bat', - hh : '%d ordu', - d : 'egun bat', - dd : '%d egun', - M : 'hilabete bat', - MM : '%d hilabete', - y : 'urte bat', - yy : '%d urte' + future : 'через %s', + past : '%s назад', + s : 'несколько секунд', + ss : relativeTimeWithPlural, + m : relativeTimeWithPlural, + mm : relativeTimeWithPlural, + h : 'час', + hh : relativeTimeWithPlural, + d : 'день', + dd : relativeTimeWithPlural, + M : 'месяц', + MM : relativeTimeWithPlural, + y : 'год', + yy : relativeTimeWithPlural + }, + meridiemParse: /ночи|утра|дня|вечера/i, + isPM : function (input) { + return /^(дня|вечера)$/.test(input); + }, + meridiem : function (hour, minute, isLower) { + if (hour < 4) { + return 'ночи'; + } else if (hour < 12) { + return 'утра'; + } else if (hour < 17) { + return 'дня'; + } else { + return 'вечера'; + } + }, + dayOfMonthOrdinalParse: /\d{1,2}-(й|го|я)/, + ordinal: function (number, period) { + switch (period) { + case 'M': + case 'd': + case 'DDD': + return number + '-й'; + case 'D': + return number + '-го'; + case 'w': + case 'W': + return number + '-я'; + default: + return number; + } }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. + doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return eu; + return ru; }))); /***/ }), -/* 81 */ +/* 107 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var symbolMap = { - '1': '۱', - '2': '۲', - '3': '۳', - '4': '۴', - '5': '۵', - '6': '۶', - '7': '۷', - '8': '۸', - '9': '۹', - '0': '۰' - }, numberMap = { - '۱': '1', - '۲': '2', - '۳': '3', - '۴': '4', - '۵': '5', - '۶': '6', - '۷': '7', - '۸': '8', - '۹': '9', - '۰': '0' - }; + var months = [ + 'جنوري', + 'فيبروري', + 'مارچ', + 'اپريل', + 'مئي', + 'جون', + 'جولاءِ', + 'آگسٽ', + 'سيپٽمبر', + 'آڪٽوبر', + 'نومبر', + 'ڊسمبر' + ]; + var days = [ + 'آچر', + 'سومر', + 'اڱارو', + 'اربع', + 'خميس', + 'جمع', + 'ڇنڇر' + ]; - var fa = moment.defineLocale('fa', { - months : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), - monthsShort : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), - weekdays : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), - weekdaysShort : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), - weekdaysMin : 'ی_د_س_چ_پ_ج_ش'.split('_'), - weekdaysParseExact : true, + var sd = moment.defineLocale('sd', { + months : months, + monthsShort : months, + weekdays : days, + weekdaysShort : days, + weekdaysMin : days, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd, D MMMM YYYY HH:mm' + LLLL : 'dddd، D MMMM YYYY HH:mm' }, - meridiemParse: /قبل از ظهر|بعد از ظهر/, - isPM: function (input) { - return /بعد از ظهر/.test(input); + meridiemParse: /صبح|شام/, + isPM : function (input) { + return 'شام' === input; }, meridiem : function (hour, minute, isLower) { if (hour < 12) { - return 'قبل از ظهر'; - } else { - return 'بعد از ظهر'; + return 'صبح'; } + return 'شام'; }, calendar : { - sameDay : '[امروز ساعت] LT', - nextDay : '[فردا ساعت] LT', - nextWeek : 'dddd [ساعت] LT', - lastDay : '[دیروز ساعت] LT', - lastWeek : 'dddd [پیش] [ساعت] LT', + sameDay : '[اڄ] LT', + nextDay : '[سڀاڻي] LT', + nextWeek : 'dddd [اڳين هفتي تي] LT', + lastDay : '[ڪالهه] LT', + lastWeek : '[گزريل هفتي] dddd [تي] LT', sameElse : 'L' }, relativeTime : { - future : 'در %s', - past : '%s پیش', - s : 'چند ثانیه', - ss : 'ثانیه d%', - m : 'یک دقیقه', - mm : '%d دقیقه', - h : 'یک ساعت', - hh : '%d ساعت', - d : 'یک روز', - dd : '%d روز', - M : 'یک ماه', - MM : '%d ماه', - y : 'یک سال', + future : '%s پوء', + past : '%s اڳ', + s : 'چند سيڪنڊ', + ss : '%d سيڪنڊ', + m : 'هڪ منٽ', + mm : '%d منٽ', + h : 'هڪ ڪلاڪ', + hh : '%d ڪلاڪ', + d : 'هڪ ڏينهن', + dd : '%d ڏينهن', + M : 'هڪ مهينو', + MM : '%d مهينا', + y : 'هڪ سال', yy : '%d سال' }, preparse: function (string) { - return string.replace(/[۰-۹]/g, function (match) { - return numberMap[match]; - }).replace(/،/g, ','); + return string.replace(/،/g, ','); }, postformat: function (string) { - return string.replace(/\d/g, function (match) { - return symbolMap[match]; - }).replace(/,/g, '،'); + return string.replace(/,/g, '،'); }, - dayOfMonthOrdinalParse: /\d{1,2}م/, - ordinal : '%dم', week : { - dow : 6, // Saturday is the first day of the week. - doy : 12 // The week that contains Jan 12th is the first week of the year. + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return fa; + return sd; }))); /***/ }), -/* 82 */ +/* 108 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var numbersPast = 'nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän'.split(' '), - numbersFuture = [ - 'nolla', 'yhden', 'kahden', 'kolmen', 'neljän', 'viiden', 'kuuden', - numbersPast[7], numbersPast[8], numbersPast[9] - ]; - function translate(number, withoutSuffix, key, isFuture) { - var result = ''; - switch (key) { - case 's': - return isFuture ? 'muutaman sekunnin' : 'muutama sekunti'; - case 'ss': - return isFuture ? 'sekunnin' : 'sekuntia'; - case 'm': - return isFuture ? 'minuutin' : 'minuutti'; - case 'mm': - result = isFuture ? 'minuutin' : 'minuuttia'; - break; - case 'h': - return isFuture ? 'tunnin' : 'tunti'; - case 'hh': - result = isFuture ? 'tunnin' : 'tuntia'; - break; - case 'd': - return isFuture ? 'päivän' : 'päivä'; - case 'dd': - result = isFuture ? 'päivän' : 'päivää'; - break; - case 'M': - return isFuture ? 'kuukauden' : 'kuukausi'; - case 'MM': - result = isFuture ? 'kuukauden' : 'kuukautta'; - break; - case 'y': - return isFuture ? 'vuoden' : 'vuosi'; - case 'yy': - result = isFuture ? 'vuoden' : 'vuotta'; - break; - } - result = verbalNumber(number, isFuture) + ' ' + result; - return result; - } - function verbalNumber(number, isFuture) { - return number < 10 ? (isFuture ? numbersFuture[number] : numbersPast[number]) : number; - } - - var fi = moment.defineLocale('fi', { - months : 'tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu'.split('_'), - monthsShort : 'tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu'.split('_'), - weekdays : 'sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai'.split('_'), - weekdaysShort : 'su_ma_ti_ke_to_pe_la'.split('_'), - weekdaysMin : 'su_ma_ti_ke_to_pe_la'.split('_'), + var se = moment.defineLocale('se', { + months : 'ođđajagemánnu_guovvamánnu_njukčamánnu_cuoŋománnu_miessemánnu_geassemánnu_suoidnemánnu_borgemánnu_čakčamánnu_golggotmánnu_skábmamánnu_juovlamánnu'.split('_'), + monthsShort : 'ođđj_guov_njuk_cuo_mies_geas_suoi_borg_čakč_golg_skáb_juov'.split('_'), + weekdays : 'sotnabeaivi_vuossárga_maŋŋebárga_gaskavahkku_duorastat_bearjadat_lávvardat'.split('_'), + weekdaysShort : 'sotn_vuos_maŋ_gask_duor_bear_láv'.split('_'), + weekdaysMin : 's_v_m_g_d_b_L'.split('_'), longDateFormat : { - LT : 'HH.mm', - LTS : 'HH.mm.ss', + LT : 'HH:mm', + LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', - LL : 'Do MMMM[ta] YYYY', - LLL : 'Do MMMM[ta] YYYY, [klo] HH.mm', - LLLL : 'dddd, Do MMMM[ta] YYYY, [klo] HH.mm', - l : 'D.M.YYYY', - ll : 'Do MMM YYYY', - lll : 'Do MMM YYYY, [klo] HH.mm', - llll : 'ddd, Do MMM YYYY, [klo] HH.mm' + LL : 'MMMM D. [b.] YYYY', + LLL : 'MMMM D. [b.] YYYY [ti.] HH:mm', + LLLL : 'dddd, MMMM D. [b.] YYYY [ti.] HH:mm' }, calendar : { - sameDay : '[tänään] [klo] LT', - nextDay : '[huomenna] [klo] LT', - nextWeek : 'dddd [klo] LT', - lastDay : '[eilen] [klo] LT', - lastWeek : '[viime] dddd[na] [klo] LT', - sameElse : 'L' + sameDay: '[otne ti] LT', + nextDay: '[ihttin ti] LT', + nextWeek: 'dddd [ti] LT', + lastDay: '[ikte ti] LT', + lastWeek: '[ovddit] dddd [ti] LT', + sameElse: 'L' }, relativeTime : { - future : '%s päästä', - past : '%s sitten', - s : translate, - ss : translate, - m : translate, - mm : translate, - h : translate, - hh : translate, - d : translate, - dd : translate, - M : translate, - MM : translate, - y : translate, - yy : translate + future : '%s geažes', + past : 'maŋit %s', + s : 'moadde sekunddat', + ss: '%d sekunddat', + m : 'okta minuhta', + mm : '%d minuhtat', + h : 'okta diimmu', + hh : '%d diimmut', + d : 'okta beaivi', + dd : '%d beaivvit', + M : 'okta mánnu', + MM : '%d mánut', + y : 'okta jahki', + yy : '%d jagit' }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', @@ -13616,1102 +15097,1155 @@ webpackContext.id = 41; } }); - return fi; + return se; }))); /***/ }), -/* 83 */ +/* 109 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var fo = moment.defineLocale('fo', { - months : 'januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember'.split('_'), - monthsShort : 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'), - weekdays : 'sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur'.split('_'), - weekdaysShort : 'sun_mán_týs_mik_hós_frí_ley'.split('_'), - weekdaysMin : 'su_má_tý_mi_hó_fr_le'.split('_'), + /*jshint -W100*/ + var si = moment.defineLocale('si', { + months : 'ජනවාරි_පෙබරවාරි_මාර්තු_අප්‍රේල්_මැයි_ජූනි_ජූලි_අගෝස්තු_සැප්තැම්බර්_ඔක්තෝබර්_නොවැම්බර්_දෙසැම්බර්'.split('_'), + monthsShort : 'ජන_පෙබ_මාර්_අප්_මැයි_ජූනි_ජූලි_අගෝ_සැප්_ඔක්_නොවැ_දෙසැ'.split('_'), + weekdays : 'ඉරිදා_සඳුදා_අඟහරුවාදා_බදාදා_බ්‍රහස්පතින්දා_සිකුරාදා_සෙනසුරාදා'.split('_'), + weekdaysShort : 'ඉරි_සඳු_අඟ_බදා_බ්‍රහ_සිකු_සෙන'.split('_'), + weekdaysMin : 'ඉ_ස_අ_බ_බ්‍ර_සි_සෙ'.split('_'), + weekdaysParseExact : true, longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd D. MMMM, YYYY HH:mm' + LT : 'a h:mm', + LTS : 'a h:mm:ss', + L : 'YYYY/MM/DD', + LL : 'YYYY MMMM D', + LLL : 'YYYY MMMM D, a h:mm', + LLLL : 'YYYY MMMM D [වැනි] dddd, a h:mm:ss' }, calendar : { - sameDay : '[Í dag kl.] LT', - nextDay : '[Í morgin kl.] LT', - nextWeek : 'dddd [kl.] LT', - lastDay : '[Í gjár kl.] LT', - lastWeek : '[síðstu] dddd [kl] LT', + sameDay : '[අද] LT[ට]', + nextDay : '[හෙට] LT[ට]', + nextWeek : 'dddd LT[ට]', + lastDay : '[ඊයේ] LT[ට]', + lastWeek : '[පසුගිය] dddd LT[ට]', sameElse : 'L' }, relativeTime : { - future : 'um %s', - past : '%s síðani', - s : 'fá sekund', - ss : '%d sekundir', - m : 'ein minuttur', - mm : '%d minuttir', - h : 'ein tími', - hh : '%d tímar', - d : 'ein dagur', - dd : '%d dagar', - M : 'ein mánaður', - MM : '%d mánaðir', - y : 'eitt ár', - yy : '%d ár' + future : '%sකින්', + past : '%sකට පෙර', + s : 'තත්පර කිහිපය', + ss : 'තත්පර %d', + m : 'මිනිත්තුව', + mm : 'මිනිත්තු %d', + h : 'පැය', + hh : 'පැය %d', + d : 'දිනය', + dd : 'දින %d', + M : 'මාසය', + MM : 'මාස %d', + y : 'වසර', + yy : 'වසර %d' }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + dayOfMonthOrdinalParse: /\d{1,2} වැනි/, + ordinal : function (number) { + return number + ' වැනි'; + }, + meridiemParse : /පෙර වරු|පස් වරු|පෙ.ව|ප.ව./, + isPM : function (input) { + return input === 'ප.ව.' || input === 'පස් වරු'; + }, + meridiem : function (hours, minutes, isLower) { + if (hours > 11) { + return isLower ? 'ප.ව.' : 'පස් වරු'; + } else { + return isLower ? 'පෙ.ව.' : 'පෙර වරු'; + } } }); - return fo; + return si; }))); /***/ }), -/* 84 */ +/* 110 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var fr = moment.defineLocale('fr', { - months : 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'), - monthsShort : 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'), - monthsParseExact : true, - weekdays : 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), - weekdaysShort : 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), - weekdaysMin : 'di_lu_ma_me_je_ve_sa'.split('_'), - weekdaysParseExact : true, - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd D MMMM YYYY HH:mm' - }, - calendar : { - sameDay : '[Aujourd’hui à] LT', - nextDay : '[Demain à] LT', - nextWeek : 'dddd [à] LT', - lastDay : '[Hier à] LT', - lastWeek : 'dddd [dernier à] LT', - sameElse : 'L' - }, - relativeTime : { - future : 'dans %s', - past : 'il y a %s', - s : 'quelques secondes', - ss : '%d secondes', - m : 'une minute', - mm : '%d minutes', - h : 'une heure', - hh : '%d heures', - d : 'un jour', - dd : '%d jours', - M : 'un mois', - MM : '%d mois', - y : 'un an', - yy : '%d ans' - }, - dayOfMonthOrdinalParse: /\d{1,2}(er|)/, - ordinal : function (number, period) { - switch (period) { - // TODO: Return 'e' when day of month > 1. Move this case inside - // block for masculine words below. - // See https://github.com/moment/moment/issues/3375 - case 'D': - return number + (number === 1 ? 'er' : ''); - - // Words with masculine grammatical gender: mois, trimestre, jour - default: - case 'M': - case 'Q': - case 'DDD': - case 'd': - return number + (number === 1 ? 'er' : 'e'); - - // Words with feminine grammatical gender: semaine - case 'w': - case 'W': - return number + (number === 1 ? 're' : 'e'); - } - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + var months = 'január_február_marec_apríl_máj_jún_júl_august_september_október_november_december'.split('_'), + monthsShort = 'jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec'.split('_'); + function plural(n) { + return (n > 1) && (n < 5); + } + function translate(number, withoutSuffix, key, isFuture) { + var result = number + ' '; + switch (key) { + case 's': // a few seconds / in a few seconds / a few seconds ago + return (withoutSuffix || isFuture) ? 'pár sekúnd' : 'pár sekundami'; + case 'ss': // 9 seconds / in 9 seconds / 9 seconds ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'sekundy' : 'sekúnd'); + } else { + return result + 'sekundami'; + } + break; + case 'm': // a minute / in a minute / a minute ago + return withoutSuffix ? 'minúta' : (isFuture ? 'minútu' : 'minútou'); + case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'minúty' : 'minút'); + } else { + return result + 'minútami'; + } + break; + case 'h': // an hour / in an hour / an hour ago + return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou'); + case 'hh': // 9 hours / in 9 hours / 9 hours ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'hodiny' : 'hodín'); + } else { + return result + 'hodinami'; + } + break; + case 'd': // a day / in a day / a day ago + return (withoutSuffix || isFuture) ? 'deň' : 'dňom'; + case 'dd': // 9 days / in 9 days / 9 days ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'dni' : 'dní'); + } else { + return result + 'dňami'; + } + break; + case 'M': // a month / in a month / a month ago + return (withoutSuffix || isFuture) ? 'mesiac' : 'mesiacom'; + case 'MM': // 9 months / in 9 months / 9 months ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'mesiace' : 'mesiacov'); + } else { + return result + 'mesiacmi'; + } + break; + case 'y': // a year / in a year / a year ago + return (withoutSuffix || isFuture) ? 'rok' : 'rokom'; + case 'yy': // 9 years / in 9 years / 9 years ago + if (withoutSuffix || isFuture) { + return result + (plural(number) ? 'roky' : 'rokov'); + } else { + return result + 'rokmi'; + } + break; } - }); - - return fr; - -}))); - - -/***/ }), -/* 85 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js locale configuration - -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - + } - var frCa = moment.defineLocale('fr-ca', { - months : 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'), - monthsShort : 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'), - monthsParseExact : true, - weekdays : 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), - weekdaysShort : 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), - weekdaysMin : 'di_lu_ma_me_je_ve_sa'.split('_'), - weekdaysParseExact : true, + var sk = moment.defineLocale('sk', { + months : months, + monthsShort : monthsShort, + weekdays : 'nedeľa_pondelok_utorok_streda_štvrtok_piatok_sobota'.split('_'), + weekdaysShort : 'ne_po_ut_st_št_pi_so'.split('_'), + weekdaysMin : 'ne_po_ut_st_št_pi_so'.split('_'), longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'YYYY-MM-DD', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd D MMMM YYYY HH:mm' + LT: 'H:mm', + LTS : 'H:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D. MMMM YYYY', + LLL : 'D. MMMM YYYY H:mm', + LLLL : 'dddd D. MMMM YYYY H:mm' }, calendar : { - sameDay : '[Aujourd’hui à] LT', - nextDay : '[Demain à] LT', - nextWeek : 'dddd [à] LT', - lastDay : '[Hier à] LT', - lastWeek : 'dddd [dernier à] LT', - sameElse : 'L' + sameDay: '[dnes o] LT', + nextDay: '[zajtra o] LT', + nextWeek: function () { + switch (this.day()) { + case 0: + return '[v nedeľu o] LT'; + case 1: + case 2: + return '[v] dddd [o] LT'; + case 3: + return '[v stredu o] LT'; + case 4: + return '[vo štvrtok o] LT'; + case 5: + return '[v piatok o] LT'; + case 6: + return '[v sobotu o] LT'; + } + }, + lastDay: '[včera o] LT', + lastWeek: function () { + switch (this.day()) { + case 0: + return '[minulú nedeľu o] LT'; + case 1: + case 2: + return '[minulý] dddd [o] LT'; + case 3: + return '[minulú stredu o] LT'; + case 4: + case 5: + return '[minulý] dddd [o] LT'; + case 6: + return '[minulú sobotu o] LT'; + } + }, + sameElse: 'L' }, relativeTime : { - future : 'dans %s', - past : 'il y a %s', - s : 'quelques secondes', - ss : '%d secondes', - m : 'une minute', - mm : '%d minutes', - h : 'une heure', - hh : '%d heures', - d : 'un jour', - dd : '%d jours', - M : 'un mois', - MM : '%d mois', - y : 'un an', - yy : '%d ans' + future : 'za %s', + past : 'pred %s', + s : translate, + ss : translate, + m : translate, + mm : translate, + h : translate, + hh : translate, + d : translate, + dd : translate, + M : translate, + MM : translate, + y : translate, + yy : translate }, - dayOfMonthOrdinalParse: /\d{1,2}(er|e)/, - ordinal : function (number, period) { - switch (period) { - // Words with masculine grammatical gender: mois, trimestre, jour - default: - case 'M': - case 'Q': - case 'D': - case 'DDD': - case 'd': - return number + (number === 1 ? 'er' : 'e'); - - // Words with feminine grammatical gender: semaine - case 'w': - case 'W': - return number + (number === 1 ? 're' : 'e'); - } + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return frCa; + return sk; }))); /***/ }), -/* 86 */ +/* 111 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var frCh = moment.defineLocale('fr-ch', { - months : 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'), - monthsShort : 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'), - monthsParseExact : true, - weekdays : 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), - weekdaysShort : 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), - weekdaysMin : 'di_lu_ma_me_je_ve_sa'.split('_'), + function processRelativeTime(number, withoutSuffix, key, isFuture) { + var result = number + ' '; + switch (key) { + case 's': + return withoutSuffix || isFuture ? 'nekaj sekund' : 'nekaj sekundami'; + case 'ss': + if (number === 1) { + result += withoutSuffix ? 'sekundo' : 'sekundi'; + } else if (number === 2) { + result += withoutSuffix || isFuture ? 'sekundi' : 'sekundah'; + } else if (number < 5) { + result += withoutSuffix || isFuture ? 'sekunde' : 'sekundah'; + } else { + result += 'sekund'; + } + return result; + case 'm': + return withoutSuffix ? 'ena minuta' : 'eno minuto'; + case 'mm': + if (number === 1) { + result += withoutSuffix ? 'minuta' : 'minuto'; + } else if (number === 2) { + result += withoutSuffix || isFuture ? 'minuti' : 'minutama'; + } else if (number < 5) { + result += withoutSuffix || isFuture ? 'minute' : 'minutami'; + } else { + result += withoutSuffix || isFuture ? 'minut' : 'minutami'; + } + return result; + case 'h': + return withoutSuffix ? 'ena ura' : 'eno uro'; + case 'hh': + if (number === 1) { + result += withoutSuffix ? 'ura' : 'uro'; + } else if (number === 2) { + result += withoutSuffix || isFuture ? 'uri' : 'urama'; + } else if (number < 5) { + result += withoutSuffix || isFuture ? 'ure' : 'urami'; + } else { + result += withoutSuffix || isFuture ? 'ur' : 'urami'; + } + return result; + case 'd': + return withoutSuffix || isFuture ? 'en dan' : 'enim dnem'; + case 'dd': + if (number === 1) { + result += withoutSuffix || isFuture ? 'dan' : 'dnem'; + } else if (number === 2) { + result += withoutSuffix || isFuture ? 'dni' : 'dnevoma'; + } else { + result += withoutSuffix || isFuture ? 'dni' : 'dnevi'; + } + return result; + case 'M': + return withoutSuffix || isFuture ? 'en mesec' : 'enim mesecem'; + case 'MM': + if (number === 1) { + result += withoutSuffix || isFuture ? 'mesec' : 'mesecem'; + } else if (number === 2) { + result += withoutSuffix || isFuture ? 'meseca' : 'mesecema'; + } else if (number < 5) { + result += withoutSuffix || isFuture ? 'mesece' : 'meseci'; + } else { + result += withoutSuffix || isFuture ? 'mesecev' : 'meseci'; + } + return result; + case 'y': + return withoutSuffix || isFuture ? 'eno leto' : 'enim letom'; + case 'yy': + if (number === 1) { + result += withoutSuffix || isFuture ? 'leto' : 'letom'; + } else if (number === 2) { + result += withoutSuffix || isFuture ? 'leti' : 'letoma'; + } else if (number < 5) { + result += withoutSuffix || isFuture ? 'leta' : 'leti'; + } else { + result += withoutSuffix || isFuture ? 'let' : 'leti'; + } + return result; + } + } + + var sl = moment.defineLocale('sl', { + months : 'januar_februar_marec_april_maj_junij_julij_avgust_september_oktober_november_december'.split('_'), + monthsShort : 'jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.'.split('_'), + monthsParseExact: true, + weekdays : 'nedelja_ponedeljek_torek_sreda_četrtek_petek_sobota'.split('_'), + weekdaysShort : 'ned._pon._tor._sre._čet._pet._sob.'.split('_'), + weekdaysMin : 'ne_po_to_sr_če_pe_so'.split('_'), weekdaysParseExact : true, longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', + LT : 'H:mm', + LTS : 'H:mm:ss', L : 'DD.MM.YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd D MMMM YYYY HH:mm' + LL : 'D. MMMM YYYY', + LLL : 'D. MMMM YYYY H:mm', + LLLL : 'dddd, D. MMMM YYYY H:mm' }, calendar : { - sameDay : '[Aujourd’hui à] LT', - nextDay : '[Demain à] LT', - nextWeek : 'dddd [à] LT', - lastDay : '[Hier à] LT', - lastWeek : 'dddd [dernier à] LT', + sameDay : '[danes ob] LT', + nextDay : '[jutri ob] LT', + + nextWeek : function () { + switch (this.day()) { + case 0: + return '[v] [nedeljo] [ob] LT'; + case 3: + return '[v] [sredo] [ob] LT'; + case 6: + return '[v] [soboto] [ob] LT'; + case 1: + case 2: + case 4: + case 5: + return '[v] dddd [ob] LT'; + } + }, + lastDay : '[včeraj ob] LT', + lastWeek : function () { + switch (this.day()) { + case 0: + return '[prejšnjo] [nedeljo] [ob] LT'; + case 3: + return '[prejšnjo] [sredo] [ob] LT'; + case 6: + return '[prejšnjo] [soboto] [ob] LT'; + case 1: + case 2: + case 4: + case 5: + return '[prejšnji] dddd [ob] LT'; + } + }, sameElse : 'L' }, relativeTime : { - future : 'dans %s', - past : 'il y a %s', - s : 'quelques secondes', - ss : '%d secondes', - m : 'une minute', - mm : '%d minutes', - h : 'une heure', - hh : '%d heures', - d : 'un jour', - dd : '%d jours', - M : 'un mois', - MM : '%d mois', - y : 'un an', - yy : '%d ans' - }, - dayOfMonthOrdinalParse: /\d{1,2}(er|e)/, - ordinal : function (number, period) { - switch (period) { - // Words with masculine grammatical gender: mois, trimestre, jour - default: - case 'M': - case 'Q': - case 'D': - case 'DDD': - case 'd': - return number + (number === 1 ? 'er' : 'e'); - - // Words with feminine grammatical gender: semaine - case 'w': - case 'W': - return number + (number === 1 ? 're' : 'e'); - } + future : 'čez %s', + past : 'pred %s', + s : processRelativeTime, + ss : processRelativeTime, + m : processRelativeTime, + mm : processRelativeTime, + h : processRelativeTime, + hh : processRelativeTime, + d : processRelativeTime, + dd : processRelativeTime, + M : processRelativeTime, + MM : processRelativeTime, + y : processRelativeTime, + yy : processRelativeTime }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + doy : 7 // The week that contains Jan 7th is the first week of the year. } }); - return frCh; + return sl; }))); /***/ }), -/* 87 */ +/* 112 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var monthsShortWithDots = 'jan._feb._mrt._apr._mai_jun._jul._aug._sep._okt._nov._des.'.split('_'), - monthsShortWithoutDots = 'jan_feb_mrt_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'); - - var fy = moment.defineLocale('fy', { - months : 'jannewaris_febrewaris_maart_april_maaie_juny_july_augustus_septimber_oktober_novimber_desimber'.split('_'), - monthsShort : function (m, format) { - if (!m) { - return monthsShortWithDots; - } else if (/-MMM-/.test(format)) { - return monthsShortWithoutDots[m.month()]; - } else { - return monthsShortWithDots[m.month()]; - } - }, - monthsParseExact : true, - weekdays : 'snein_moandei_tiisdei_woansdei_tongersdei_freed_sneon'.split('_'), - weekdaysShort : 'si._mo._ti._wo._to._fr._so.'.split('_'), - weekdaysMin : 'Si_Mo_Ti_Wo_To_Fr_So'.split('_'), + var sq = moment.defineLocale('sq', { + months : 'Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor'.split('_'), + monthsShort : 'Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj'.split('_'), + weekdays : 'E Diel_E Hënë_E Martë_E Mërkurë_E Enjte_E Premte_E Shtunë'.split('_'), + weekdaysShort : 'Die_Hën_Mar_Mër_Enj_Pre_Sht'.split('_'), + weekdaysMin : 'D_H_Ma_Më_E_P_Sh'.split('_'), weekdaysParseExact : true, + meridiemParse: /PD|MD/, + isPM: function (input) { + return input.charAt(0) === 'M'; + }, + meridiem : function (hours, minutes, isLower) { + return hours < 12 ? 'PD' : 'MD'; + }, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', - L : 'DD-MM-YYYY', + L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd D MMMM YYYY HH:mm' + LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { - sameDay: '[hjoed om] LT', - nextDay: '[moarn om] LT', - nextWeek: 'dddd [om] LT', - lastDay: '[juster om] LT', - lastWeek: '[ôfrûne] dddd [om] LT', - sameElse: 'L' + sameDay : '[Sot në] LT', + nextDay : '[Nesër në] LT', + nextWeek : 'dddd [në] LT', + lastDay : '[Dje në] LT', + lastWeek : 'dddd [e kaluar në] LT', + sameElse : 'L' }, relativeTime : { - future : 'oer %s', - past : '%s lyn', - s : 'in pear sekonden', - ss : '%d sekonden', - m : 'ien minút', - mm : '%d minuten', - h : 'ien oere', - hh : '%d oeren', - d : 'ien dei', - dd : '%d dagen', - M : 'ien moanne', - MM : '%d moannen', - y : 'ien jier', - yy : '%d jierren' - }, - dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, - ordinal : function (number) { - return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); + future : 'në %s', + past : '%s më parë', + s : 'disa sekonda', + ss : '%d sekonda', + m : 'një minutë', + mm : '%d minuta', + h : 'një orë', + hh : '%d orë', + d : 'një ditë', + dd : '%d ditë', + M : 'një muaj', + MM : '%d muaj', + y : 'një vit', + yy : '%d vite' }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return fy; + return sq; }))); /***/ }), -/* 88 */ +/* 113 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; + var translator = { + words: { //Different grammatical cases + ss: ['sekunda', 'sekunde', 'sekundi'], + m: ['jedan minut', 'jedne minute'], + mm: ['minut', 'minute', 'minuta'], + h: ['jedan sat', 'jednog sata'], + hh: ['sat', 'sata', 'sati'], + dd: ['dan', 'dana', 'dana'], + MM: ['mesec', 'meseca', 'meseci'], + yy: ['godina', 'godine', 'godina'] + }, + correctGrammaticalCase: function (number, wordKey) { + return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]); + }, + translate: function (number, withoutSuffix, key) { + var wordKey = translator.words[key]; + if (key.length === 1) { + return withoutSuffix ? wordKey[0] : wordKey[1]; + } else { + return number + ' ' + translator.correctGrammaticalCase(number, wordKey); + } + } + }; - var months = [ - 'Eanáir', 'Feabhra', 'Márta', 'Aibreán', 'Bealtaine', 'Méitheamh', 'Iúil', 'Lúnasa', 'Meán Fómhair', 'Deaireadh Fómhair', 'Samhain', 'Nollaig' - ]; - - var monthsShort = ['Eaná', 'Feab', 'Márt', 'Aibr', 'Beal', 'Méit', 'Iúil', 'Lúna', 'Meán', 'Deai', 'Samh', 'Noll']; - - var weekdays = ['Dé Domhnaigh', 'Dé Luain', 'Dé Máirt', 'Dé Céadaoin', 'Déardaoin', 'Dé hAoine', 'Dé Satharn']; - - var weekdaysShort = ['Dom', 'Lua', 'Mái', 'Céa', 'Déa', 'hAo', 'Sat']; - - var weekdaysMin = ['Do', 'Lu', 'Má', 'Ce', 'Dé', 'hA', 'Sa']; - - var ga = moment.defineLocale('ga', { - months: months, - monthsShort: monthsShort, + var sr = moment.defineLocale('sr', { + months: 'januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar'.split('_'), + monthsShort: 'jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.'.split('_'), monthsParseExact: true, - weekdays: weekdays, - weekdaysShort: weekdaysShort, - weekdaysMin: weekdaysMin, + weekdays: 'nedelja_ponedeljak_utorak_sreda_četvrtak_petak_subota'.split('_'), + weekdaysShort: 'ned._pon._uto._sre._čet._pet._sub.'.split('_'), + weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'), + weekdaysParseExact : true, longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm' + LT: 'H:mm', + LTS : 'H:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D. MMMM YYYY', + LLL: 'D. MMMM YYYY H:mm', + LLLL: 'dddd, D. MMMM YYYY H:mm' }, calendar: { - sameDay: '[Inniu ag] LT', - nextDay: '[Amárach ag] LT', - nextWeek: 'dddd [ag] LT', - lastDay: '[Inné aig] LT', - lastWeek: 'dddd [seo caite] [ag] LT', - sameElse: 'L' - }, - relativeTime: { - future: 'i %s', - past: '%s ó shin', - s: 'cúpla soicind', - ss: '%d soicind', - m: 'nóiméad', - mm: '%d nóiméad', - h: 'uair an chloig', - hh: '%d uair an chloig', - d: 'lá', - dd: '%d lá', - M: 'mí', - MM: '%d mí', - y: 'bliain', - yy: '%d bliain' + sameDay: '[danas u] LT', + nextDay: '[sutra u] LT', + nextWeek: function () { + switch (this.day()) { + case 0: + return '[u] [nedelju] [u] LT'; + case 3: + return '[u] [sredu] [u] LT'; + case 6: + return '[u] [subotu] [u] LT'; + case 1: + case 2: + case 4: + case 5: + return '[u] dddd [u] LT'; + } + }, + lastDay : '[juče u] LT', + lastWeek : function () { + var lastWeekDays = [ + '[prošle] [nedelje] [u] LT', + '[prošlog] [ponedeljka] [u] LT', + '[prošlog] [utorka] [u] LT', + '[prošle] [srede] [u] LT', + '[prošlog] [četvrtka] [u] LT', + '[prošlog] [petka] [u] LT', + '[prošle] [subote] [u] LT' + ]; + return lastWeekDays[this.day()]; + }, + sameElse : 'L' }, - dayOfMonthOrdinalParse: /\d{1,2}(d|na|mh)/, - ordinal: function (number) { - var output = number === 1 ? 'd' : number % 10 === 2 ? 'na' : 'mh'; - return number + output; + relativeTime : { + future : 'za %s', + past : 'pre %s', + s : 'nekoliko sekundi', + ss : translator.translate, + m : translator.translate, + mm : translator.translate, + h : translator.translate, + hh : translator.translate, + d : 'dan', + dd : translator.translate, + M : 'mesec', + MM : translator.translate, + y : 'godinu', + yy : translator.translate }, - week: { - dow: 1, // Monday is the first day of the week. - doy: 4 // The week that contains Jan 4th is the first week of the year. + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', + week : { + dow : 1, // Monday is the first day of the week. + doy : 7 // The week that contains Jan 7th is the first week of the year. } }); - return ga; + return sr; }))); /***/ }), -/* 89 */ +/* 114 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var months = [ - 'Am Faoilleach', 'An Gearran', 'Am Màrt', 'An Giblean', 'An Cèitean', 'An t-Ògmhios', 'An t-Iuchar', 'An Lùnastal', 'An t-Sultain', 'An Dàmhair', 'An t-Samhain', 'An Dùbhlachd' - ]; - - var monthsShort = ['Faoi', 'Gear', 'Màrt', 'Gibl', 'Cèit', 'Ògmh', 'Iuch', 'Lùn', 'Sult', 'Dàmh', 'Samh', 'Dùbh']; - - var weekdays = ['Didòmhnaich', 'Diluain', 'Dimàirt', 'Diciadain', 'Diardaoin', 'Dihaoine', 'Disathairne']; - - var weekdaysShort = ['Did', 'Dil', 'Dim', 'Dic', 'Dia', 'Dih', 'Dis']; - - var weekdaysMin = ['Dò', 'Lu', 'Mà', 'Ci', 'Ar', 'Ha', 'Sa']; + var translator = { + words: { //Different grammatical cases + ss: ['секунда', 'секунде', 'секунди'], + m: ['један минут', 'једне минуте'], + mm: ['минут', 'минуте', 'минута'], + h: ['један сат', 'једног сата'], + hh: ['сат', 'сата', 'сати'], + dd: ['дан', 'дана', 'дана'], + MM: ['месец', 'месеца', 'месеци'], + yy: ['година', 'године', 'година'] + }, + correctGrammaticalCase: function (number, wordKey) { + return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]); + }, + translate: function (number, withoutSuffix, key) { + var wordKey = translator.words[key]; + if (key.length === 1) { + return withoutSuffix ? wordKey[0] : wordKey[1]; + } else { + return number + ' ' + translator.correctGrammaticalCase(number, wordKey); + } + } + }; - var gd = moment.defineLocale('gd', { - months : months, - monthsShort : monthsShort, - monthsParseExact : true, - weekdays : weekdays, - weekdaysShort : weekdaysShort, - weekdaysMin : weekdaysMin, - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd, D MMMM YYYY HH:mm' + var srCyrl = moment.defineLocale('sr-cyrl', { + months: 'јануар_фебруар_март_април_мај_јун_јул_август_септембар_октобар_новембар_децембар'.split('_'), + monthsShort: 'јан._феб._мар._апр._мај_јун_јул_авг._сеп._окт._нов._дец.'.split('_'), + monthsParseExact: true, + weekdays: 'недеља_понедељак_уторак_среда_четвртак_петак_субота'.split('_'), + weekdaysShort: 'нед._пон._уто._сре._чет._пет._суб.'.split('_'), + weekdaysMin: 'не_по_ут_ср_че_пе_су'.split('_'), + weekdaysParseExact : true, + longDateFormat: { + LT: 'H:mm', + LTS : 'H:mm:ss', + L: 'DD.MM.YYYY', + LL: 'D. MMMM YYYY', + LLL: 'D. MMMM YYYY H:mm', + LLLL: 'dddd, D. MMMM YYYY H:mm' }, - calendar : { - sameDay : '[An-diugh aig] LT', - nextDay : '[A-màireach aig] LT', - nextWeek : 'dddd [aig] LT', - lastDay : '[An-dè aig] LT', - lastWeek : 'dddd [seo chaidh] [aig] LT', + calendar: { + sameDay: '[данас у] LT', + nextDay: '[сутра у] LT', + nextWeek: function () { + switch (this.day()) { + case 0: + return '[у] [недељу] [у] LT'; + case 3: + return '[у] [среду] [у] LT'; + case 6: + return '[у] [суботу] [у] LT'; + case 1: + case 2: + case 4: + case 5: + return '[у] dddd [у] LT'; + } + }, + lastDay : '[јуче у] LT', + lastWeek : function () { + var lastWeekDays = [ + '[прошле] [недеље] [у] LT', + '[прошлог] [понедељка] [у] LT', + '[прошлог] [уторка] [у] LT', + '[прошле] [среде] [у] LT', + '[прошлог] [четвртка] [у] LT', + '[прошлог] [петка] [у] LT', + '[прошле] [суботе] [у] LT' + ]; + return lastWeekDays[this.day()]; + }, sameElse : 'L' }, relativeTime : { - future : 'ann an %s', - past : 'bho chionn %s', - s : 'beagan diogan', - ss : '%d diogan', - m : 'mionaid', - mm : '%d mionaidean', - h : 'uair', - hh : '%d uairean', - d : 'latha', - dd : '%d latha', - M : 'mìos', - MM : '%d mìosan', - y : 'bliadhna', - yy : '%d bliadhna' - }, - dayOfMonthOrdinalParse : /\d{1,2}(d|na|mh)/, - ordinal : function (number) { - var output = number === 1 ? 'd' : number % 10 === 2 ? 'na' : 'mh'; - return number + output; + future : 'за %s', + past : 'пре %s', + s : 'неколико секунди', + ss : translator.translate, + m : translator.translate, + mm : translator.translate, + h : translator.translate, + hh : translator.translate, + d : 'дан', + dd : translator.translate, + M : 'месец', + MM : translator.translate, + y : 'годину', + yy : translator.translate }, + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + doy : 7 // The week that contains Jan 7th is the first week of the year. } }); - return gd; + return srCyrl; }))); /***/ }), -/* 90 */ +/* 115 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var gl = moment.defineLocale('gl', { - months : 'xaneiro_febreiro_marzo_abril_maio_xuño_xullo_agosto_setembro_outubro_novembro_decembro'.split('_'), - monthsShort : 'xan._feb._mar._abr._mai._xuñ._xul._ago._set._out._nov._dec.'.split('_'), - monthsParseExact: true, - weekdays : 'domingo_luns_martes_mércores_xoves_venres_sábado'.split('_'), - weekdaysShort : 'dom._lun._mar._mér._xov._ven._sáb.'.split('_'), - weekdaysMin : 'do_lu_ma_mé_xo_ve_sá'.split('_'), + var ss = moment.defineLocale('ss', { + months : "Bhimbidvwane_Indlovana_Indlov'lenkhulu_Mabasa_Inkhwekhweti_Inhlaba_Kholwane_Ingci_Inyoni_Imphala_Lweti_Ingongoni".split('_'), + monthsShort : 'Bhi_Ina_Inu_Mab_Ink_Inh_Kho_Igc_Iny_Imp_Lwe_Igo'.split('_'), + weekdays : 'Lisontfo_Umsombuluko_Lesibili_Lesitsatfu_Lesine_Lesihlanu_Umgcibelo'.split('_'), + weekdaysShort : 'Lis_Umb_Lsb_Les_Lsi_Lsh_Umg'.split('_'), + weekdaysMin : 'Li_Us_Lb_Lt_Ls_Lh_Ug'.split('_'), weekdaysParseExact : true, longDateFormat : { - LT : 'H:mm', - LTS : 'H:mm:ss', + LT : 'h:mm A', + LTS : 'h:mm:ss A', L : 'DD/MM/YYYY', - LL : 'D [de] MMMM [de] YYYY', - LLL : 'D [de] MMMM [de] YYYY H:mm', - LLLL : 'dddd, D [de] MMMM [de] YYYY H:mm' + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY h:mm A', + LLLL : 'dddd, D MMMM YYYY h:mm A' }, calendar : { - sameDay : function () { - return '[hoxe ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; - }, - nextDay : function () { - return '[mañá ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; - }, - nextWeek : function () { - return 'dddd [' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; - }, - lastDay : function () { - return '[onte ' + ((this.hours() !== 1) ? 'á' : 'a') + '] LT'; - }, - lastWeek : function () { - return '[o] dddd [pasado ' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; - }, + sameDay : '[Namuhla nga] LT', + nextDay : '[Kusasa nga] LT', + nextWeek : 'dddd [nga] LT', + lastDay : '[Itolo nga] LT', + lastWeek : 'dddd [leliphelile] [nga] LT', sameElse : 'L' }, relativeTime : { - future : function (str) { - if (str.indexOf('un') === 0) { - return 'n' + str; + future : 'nga %s', + past : 'wenteka nga %s', + s : 'emizuzwana lomcane', + ss : '%d mzuzwana', + m : 'umzuzu', + mm : '%d emizuzu', + h : 'lihora', + hh : '%d emahora', + d : 'lilanga', + dd : '%d emalanga', + M : 'inyanga', + MM : '%d tinyanga', + y : 'umnyaka', + yy : '%d iminyaka' + }, + meridiemParse: /ekuseni|emini|entsambama|ebusuku/, + meridiem : function (hours, minutes, isLower) { + if (hours < 11) { + return 'ekuseni'; + } else if (hours < 15) { + return 'emini'; + } else if (hours < 19) { + return 'entsambama'; + } else { + return 'ebusuku'; + } + }, + meridiemHour : function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'ekuseni') { + return hour; + } else if (meridiem === 'emini') { + return hour >= 11 ? hour : hour + 12; + } else if (meridiem === 'entsambama' || meridiem === 'ebusuku') { + if (hour === 0) { + return 0; } - return 'en ' + str; - }, - past : 'hai %s', - s : 'uns segundos', - ss : '%d segundos', - m : 'un minuto', - mm : '%d minutos', - h : 'unha hora', - hh : '%d horas', - d : 'un día', - dd : '%d días', - M : 'un mes', - MM : '%d meses', - y : 'un ano', - yy : '%d anos' + return hour + 12; + } }, - dayOfMonthOrdinalParse : /\d{1,2}º/, - ordinal : '%dº', + dayOfMonthOrdinalParse: /\d{1,2}/, + ordinal : '%d', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return gl; + return ss; }))); /***/ }), -/* 91 */ +/* 116 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - function processRelativeTime(number, withoutSuffix, key, isFuture) { - var format = { - 's': ['thodde secondanim', 'thodde second'], - 'ss': [number + ' secondanim', number + ' second'], - 'm': ['eka mintan', 'ek minute'], - 'mm': [number + ' mintanim', number + ' mintam'], - 'h': ['eka voran', 'ek vor'], - 'hh': [number + ' voranim', number + ' voram'], - 'd': ['eka disan', 'ek dis'], - 'dd': [number + ' disanim', number + ' dis'], - 'M': ['eka mhoinean', 'ek mhoino'], - 'MM': [number + ' mhoineanim', number + ' mhoine'], - 'y': ['eka vorsan', 'ek voros'], - 'yy': [number + ' vorsanim', number + ' vorsam'] - }; - return withoutSuffix ? format[key][0] : format[key][1]; - } - - var gomLatn = moment.defineLocale('gom-latn', { - months : 'Janer_Febrer_Mars_Abril_Mai_Jun_Julai_Agost_Setembr_Otubr_Novembr_Dezembr'.split('_'), - monthsShort : 'Jan._Feb._Mars_Abr._Mai_Jun_Jul._Ago._Set._Otu._Nov._Dez.'.split('_'), - monthsParseExact : true, - weekdays : 'Aitar_Somar_Mongllar_Budvar_Brestar_Sukrar_Son\'var'.split('_'), - weekdaysShort : 'Ait._Som._Mon._Bud._Bre._Suk._Son.'.split('_'), - weekdaysMin : 'Ai_Sm_Mo_Bu_Br_Su_Sn'.split('_'), - weekdaysParseExact : true, + var sv = moment.defineLocale('sv', { + months : 'januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december'.split('_'), + monthsShort : 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'), + weekdays : 'söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag'.split('_'), + weekdaysShort : 'sön_mån_tis_ons_tor_fre_lör'.split('_'), + weekdaysMin : 'sö_må_ti_on_to_fr_lö'.split('_'), longDateFormat : { - LT : 'A h:mm [vazta]', - LTS : 'A h:mm:ss [vazta]', - L : 'DD-MM-YYYY', + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'YYYY-MM-DD', LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY A h:mm [vazta]', - LLLL : 'dddd, MMMM[achea] Do, YYYY, A h:mm [vazta]', - llll: 'ddd, D MMM YYYY, A h:mm [vazta]' + LLL : 'D MMMM YYYY [kl.] HH:mm', + LLLL : 'dddd D MMMM YYYY [kl.] HH:mm', + lll : 'D MMM YYYY HH:mm', + llll : 'ddd D MMM YYYY HH:mm' }, calendar : { - sameDay: '[Aiz] LT', - nextDay: '[Faleam] LT', - nextWeek: '[Ieta to] dddd[,] LT', - lastDay: '[Kal] LT', - lastWeek: '[Fatlo] dddd[,] LT', + sameDay: '[Idag] LT', + nextDay: '[Imorgon] LT', + lastDay: '[Igår] LT', + nextWeek: '[På] dddd LT', + lastWeek: '[I] dddd[s] LT', sameElse: 'L' }, relativeTime : { - future : '%s', - past : '%s adim', - s : processRelativeTime, - ss : processRelativeTime, - m : processRelativeTime, - mm : processRelativeTime, - h : processRelativeTime, - hh : processRelativeTime, - d : processRelativeTime, - dd : processRelativeTime, - M : processRelativeTime, - MM : processRelativeTime, - y : processRelativeTime, - yy : processRelativeTime + future : 'om %s', + past : 'för %s sedan', + s : 'några sekunder', + ss : '%d sekunder', + m : 'en minut', + mm : '%d minuter', + h : 'en timme', + hh : '%d timmar', + d : 'en dag', + dd : '%d dagar', + M : 'en månad', + MM : '%d månader', + y : 'ett år', + yy : '%d år' }, - dayOfMonthOrdinalParse : /\d{1,2}(er)/, - ordinal : function (number, period) { - switch (period) { - // the ordinal 'er' only applies to day of the month - case 'D': - return number + 'er'; - default: - case 'M': - case 'Q': - case 'DDD': - case 'd': - case 'w': - case 'W': - return number; - } + dayOfMonthOrdinalParse: /\d{1,2}(e|a)/, + ordinal : function (number) { + var b = number % 10, + output = (~~(number % 100 / 10) === 1) ? 'e' : + (b === 1) ? 'a' : + (b === 2) ? 'a' : + (b === 3) ? 'e' : 'e'; + return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. - }, - meridiemParse: /rati|sokalli|donparam|sanje/, - meridiemHour : function (hour, meridiem) { - if (hour === 12) { - hour = 0; - } - if (meridiem === 'rati') { - return hour < 4 ? hour : hour + 12; - } else if (meridiem === 'sokalli') { - return hour; - } else if (meridiem === 'donparam') { - return hour > 12 ? hour : hour + 12; - } else if (meridiem === 'sanje') { - return hour + 12; - } - }, - meridiem : function (hour, minute, isLower) { - if (hour < 4) { - return 'rati'; - } else if (hour < 12) { - return 'sokalli'; - } else if (hour < 16) { - return 'donparam'; - } else if (hour < 20) { - return 'sanje'; - } else { - return 'rati'; - } } }); - return gomLatn; + return sv; }))); /***/ }), -/* 92 */ +/* 117 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var symbolMap = { - '1': '૧', - '2': '૨', - '3': '૩', - '4': '૪', - '5': '૫', - '6': '૬', - '7': '૭', - '8': '૮', - '9': '૯', - '0': '૦' - }, - numberMap = { - '૧': '1', - '૨': '2', - '૩': '3', - '૪': '4', - '૫': '5', - '૬': '6', - '૭': '7', - '૮': '8', - '૯': '9', - '૦': '0' - }; - - var gu = moment.defineLocale('gu', { - months: 'જાન્યુઆરી_ફેબ્રુઆરી_માર્ચ_એપ્રિલ_મે_જૂન_જુલાઈ_ઑગસ્ટ_સપ્ટેમ્બર_ઑક્ટ્બર_નવેમ્બર_ડિસેમ્બર'.split('_'), - monthsShort: 'જાન્યુ._ફેબ્રુ._માર્ચ_એપ્રિ._મે_જૂન_જુલા._ઑગ._સપ્ટે._ઑક્ટ્._નવે._ડિસે.'.split('_'), - monthsParseExact: true, - weekdays: 'રવિવાર_સોમવાર_મંગળવાર_બુધ્વાર_ગુરુવાર_શુક્રવાર_શનિવાર'.split('_'), - weekdaysShort: 'રવિ_સોમ_મંગળ_બુધ્_ગુરુ_શુક્ર_શનિ'.split('_'), - weekdaysMin: 'ર_સો_મં_બુ_ગુ_શુ_શ'.split('_'), - longDateFormat: { - LT: 'A h:mm વાગ્યે', - LTS: 'A h:mm:ss વાગ્યે', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY, A h:mm વાગ્યે', - LLLL: 'dddd, D MMMM YYYY, A h:mm વાગ્યે' - }, - calendar: { - sameDay: '[આજ] LT', - nextDay: '[કાલે] LT', - nextWeek: 'dddd, LT', - lastDay: '[ગઇકાલે] LT', - lastWeek: '[પાછલા] dddd, LT', - sameElse: 'L' - }, - relativeTime: { - future: '%s મા', - past: '%s પેહલા', - s: 'અમુક પળો', - ss: '%d સેકંડ', - m: 'એક મિનિટ', - mm: '%d મિનિટ', - h: 'એક કલાક', - hh: '%d કલાક', - d: 'એક દિવસ', - dd: '%d દિવસ', - M: 'એક મહિનો', - MM: '%d મહિનો', - y: 'એક વર્ષ', - yy: '%d વર્ષ' - }, - preparse: function (string) { - return string.replace(/[૧૨૩૪૫૬૭૮૯૦]/g, function (match) { - return numberMap[match]; - }); - }, - postformat: function (string) { - return string.replace(/\d/g, function (match) { - return symbolMap[match]; - }); + var sw = moment.defineLocale('sw', { + months : 'Januari_Februari_Machi_Aprili_Mei_Juni_Julai_Agosti_Septemba_Oktoba_Novemba_Desemba'.split('_'), + monthsShort : 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ago_Sep_Okt_Nov_Des'.split('_'), + weekdays : 'Jumapili_Jumatatu_Jumanne_Jumatano_Alhamisi_Ijumaa_Jumamosi'.split('_'), + weekdaysShort : 'Jpl_Jtat_Jnne_Jtan_Alh_Ijm_Jmos'.split('_'), + weekdaysMin : 'J2_J3_J4_J5_Al_Ij_J1'.split('_'), + weekdaysParseExact : true, + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd, D MMMM YYYY HH:mm' }, - // Gujarati notation for meridiems are quite fuzzy in practice. While there exists - // a rigid notion of a 'Pahar' it is not used as rigidly in modern Gujarati. - meridiemParse: /રાત|બપોર|સવાર|સાંજ/, - meridiemHour: function (hour, meridiem) { - if (hour === 12) { - hour = 0; - } - if (meridiem === 'રાત') { - return hour < 4 ? hour : hour + 12; - } else if (meridiem === 'સવાર') { - return hour; - } else if (meridiem === 'બપોર') { - return hour >= 10 ? hour : hour + 12; - } else if (meridiem === 'સાંજ') { - return hour + 12; - } + calendar : { + sameDay : '[leo saa] LT', + nextDay : '[kesho saa] LT', + nextWeek : '[wiki ijayo] dddd [saat] LT', + lastDay : '[jana] LT', + lastWeek : '[wiki iliyopita] dddd [saat] LT', + sameElse : 'L' }, - meridiem: function (hour, minute, isLower) { - if (hour < 4) { - return 'રાત'; - } else if (hour < 10) { - return 'સવાર'; - } else if (hour < 17) { - return 'બપોર'; - } else if (hour < 20) { - return 'સાંજ'; - } else { - return 'રાત'; - } + relativeTime : { + future : '%s baadaye', + past : 'tokea %s', + s : 'hivi punde', + ss : 'sekunde %d', + m : 'dakika moja', + mm : 'dakika %d', + h : 'saa limoja', + hh : 'masaa %d', + d : 'siku moja', + dd : 'masiku %d', + M : 'mwezi mmoja', + MM : 'miezi %d', + y : 'mwaka mmoja', + yy : 'miaka %d' }, - week: { - dow: 0, // Sunday is the first day of the week. - doy: 6 // The week that contains Jan 6th is the first week of the year. + week : { + dow : 1, // Monday is the first day of the week. + doy : 7 // The week that contains Jan 7th is the first week of the year. } }); - return gu; + return sw; }))); /***/ }), -/* 93 */ +/* 118 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var he = moment.defineLocale('he', { - months : 'ינואר_פברואר_מרץ_אפריל_מאי_יוני_יולי_אוגוסט_ספטמבר_אוקטובר_נובמבר_דצמבר'.split('_'), - monthsShort : 'ינו׳_פבר׳_מרץ_אפר׳_מאי_יוני_יולי_אוג׳_ספט׳_אוק׳_נוב׳_דצמ׳'.split('_'), - weekdays : 'ראשון_שני_שלישי_רביעי_חמישי_שישי_שבת'.split('_'), - weekdaysShort : 'א׳_ב׳_ג׳_ד׳_ה׳_ו׳_ש׳'.split('_'), - weekdaysMin : 'א_ב_ג_ד_ה_ו_ש'.split('_'), + var symbolMap = { + '1': '௧', + '2': '௨', + '3': '௩', + '4': '௪', + '5': '௫', + '6': '௬', + '7': '௭', + '8': '௮', + '9': '௯', + '0': '௦' + }, numberMap = { + '௧': '1', + '௨': '2', + '௩': '3', + '௪': '4', + '௫': '5', + '௬': '6', + '௭': '7', + '௮': '8', + '௯': '9', + '௦': '0' + }; + + var ta = moment.defineLocale('ta', { + months : 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split('_'), + monthsShort : 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split('_'), + weekdays : 'ஞாயிற்றுக்கிழமை_திங்கட்கிழமை_செவ்வாய்கிழமை_புதன்கிழமை_வியாழக்கிழமை_வெள்ளிக்கிழமை_சனிக்கிழமை'.split('_'), + weekdaysShort : 'ஞாயிறு_திங்கள்_செவ்வாய்_புதன்_வியாழன்_வெள்ளி_சனி'.split('_'), + weekdaysMin : 'ஞா_தி_செ_பு_வி_வெ_ச'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', - LL : 'D [ב]MMMM YYYY', - LLL : 'D [ב]MMMM YYYY HH:mm', - LLLL : 'dddd, D [ב]MMMM YYYY HH:mm', - l : 'D/M/YYYY', - ll : 'D MMM YYYY', - lll : 'D MMM YYYY HH:mm', - llll : 'ddd, D MMM YYYY HH:mm' + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY, HH:mm', + LLLL : 'dddd, D MMMM YYYY, HH:mm' }, calendar : { - sameDay : '[היום ב־]LT', - nextDay : '[מחר ב־]LT', - nextWeek : 'dddd [בשעה] LT', - lastDay : '[אתמול ב־]LT', - lastWeek : '[ביום] dddd [האחרון בשעה] LT', + sameDay : '[இன்று] LT', + nextDay : '[நாளை] LT', + nextWeek : 'dddd, LT', + lastDay : '[நேற்று] LT', + lastWeek : '[கடந்த வாரம்] dddd, LT', sameElse : 'L' }, relativeTime : { - future : 'בעוד %s', - past : 'לפני %s', - s : 'מספר שניות', - ss : '%d שניות', - m : 'דקה', - mm : '%d דקות', - h : 'שעה', - hh : function (number) { - if (number === 2) { - return 'שעתיים'; - } - return number + ' שעות'; - }, - d : 'יום', - dd : function (number) { - if (number === 2) { - return 'יומיים'; - } - return number + ' ימים'; - }, - M : 'חודש', - MM : function (number) { - if (number === 2) { - return 'חודשיים'; - } - return number + ' חודשים'; - }, - y : 'שנה', - yy : function (number) { - if (number === 2) { - return 'שנתיים'; - } else if (number % 10 === 0 && number !== 10) { - return number + ' שנה'; - } - return number + ' שנים'; - } + future : '%s இல்', + past : '%s முன்', + s : 'ஒரு சில விநாடிகள்', + ss : '%d விநாடிகள்', + m : 'ஒரு நிமிடம்', + mm : '%d நிமிடங்கள்', + h : 'ஒரு மணி நேரம்', + hh : '%d மணி நேரம்', + d : 'ஒரு நாள்', + dd : '%d நாட்கள்', + M : 'ஒரு மாதம்', + MM : '%d மாதங்கள்', + y : 'ஒரு வருடம்', + yy : '%d ஆண்டுகள்' }, - meridiemParse: /אחה"צ|לפנה"צ|אחרי הצהריים|לפני הצהריים|לפנות בוקר|בבוקר|בערב/i, - isPM : function (input) { - return /^(אחה"צ|אחרי הצהריים|בערב)$/.test(input); + dayOfMonthOrdinalParse: /\d{1,2}வது/, + ordinal : function (number) { + return number + 'வது'; }, + preparse: function (string) { + return string.replace(/[௧௨௩௪௫௬௭௮௯௦]/g, function (match) { + return numberMap[match]; + }); + }, + postformat: function (string) { + return string.replace(/\d/g, function (match) { + return symbolMap[match]; + }); + }, + // refer http://ta.wikipedia.org/s/1er1 + meridiemParse: /யாமம்|வைகறை|காலை|நண்பகல்|எற்பாடு|மாலை/, meridiem : function (hour, minute, isLower) { - if (hour < 5) { - return 'לפנות בוקר'; + if (hour < 2) { + return ' யாமம்'; + } else if (hour < 6) { + return ' வைகறை'; // வைகறை } else if (hour < 10) { - return 'בבוקר'; - } else if (hour < 12) { - return isLower ? 'לפנה"צ' : 'לפני הצהריים'; + return ' காலை'; // காலை + } else if (hour < 14) { + return ' நண்பகல்'; // நண்பகல் } else if (hour < 18) { - return isLower ? 'אחה"צ' : 'אחרי הצהריים'; + return ' எற்பாடு'; // எற்பாடு + } else if (hour < 22) { + return ' மாலை'; // மாலை } else { - return 'בערב'; + return ' யாமம்'; + } + }, + meridiemHour : function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'யாமம்') { + return hour < 2 ? hour : hour + 12; + } else if (meridiem === 'வைகறை' || meridiem === 'காலை') { + return hour; + } else if (meridiem === 'நண்பகல்') { + return hour >= 10 ? hour : hour + 12; + } else { + return hour + 12; } + }, + week : { + dow : 0, // Sunday is the first day of the week. + doy : 6 // The week that contains Jan 6th is the first week of the year. } }); - return he; + return ta; }))); /***/ }), -/* 94 */ +/* 119 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var symbolMap = { - '1': '१', - '2': '२', - '3': '३', - '4': '४', - '5': '५', - '6': '६', - '7': '७', - '8': '८', - '9': '९', - '0': '०' - }, - numberMap = { - '१': '1', - '२': '2', - '३': '3', - '४': '4', - '५': '5', - '६': '6', - '७': '7', - '८': '8', - '९': '9', - '०': '0' - }; - - var hi = moment.defineLocale('hi', { - months : 'जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर'.split('_'), - monthsShort : 'जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.'.split('_'), - monthsParseExact: true, - weekdays : 'रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'), - weekdaysShort : 'रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि'.split('_'), - weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split('_'), + var te = moment.defineLocale('te', { + months : 'జనవరి_ఫిబ్రవరి_మార్చి_ఏప్రిల్_మే_జూన్_జులై_ఆగస్టు_సెప్టెంబర్_అక్టోబర్_నవంబర్_డిసెంబర్'.split('_'), + monthsShort : 'జన._ఫిబ్ర._మార్చి_ఏప్రి._మే_జూన్_జులై_ఆగ._సెప్._అక్టో._నవ._డిసె.'.split('_'), + monthsParseExact : true, + weekdays : 'ఆదివారం_సోమవారం_మంగళవారం_బుధవారం_గురువారం_శుక్రవారం_శనివారం'.split('_'), + weekdaysShort : 'ఆది_సోమ_మంగళ_బుధ_గురు_శుక్ర_శని'.split('_'), + weekdaysMin : 'ఆ_సో_మం_బు_గు_శు_శ'.split('_'), longDateFormat : { - LT : 'A h:mm बजे', - LTS : 'A h:mm:ss बजे', + LT : 'A h:mm', + LTS : 'A h:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY, A h:mm बजे', - LLLL : 'dddd, D MMMM YYYY, A h:mm बजे' + LLL : 'D MMMM YYYY, A h:mm', + LLLL : 'dddd, D MMMM YYYY, A h:mm' }, calendar : { - sameDay : '[आज] LT', - nextDay : '[कल] LT', + sameDay : '[నేడు] LT', + nextDay : '[రేపు] LT', nextWeek : 'dddd, LT', - lastDay : '[कल] LT', - lastWeek : '[पिछले] dddd, LT', + lastDay : '[నిన్న] LT', + lastWeek : '[గత] dddd, LT', sameElse : 'L' }, relativeTime : { - future : '%s में', - past : '%s पहले', - s : 'कुछ ही क्षण', - ss : '%d सेकंड', - m : 'एक मिनट', - mm : '%d मिनट', - h : 'एक घंटा', - hh : '%d घंटे', - d : 'एक दिन', - dd : '%d दिन', - M : 'एक महीने', - MM : '%d महीने', - y : 'एक वर्ष', - yy : '%d वर्ष' - }, - preparse: function (string) { - return string.replace(/[१२३४५६७८९०]/g, function (match) { - return numberMap[match]; - }); - }, - postformat: function (string) { - return string.replace(/\d/g, function (match) { - return symbolMap[match]; - }); + future : '%s లో', + past : '%s క్రితం', + s : 'కొన్ని క్షణాలు', + ss : '%d సెకన్లు', + m : 'ఒక నిమిషం', + mm : '%d నిమిషాలు', + h : 'ఒక గంట', + hh : '%d గంటలు', + d : 'ఒక రోజు', + dd : '%d రోజులు', + M : 'ఒక నెల', + MM : '%d నెలలు', + y : 'ఒక సంవత్సరం', + yy : '%d సంవత్సరాలు' }, - // Hindi notation for meridiems are quite fuzzy in practice. While there exists - // a rigid notion of a 'Pahar' it is not used as rigidly in modern Hindi. - meridiemParse: /रात|सुबह|दोपहर|शाम/, + dayOfMonthOrdinalParse : /\d{1,2}వ/, + ordinal : '%dవ', + meridiemParse: /రాత్రి|ఉదయం|మధ్యాహ్నం|సాయంత్రం/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } - if (meridiem === 'रात') { + if (meridiem === 'రాత్రి') { return hour < 4 ? hour : hour + 12; - } else if (meridiem === 'सुबह') { + } else if (meridiem === 'ఉదయం') { return hour; - } else if (meridiem === 'दोपहर') { + } else if (meridiem === 'మధ్యాహ్నం') { return hour >= 10 ? hour : hour + 12; - } else if (meridiem === 'शाम') { + } else if (meridiem === 'సాయంత్రం') { return hour + 12; } }, meridiem : function (hour, minute, isLower) { if (hour < 4) { - return 'रात'; + return 'రాత్రి'; } else if (hour < 10) { - return 'सुबह'; + return 'ఉదయం'; } else if (hour < 17) { - return 'दोपहर'; + return 'మధ్యాహ్నం'; } else if (hour < 20) { - return 'शाम'; + return 'సాయంత్రం'; } else { - return 'रात'; + return 'రాత్రి'; } }, week : { @@ -14720,584 +16254,445 @@ webpackContext.id = 41; } }); - return hi; + return te; }))); /***/ }), -/* 95 */ +/* 120 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - function translate(number, withoutSuffix, key) { - var result = number + ' '; - switch (key) { - case 'ss': - if (number === 1) { - result += 'sekunda'; - } else if (number === 2 || number === 3 || number === 4) { - result += 'sekunde'; - } else { - result += 'sekundi'; - } - return result; - case 'm': - return withoutSuffix ? 'jedna minuta' : 'jedne minute'; - case 'mm': - if (number === 1) { - result += 'minuta'; - } else if (number === 2 || number === 3 || number === 4) { - result += 'minute'; - } else { - result += 'minuta'; - } - return result; - case 'h': - return withoutSuffix ? 'jedan sat' : 'jednog sata'; - case 'hh': - if (number === 1) { - result += 'sat'; - } else if (number === 2 || number === 3 || number === 4) { - result += 'sata'; - } else { - result += 'sati'; - } - return result; - case 'dd': - if (number === 1) { - result += 'dan'; - } else { - result += 'dana'; - } - return result; - case 'MM': - if (number === 1) { - result += 'mjesec'; - } else if (number === 2 || number === 3 || number === 4) { - result += 'mjeseca'; - } else { - result += 'mjeseci'; - } - return result; - case 'yy': - if (number === 1) { - result += 'godina'; - } else if (number === 2 || number === 3 || number === 4) { - result += 'godine'; - } else { - result += 'godina'; - } - return result; - } - } - - var hr = moment.defineLocale('hr', { - months : { - format: 'siječnja_veljače_ožujka_travnja_svibnja_lipnja_srpnja_kolovoza_rujna_listopada_studenoga_prosinca'.split('_'), - standalone: 'siječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac'.split('_') - }, - monthsShort : 'sij._velj._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.'.split('_'), - monthsParseExact: true, - weekdays : 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'), - weekdaysShort : 'ned._pon._uto._sri._čet._pet._sub.'.split('_'), - weekdaysMin : 'ne_po_ut_sr_če_pe_su'.split('_'), - weekdaysParseExact : true, + var tet = moment.defineLocale('tet', { + months : 'Janeiru_Fevereiru_Marsu_Abril_Maiu_Juñu_Jullu_Agustu_Setembru_Outubru_Novembru_Dezembru'.split('_'), + monthsShort : 'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'), + weekdays : 'Domingu_Segunda_Tersa_Kuarta_Kinta_Sesta_Sabadu'.split('_'), + weekdaysShort : 'Dom_Seg_Ters_Kua_Kint_Sest_Sab'.split('_'), + weekdaysMin : 'Do_Seg_Te_Ku_Ki_Ses_Sa'.split('_'), longDateFormat : { - LT : 'H:mm', - LTS : 'H:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D. MMMM YYYY', - LLL : 'D. MMMM YYYY H:mm', - LLLL : 'dddd, D. MMMM YYYY H:mm' + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { - sameDay : '[danas u] LT', - nextDay : '[sutra u] LT', - nextWeek : function () { - switch (this.day()) { - case 0: - return '[u] [nedjelju] [u] LT'; - case 3: - return '[u] [srijedu] [u] LT'; - case 6: - return '[u] [subotu] [u] LT'; - case 1: - case 2: - case 4: - case 5: - return '[u] dddd [u] LT'; - } - }, - lastDay : '[jučer u] LT', - lastWeek : function () { - switch (this.day()) { - case 0: - case 3: - return '[prošlu] dddd [u] LT'; - case 6: - return '[prošle] [subote] [u] LT'; - case 1: - case 2: - case 4: - case 5: - return '[prošli] dddd [u] LT'; - } - }, - sameElse : 'L' + sameDay: '[Ohin iha] LT', + nextDay: '[Aban iha] LT', + nextWeek: 'dddd [iha] LT', + lastDay: '[Horiseik iha] LT', + lastWeek: 'dddd [semana kotuk] [iha] LT', + sameElse: 'L' }, relativeTime : { - future : 'za %s', - past : 'prije %s', - s : 'par sekundi', - ss : translate, - m : translate, - mm : translate, - h : translate, - hh : translate, - d : 'dan', - dd : translate, - M : 'mjesec', - MM : translate, - y : 'godinu', - yy : translate + future : 'iha %s', + past : '%s liuba', + s : 'minutu balun', + ss : 'minutu %d', + m : 'minutu ida', + mm : 'minutu %d', + h : 'oras ida', + hh : 'oras %d', + d : 'loron ida', + dd : 'loron %d', + M : 'fulan ida', + MM : 'fulan %d', + y : 'tinan ida', + yy : 'tinan %d' + }, + dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, + ordinal : function (number) { + var b = number % 10, + output = (~~(number % 100 / 10) === 1) ? 'th' : + (b === 1) ? 'st' : + (b === 2) ? 'nd' : + (b === 3) ? 'rd' : 'th'; + return number + output; }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. + doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return hr; + return tet; }))); /***/ }), -/* 96 */ +/* 121 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var weekEndings = 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' '); - function translate(number, withoutSuffix, key, isFuture) { - var num = number; - switch (key) { - case 's': - return (isFuture || withoutSuffix) ? 'néhány másodperc' : 'néhány másodperce'; - case 'ss': - return num + (isFuture || withoutSuffix) ? ' másodperc' : ' másodperce'; - case 'm': - return 'egy' + (isFuture || withoutSuffix ? ' perc' : ' perce'); - case 'mm': - return num + (isFuture || withoutSuffix ? ' perc' : ' perce'); - case 'h': - return 'egy' + (isFuture || withoutSuffix ? ' óra' : ' órája'); - case 'hh': - return num + (isFuture || withoutSuffix ? ' óra' : ' órája'); - case 'd': - return 'egy' + (isFuture || withoutSuffix ? ' nap' : ' napja'); - case 'dd': - return num + (isFuture || withoutSuffix ? ' nap' : ' napja'); - case 'M': - return 'egy' + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); - case 'MM': - return num + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); - case 'y': - return 'egy' + (isFuture || withoutSuffix ? ' év' : ' éve'); - case 'yy': - return num + (isFuture || withoutSuffix ? ' év' : ' éve'); - } - return ''; - } - function week(isFuture) { - return (isFuture ? '' : '[múlt] ') + '[' + weekEndings[this.day()] + '] LT[-kor]'; - } + var suffixes = { + 0: '-ум', + 1: '-ум', + 2: '-юм', + 3: '-юм', + 4: '-ум', + 5: '-ум', + 6: '-ум', + 7: '-ум', + 8: '-ум', + 9: '-ум', + 10: '-ум', + 12: '-ум', + 13: '-ум', + 20: '-ум', + 30: '-юм', + 40: '-ум', + 50: '-ум', + 60: '-ум', + 70: '-ум', + 80: '-ум', + 90: '-ум', + 100: '-ум' + }; - var hu = moment.defineLocale('hu', { - months : 'január_február_március_április_május_június_július_augusztus_szeptember_október_november_december'.split('_'), - monthsShort : 'jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec'.split('_'), - weekdays : 'vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat'.split('_'), - weekdaysShort : 'vas_hét_kedd_sze_csüt_pén_szo'.split('_'), - weekdaysMin : 'v_h_k_sze_cs_p_szo'.split('_'), + var tg = moment.defineLocale('tg', { + months : 'январ_феврал_март_апрел_май_июн_июл_август_сентябр_октябр_ноябр_декабр'.split('_'), + monthsShort : 'янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек'.split('_'), + weekdays : 'якшанбе_душанбе_сешанбе_чоршанбе_панҷшанбе_ҷумъа_шанбе'.split('_'), + weekdaysShort : 'яшб_дшб_сшб_чшб_пшб_ҷум_шнб'.split('_'), + weekdaysMin : 'яш_дш_сш_чш_пш_ҷм_шб'.split('_'), longDateFormat : { - LT : 'H:mm', - LTS : 'H:mm:ss', - L : 'YYYY.MM.DD.', - LL : 'YYYY. MMMM D.', - LLL : 'YYYY. MMMM D. H:mm', - LLLL : 'YYYY. MMMM D., dddd H:mm' - }, - meridiemParse: /de|du/i, - isPM: function (input) { - return input.charAt(1).toLowerCase() === 'u'; - }, - meridiem : function (hours, minutes, isLower) { - if (hours < 12) { - return isLower === true ? 'de' : 'DE'; - } else { - return isLower === true ? 'du' : 'DU'; - } + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { - sameDay : '[ma] LT[-kor]', - nextDay : '[holnap] LT[-kor]', - nextWeek : function () { - return week.call(this, true); - }, - lastDay : '[tegnap] LT[-kor]', - lastWeek : function () { - return week.call(this, false); - }, + sameDay : '[Имрӯз соати] LT', + nextDay : '[Пагоҳ соати] LT', + lastDay : '[Дирӯз соати] LT', + nextWeek : 'dddd[и] [ҳафтаи оянда соати] LT', + lastWeek : 'dddd[и] [ҳафтаи гузашта соати] LT', sameElse : 'L' }, relativeTime : { - future : '%s múlva', - past : '%s', - s : translate, - ss : translate, - m : translate, - mm : translate, - h : translate, - hh : translate, - d : translate, - dd : translate, - M : translate, - MM : translate, - y : translate, - yy : translate + future : 'баъди %s', + past : '%s пеш', + s : 'якчанд сония', + m : 'як дақиқа', + mm : '%d дақиқа', + h : 'як соат', + hh : '%d соат', + d : 'як рӯз', + dd : '%d рӯз', + M : 'як моҳ', + MM : '%d моҳ', + y : 'як сол', + yy : '%d сол' + }, + meridiemParse: /шаб|субҳ|рӯз|бегоҳ/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === 'шаб') { + return hour < 4 ? hour : hour + 12; + } else if (meridiem === 'субҳ') { + return hour; + } else if (meridiem === 'рӯз') { + return hour >= 11 ? hour : hour + 12; + } else if (meridiem === 'бегоҳ') { + return hour + 12; + } + }, + meridiem: function (hour, minute, isLower) { + if (hour < 4) { + return 'шаб'; + } else if (hour < 11) { + return 'субҳ'; + } else if (hour < 16) { + return 'рӯз'; + } else if (hour < 19) { + return 'бегоҳ'; + } else { + return 'шаб'; + } + }, + dayOfMonthOrdinalParse: /\d{1,2}-(ум|юм)/, + ordinal: function (number) { + var a = number % 10, + b = number >= 100 ? 100 : null; + return number + (suffixes[number] || suffixes[a] || suffixes[b]); }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + doy : 7 // The week that contains Jan 1th is the first week of the year. } }); - return hu; + return tg; }))); /***/ }), -/* 97 */ +/* 122 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var hyAm = moment.defineLocale('hy-am', { - months : { - format: 'հունվարի_փետրվարի_մարտի_ապրիլի_մայիսի_հունիսի_հուլիսի_օգոստոսի_սեպտեմբերի_հոկտեմբերի_նոյեմբերի_դեկտեմբերի'.split('_'), - standalone: 'հունվար_փետրվար_մարտ_ապրիլ_մայիս_հունիս_հուլիս_օգոստոս_սեպտեմբեր_հոկտեմբեր_նոյեմբեր_դեկտեմբեր'.split('_') - }, - monthsShort : 'հնվ_փտր_մրտ_ապր_մյս_հնս_հլս_օգս_սպտ_հկտ_նմբ_դկտ'.split('_'), - weekdays : 'կիրակի_երկուշաբթի_երեքշաբթի_չորեքշաբթի_հինգշաբթի_ուրբաթ_շաբաթ'.split('_'), - weekdaysShort : 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'), - weekdaysMin : 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'), + var th = moment.defineLocale('th', { + months : 'มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม'.split('_'), + monthsShort : 'ม.ค._ก.พ._มี.ค._เม.ย._พ.ค._มิ.ย._ก.ค._ส.ค._ก.ย._ต.ค._พ.ย._ธ.ค.'.split('_'), + monthsParseExact: true, + weekdays : 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์'.split('_'), + weekdaysShort : 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัส_ศุกร์_เสาร์'.split('_'), // yes, three characters difference + weekdaysMin : 'อา._จ._อ._พ._พฤ._ศ._ส.'.split('_'), + weekdaysParseExact : true, longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D MMMM YYYY թ.', - LLL : 'D MMMM YYYY թ., HH:mm', - LLLL : 'dddd, D MMMM YYYY թ., HH:mm' - }, - calendar : { - sameDay: '[այսօր] LT', - nextDay: '[վաղը] LT', - lastDay: '[երեկ] LT', - nextWeek: function () { - return 'dddd [օրը ժամը] LT'; - }, - lastWeek: function () { - return '[անցած] dddd [օրը ժամը] LT'; - }, - sameElse: 'L' - }, - relativeTime : { - future : '%s հետո', - past : '%s առաջ', - s : 'մի քանի վայրկյան', - ss : '%d վայրկյան', - m : 'րոպե', - mm : '%d րոպե', - h : 'ժամ', - hh : '%d ժամ', - d : 'օր', - dd : '%d օր', - M : 'ամիս', - MM : '%d ամիս', - y : 'տարի', - yy : '%d տարի' + LT : 'H:mm', + LTS : 'H:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY เวลา H:mm', + LLLL : 'วันddddที่ D MMMM YYYY เวลา H:mm' }, - meridiemParse: /գիշերվա|առավոտվա|ցերեկվա|երեկոյան/, + meridiemParse: /ก่อนเที่ยง|หลังเที่ยง/, isPM: function (input) { - return /^(ցերեկվա|երեկոյան)$/.test(input); + return input === 'หลังเที่ยง'; }, - meridiem : function (hour) { - if (hour < 4) { - return 'գիշերվա'; - } else if (hour < 12) { - return 'առավոտվա'; - } else if (hour < 17) { - return 'ցերեկվա'; + meridiem : function (hour, minute, isLower) { + if (hour < 12) { + return 'ก่อนเที่ยง'; } else { - return 'երեկոյան'; + return 'หลังเที่ยง'; } }, - dayOfMonthOrdinalParse: /\d{1,2}|\d{1,2}-(ին|րդ)/, - ordinal: function (number, period) { - switch (period) { - case 'DDD': - case 'w': - case 'W': - case 'DDDo': - if (number === 1) { - return number + '-ին'; - } - return number + '-րդ'; - default: - return number; - } + calendar : { + sameDay : '[วันนี้ เวลา] LT', + nextDay : '[พรุ่งนี้ เวลา] LT', + nextWeek : 'dddd[หน้า เวลา] LT', + lastDay : '[เมื่อวานนี้ เวลา] LT', + lastWeek : '[วัน]dddd[ที่แล้ว เวลา] LT', + sameElse : 'L' }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. + relativeTime : { + future : 'อีก %s', + past : '%sที่แล้ว', + s : 'ไม่กี่วินาที', + ss : '%d วินาที', + m : '1 นาที', + mm : '%d นาที', + h : '1 ชั่วโมง', + hh : '%d ชั่วโมง', + d : '1 วัน', + dd : '%d วัน', + M : '1 เดือน', + MM : '%d เดือน', + y : '1 ปี', + yy : '%d ปี' } }); - return hyAm; + return th; }))); /***/ }), -/* 98 */ +/* 123 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var id = moment.defineLocale('id', { - months : 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember'.split('_'), - monthsShort : 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Agt_Sep_Okt_Nov_Des'.split('_'), - weekdays : 'Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu'.split('_'), - weekdaysShort : 'Min_Sen_Sel_Rab_Kam_Jum_Sab'.split('_'), - weekdaysMin : 'Mg_Sn_Sl_Rb_Km_Jm_Sb'.split('_'), + var tlPh = moment.defineLocale('tl-ph', { + months : 'Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre'.split('_'), + monthsShort : 'Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis'.split('_'), + weekdays : 'Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado'.split('_'), + weekdaysShort : 'Lin_Lun_Mar_Miy_Huw_Biy_Sab'.split('_'), + weekdaysMin : 'Li_Lu_Ma_Mi_Hu_Bi_Sab'.split('_'), longDateFormat : { - LT : 'HH.mm', - LTS : 'HH.mm.ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY [pukul] HH.mm', - LLLL : 'dddd, D MMMM YYYY [pukul] HH.mm' - }, - meridiemParse: /pagi|siang|sore|malam/, - meridiemHour : function (hour, meridiem) { - if (hour === 12) { - hour = 0; - } - if (meridiem === 'pagi') { - return hour; - } else if (meridiem === 'siang') { - return hour >= 11 ? hour : hour + 12; - } else if (meridiem === 'sore' || meridiem === 'malam') { - return hour + 12; - } - }, - meridiem : function (hours, minutes, isLower) { - if (hours < 11) { - return 'pagi'; - } else if (hours < 15) { - return 'siang'; - } else if (hours < 19) { - return 'sore'; - } else { - return 'malam'; - } + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'MM/D/YYYY', + LL : 'MMMM D, YYYY', + LLL : 'MMMM D, YYYY HH:mm', + LLLL : 'dddd, MMMM DD, YYYY HH:mm' }, calendar : { - sameDay : '[Hari ini pukul] LT', - nextDay : '[Besok pukul] LT', - nextWeek : 'dddd [pukul] LT', - lastDay : '[Kemarin pukul] LT', - lastWeek : 'dddd [lalu pukul] LT', - sameElse : 'L' + sameDay: 'LT [ngayong araw]', + nextDay: '[Bukas ng] LT', + nextWeek: 'LT [sa susunod na] dddd', + lastDay: 'LT [kahapon]', + lastWeek: 'LT [noong nakaraang] dddd', + sameElse: 'L' }, relativeTime : { - future : 'dalam %s', - past : '%s yang lalu', - s : 'beberapa detik', - ss : '%d detik', - m : 'semenit', - mm : '%d menit', - h : 'sejam', - hh : '%d jam', - d : 'sehari', - dd : '%d hari', - M : 'sebulan', - MM : '%d bulan', - y : 'setahun', - yy : '%d tahun' + future : 'sa loob ng %s', + past : '%s ang nakalipas', + s : 'ilang segundo', + ss : '%d segundo', + m : 'isang minuto', + mm : '%d minuto', + h : 'isang oras', + hh : '%d oras', + d : 'isang araw', + dd : '%d araw', + M : 'isang buwan', + MM : '%d buwan', + y : 'isang taon', + yy : '%d taon' + }, + dayOfMonthOrdinalParse: /\d{1,2}/, + ordinal : function (number) { + return number; }, week : { dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. + doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return id; + return tlPh; }))); /***/ }), -/* 99 */ +/* 124 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - function plural(n) { - if (n % 100 === 11) { - return true; - } else if (n % 10 === 1) { - return false; - } - return true; + var numbersNouns = 'pagh_wa’_cha’_wej_loS_vagh_jav_Soch_chorgh_Hut'.split('_'); + + function translateFuture(output) { + var time = output; + time = (output.indexOf('jaj') !== -1) ? + time.slice(0, -3) + 'leS' : + (output.indexOf('jar') !== -1) ? + time.slice(0, -3) + 'waQ' : + (output.indexOf('DIS') !== -1) ? + time.slice(0, -3) + 'nem' : + time + ' pIq'; + return time; } - function translate(number, withoutSuffix, key, isFuture) { - var result = number + ' '; - switch (key) { - case 's': - return withoutSuffix || isFuture ? 'nokkrar sekúndur' : 'nokkrum sekúndum'; - case 'ss': - if (plural(number)) { - return result + (withoutSuffix || isFuture ? 'sekúndur' : 'sekúndum'); - } - return result + 'sekúnda'; - case 'm': - return withoutSuffix ? 'mínúta' : 'mínútu'; + + function translatePast(output) { + var time = output; + time = (output.indexOf('jaj') !== -1) ? + time.slice(0, -3) + 'Hu’' : + (output.indexOf('jar') !== -1) ? + time.slice(0, -3) + 'wen' : + (output.indexOf('DIS') !== -1) ? + time.slice(0, -3) + 'ben' : + time + ' ret'; + return time; + } + + function translate(number, withoutSuffix, string, isFuture) { + var numberNoun = numberAsNoun(number); + switch (string) { + case 'ss': + return numberNoun + ' lup'; case 'mm': - if (plural(number)) { - return result + (withoutSuffix || isFuture ? 'mínútur' : 'mínútum'); - } else if (withoutSuffix) { - return result + 'mínúta'; - } - return result + 'mínútu'; + return numberNoun + ' tup'; case 'hh': - if (plural(number)) { - return result + (withoutSuffix || isFuture ? 'klukkustundir' : 'klukkustundum'); - } - return result + 'klukkustund'; - case 'd': - if (withoutSuffix) { - return 'dagur'; - } - return isFuture ? 'dag' : 'degi'; + return numberNoun + ' rep'; case 'dd': - if (plural(number)) { - if (withoutSuffix) { - return result + 'dagar'; - } - return result + (isFuture ? 'daga' : 'dögum'); - } else if (withoutSuffix) { - return result + 'dagur'; - } - return result + (isFuture ? 'dag' : 'degi'); - case 'M': - if (withoutSuffix) { - return 'mánuður'; - } - return isFuture ? 'mánuð' : 'mánuði'; + return numberNoun + ' jaj'; case 'MM': - if (plural(number)) { - if (withoutSuffix) { - return result + 'mánuðir'; - } - return result + (isFuture ? 'mánuði' : 'mánuðum'); - } else if (withoutSuffix) { - return result + 'mánuður'; - } - return result + (isFuture ? 'mánuð' : 'mánuði'); - case 'y': - return withoutSuffix || isFuture ? 'ár' : 'ári'; + return numberNoun + ' jar'; case 'yy': - if (plural(number)) { - return result + (withoutSuffix || isFuture ? 'ár' : 'árum'); - } - return result + (withoutSuffix || isFuture ? 'ár' : 'ári'); + return numberNoun + ' DIS'; } } - var is = moment.defineLocale('is', { - months : 'janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember'.split('_'), - monthsShort : 'jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des'.split('_'), - weekdays : 'sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur'.split('_'), - weekdaysShort : 'sun_mán_þri_mið_fim_fös_lau'.split('_'), - weekdaysMin : 'Su_Má_Þr_Mi_Fi_Fö_La'.split('_'), + function numberAsNoun(number) { + var hundred = Math.floor((number % 1000) / 100), + ten = Math.floor((number % 100) / 10), + one = number % 10, + word = ''; + if (hundred > 0) { + word += numbersNouns[hundred] + 'vatlh'; + } + if (ten > 0) { + word += ((word !== '') ? ' ' : '') + numbersNouns[ten] + 'maH'; + } + if (one > 0) { + word += ((word !== '') ? ' ' : '') + numbersNouns[one]; + } + return (word === '') ? 'pagh' : word; + } + + var tlh = moment.defineLocale('tlh', { + months : 'tera’ jar wa’_tera’ jar cha’_tera’ jar wej_tera’ jar loS_tera’ jar vagh_tera’ jar jav_tera’ jar Soch_tera’ jar chorgh_tera’ jar Hut_tera’ jar wa’maH_tera’ jar wa’maH wa’_tera’ jar wa’maH cha’'.split('_'), + monthsShort : 'jar wa’_jar cha’_jar wej_jar loS_jar vagh_jar jav_jar Soch_jar chorgh_jar Hut_jar wa’maH_jar wa’maH wa’_jar wa’maH cha’'.split('_'), + monthsParseExact : true, + weekdays : 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'), + weekdaysShort : 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'), + weekdaysMin : 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'), longDateFormat : { - LT : 'H:mm', - LTS : 'H:mm:ss', + LT : 'HH:mm', + LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', - LL : 'D. MMMM YYYY', - LLL : 'D. MMMM YYYY [kl.] H:mm', - LLLL : 'dddd, D. MMMM YYYY [kl.] H:mm' + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { - sameDay : '[í dag kl.] LT', - nextDay : '[á morgun kl.] LT', - nextWeek : 'dddd [kl.] LT', - lastDay : '[í gær kl.] LT', - lastWeek : '[síðasta] dddd [kl.] LT', - sameElse : 'L' + sameDay: '[DaHjaj] LT', + nextDay: '[wa’leS] LT', + nextWeek: 'LLL', + lastDay: '[wa’Hu’] LT', + lastWeek: 'LLL', + sameElse: 'L' }, relativeTime : { - future : 'eftir %s', - past : 'fyrir %s síðan', - s : translate, + future : translateFuture, + past : translatePast, + s : 'puS lup', ss : translate, - m : translate, + m : 'wa’ tup', mm : translate, - h : 'klukkustund', + h : 'wa’ rep', hh : translate, - d : translate, + d : 'wa’ jaj', dd : translate, - M : translate, + M : 'wa’ jar', MM : translate, - y : translate, + y : 'wa’ DIS', yy : translate }, dayOfMonthOrdinalParse: /\d{1,2}\./, @@ -15308,32250 +16703,27327 @@ webpackContext.id = 41; } }); - return is; + return tlh; }))); /***/ }), -/* 100 */ +/* 125 */ /***/ (function(module, exports, __webpack_require__) { -//! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; + var suffixes = { + 1: '\'inci', + 5: '\'inci', + 8: '\'inci', + 70: '\'inci', + 80: '\'inci', + 2: '\'nci', + 7: '\'nci', + 20: '\'nci', + 50: '\'nci', + 3: '\'üncü', + 4: '\'üncü', + 100: '\'üncü', + 6: '\'ncı', + 9: '\'uncu', + 10: '\'uncu', + 30: '\'uncu', + 60: '\'ıncı', + 90: '\'ıncı' + }; - var it = moment.defineLocale('it', { - months : 'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre'.split('_'), - monthsShort : 'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic'.split('_'), - weekdays : 'domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato'.split('_'), - weekdaysShort : 'dom_lun_mar_mer_gio_ven_sab'.split('_'), - weekdaysMin : 'do_lu_ma_me_gi_ve_sa'.split('_'), + var tr = moment.defineLocale('tr', { + months : 'Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık'.split('_'), + monthsShort : 'Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara'.split('_'), + weekdays : 'Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi'.split('_'), + weekdaysShort : 'Paz_Pts_Sal_Çar_Per_Cum_Cts'.split('_'), + weekdaysMin : 'Pz_Pt_Sa_Ça_Pe_Cu_Ct'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', + L : 'DD.MM.YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd D MMMM YYYY HH:mm' + LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { - sameDay: '[Oggi alle] LT', - nextDay: '[Domani alle] LT', - nextWeek: 'dddd [alle] LT', - lastDay: '[Ieri alle] LT', - lastWeek: function () { - switch (this.day()) { - case 0: - return '[la scorsa] dddd [alle] LT'; - default: - return '[lo scorso] dddd [alle] LT'; - } - }, - sameElse: 'L' + sameDay : '[bugün saat] LT', + nextDay : '[yarın saat] LT', + nextWeek : '[gelecek] dddd [saat] LT', + lastDay : '[dün] LT', + lastWeek : '[geçen] dddd [saat] LT', + sameElse : 'L' }, relativeTime : { - future : function (s) { - return ((/^[0-9].+$/).test(s) ? 'tra' : 'in') + ' ' + s; - }, - past : '%s fa', - s : 'alcuni secondi', - ss : '%d secondi', - m : 'un minuto', - mm : '%d minuti', - h : 'un\'ora', - hh : '%d ore', - d : 'un giorno', - dd : '%d giorni', - M : 'un mese', - MM : '%d mesi', - y : 'un anno', - yy : '%d anni' + future : '%s sonra', + past : '%s önce', + s : 'birkaç saniye', + ss : '%d saniye', + m : 'bir dakika', + mm : '%d dakika', + h : 'bir saat', + hh : '%d saat', + d : 'bir gün', + dd : '%d gün', + M : 'bir ay', + MM : '%d ay', + y : 'bir yıl', + yy : '%d yıl' + }, + ordinal: function (number, period) { + switch (period) { + case 'd': + case 'D': + case 'Do': + case 'DD': + return number; + default: + if (number === 0) { // special case for zero + return number + '\'ıncı'; + } + var a = number % 10, + b = number % 100 - a, + c = number >= 100 ? 100 : null; + return number + (suffixes[a] || suffixes[b] || suffixes[c]); + } }, - dayOfMonthOrdinalParse : /\d{1,2}º/, - ordinal: '%dº', week : { dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + doy : 7 // The week that contains Jan 7th is the first week of the year. } }); - return it; + return tr; }))); /***/ }), -/* 101 */ +/* 126 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var itCh = moment.defineLocale('it-ch', { - months : 'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre'.split('_'), - monthsShort : 'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic'.split('_'), - weekdays : 'domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato'.split('_'), - weekdaysShort : 'dom_lun_mar_mer_gio_ven_sab'.split('_'), - weekdaysMin : 'do_lu_ma_me_gi_ve_sa'.split('_'), + // After the year there should be a slash and the amount of years since December 26, 1979 in Roman numerals. + // This is currently too difficult (maybe even impossible) to add. + var tzl = moment.defineLocale('tzl', { + months : 'Januar_Fevraglh_Març_Avrïu_Mai_Gün_Julia_Guscht_Setemvar_Listopäts_Noemvar_Zecemvar'.split('_'), + monthsShort : 'Jan_Fev_Mar_Avr_Mai_Gün_Jul_Gus_Set_Lis_Noe_Zec'.split('_'), + weekdays : 'Súladi_Lúneçi_Maitzi_Márcuri_Xhúadi_Viénerçi_Sáturi'.split('_'), + weekdaysShort : 'Súl_Lún_Mai_Már_Xhú_Vié_Sát'.split('_'), + weekdaysMin : 'Sú_Lú_Ma_Má_Xh_Vi_Sá'.split('_'), longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', + LT : 'HH.mm', + LTS : 'HH.mm.ss', L : 'DD.MM.YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd D MMMM YYYY HH:mm' + LL : 'D. MMMM [dallas] YYYY', + LLL : 'D. MMMM [dallas] YYYY HH.mm', + LLLL : 'dddd, [li] D. MMMM [dallas] YYYY HH.mm' + }, + meridiemParse: /d\'o|d\'a/i, + isPM : function (input) { + return 'd\'o' === input.toLowerCase(); + }, + meridiem : function (hours, minutes, isLower) { + if (hours > 11) { + return isLower ? 'd\'o' : 'D\'O'; + } else { + return isLower ? 'd\'a' : 'D\'A'; + } }, calendar : { - sameDay: '[Oggi alle] LT', - nextDay: '[Domani alle] LT', - nextWeek: 'dddd [alle] LT', - lastDay: '[Ieri alle] LT', - lastWeek: function () { - switch (this.day()) { - case 0: - return '[la scorsa] dddd [alle] LT'; - default: - return '[lo scorso] dddd [alle] LT'; - } - }, - sameElse: 'L' + sameDay : '[oxhi à] LT', + nextDay : '[demà à] LT', + nextWeek : 'dddd [à] LT', + lastDay : '[ieiri à] LT', + lastWeek : '[sür el] dddd [lasteu à] LT', + sameElse : 'L' }, relativeTime : { - future : function (s) { - return ((/^[0-9].+$/).test(s) ? 'tra' : 'in') + ' ' + s; - }, - past : '%s fa', - s : 'alcuni secondi', - ss : '%d secondi', - m : 'un minuto', - mm : '%d minuti', - h : 'un\'ora', - hh : '%d ore', - d : 'un giorno', - dd : '%d giorni', - M : 'un mese', - MM : '%d mesi', - y : 'un anno', - yy : '%d anni' + future : 'osprei %s', + past : 'ja%s', + s : processRelativeTime, + ss : processRelativeTime, + m : processRelativeTime, + mm : processRelativeTime, + h : processRelativeTime, + hh : processRelativeTime, + d : processRelativeTime, + dd : processRelativeTime, + M : processRelativeTime, + MM : processRelativeTime, + y : processRelativeTime, + yy : processRelativeTime }, - dayOfMonthOrdinalParse : /\d{1,2}º/, - ordinal: '%dº', + dayOfMonthOrdinalParse: /\d{1,2}\./, + ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return itCh; + function processRelativeTime(number, withoutSuffix, key, isFuture) { + var format = { + 's': ['viensas secunds', '\'iensas secunds'], + 'ss': [number + ' secunds', '' + number + ' secunds'], + 'm': ['\'n míut', '\'iens míut'], + 'mm': [number + ' míuts', '' + number + ' míuts'], + 'h': ['\'n þora', '\'iensa þora'], + 'hh': [number + ' þoras', '' + number + ' þoras'], + 'd': ['\'n ziua', '\'iensa ziua'], + 'dd': [number + ' ziuas', '' + number + ' ziuas'], + 'M': ['\'n mes', '\'iens mes'], + 'MM': [number + ' mesen', '' + number + ' mesen'], + 'y': ['\'n ar', '\'iens ar'], + 'yy': [number + ' ars', '' + number + ' ars'] + }; + return isFuture ? format[key][0] : (withoutSuffix ? format[key][0] : format[key][1]); + } + + return tzl; }))); /***/ }), -/* 102 */ +/* 127 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var ja = moment.defineLocale('ja', { - months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), - monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), - weekdays : '日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日'.split('_'), - weekdaysShort : '日_月_火_水_木_金_土'.split('_'), - weekdaysMin : '日_月_火_水_木_金_土'.split('_'), + var tzm = moment.defineLocale('tzm', { + months : 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'), + monthsShort : 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'), + weekdays : 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), + weekdaysShort : 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), + weekdaysMin : 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), longDateFormat : { LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'YYYY/MM/DD', - LL : 'YYYY年M月D日', - LLL : 'YYYY年M月D日 HH:mm', - LLLL : 'YYYY年M月D日 dddd HH:mm', - l : 'YYYY/MM/DD', - ll : 'YYYY年M月D日', - lll : 'YYYY年M月D日 HH:mm', - llll : 'YYYY年M月D日(ddd) HH:mm' - }, - meridiemParse: /午前|午後/i, - isPM : function (input) { - return input === '午後'; - }, - meridiem : function (hour, minute, isLower) { - if (hour < 12) { - return '午前'; - } else { - return '午後'; - } + LTS: 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { - sameDay : '[今日] LT', - nextDay : '[明日] LT', - nextWeek : function (now) { - if (now.week() < this.week()) { - return '[来週]dddd LT'; - } else { - return 'dddd LT'; - } - }, - lastDay : '[昨日] LT', - lastWeek : function (now) { - if (this.week() < now.week()) { - return '[先週]dddd LT'; - } else { - return 'dddd LT'; - } - }, - sameElse : 'L' - }, - dayOfMonthOrdinalParse : /\d{1,2}日/, - ordinal : function (number, period) { - switch (period) { - case 'd': - case 'D': - case 'DDD': - return number + '日'; - default: - return number; - } + sameDay: '[ⴰⵙⴷⵅ ⴴ] LT', + nextDay: '[ⴰⵙⴽⴰ ⴴ] LT', + nextWeek: 'dddd [ⴴ] LT', + lastDay: '[ⴰⵚⴰⵏⵜ ⴴ] LT', + lastWeek: 'dddd [ⴴ] LT', + sameElse: 'L' }, relativeTime : { - future : '%s後', - past : '%s前', - s : '数秒', - ss : '%d秒', - m : '1分', - mm : '%d分', - h : '1時間', - hh : '%d時間', - d : '1日', - dd : '%d日', - M : '1ヶ月', - MM : '%dヶ月', - y : '1年', - yy : '%d年' + future : 'ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ %s', + past : 'ⵢⴰⵏ %s', + s : 'ⵉⵎⵉⴽ', + ss : '%d ⵉⵎⵉⴽ', + m : 'ⵎⵉⵏⵓⴺ', + mm : '%d ⵎⵉⵏⵓⴺ', + h : 'ⵙⴰⵄⴰ', + hh : '%d ⵜⴰⵙⵙⴰⵄⵉⵏ', + d : 'ⴰⵙⵙ', + dd : '%d oⵙⵙⴰⵏ', + M : 'ⴰⵢoⵓⵔ', + MM : '%d ⵉⵢⵢⵉⵔⵏ', + y : 'ⴰⵙⴳⴰⵙ', + yy : '%d ⵉⵙⴳⴰⵙⵏ' + }, + week : { + dow : 6, // Saturday is the first day of the week. + doy : 12 // The week that contains Jan 12th is the first week of the year. } }); - return ja; + return tzm; }))); /***/ }), -/* 103 */ +/* 128 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var jv = moment.defineLocale('jv', { - months : 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_Nopember_Desember'.split('_'), - monthsShort : 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nop_Des'.split('_'), - weekdays : 'Minggu_Senen_Seloso_Rebu_Kemis_Jemuwah_Septu'.split('_'), - weekdaysShort : 'Min_Sen_Sel_Reb_Kem_Jem_Sep'.split('_'), - weekdaysMin : 'Mg_Sn_Sl_Rb_Km_Jm_Sp'.split('_'), + var tzmLatn = moment.defineLocale('tzm-latn', { + months : 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'), + monthsShort : 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'), + weekdays : 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), + weekdaysShort : 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), + weekdaysMin : 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), longDateFormat : { - LT : 'HH.mm', - LTS : 'HH.mm.ss', + LT : 'HH:mm', + LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY [pukul] HH.mm', - LLLL : 'dddd, D MMMM YYYY [pukul] HH.mm' + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'dddd D MMMM YYYY HH:mm' }, - meridiemParse: /enjing|siyang|sonten|ndalu/, - meridiemHour : function (hour, meridiem) { - if (hour === 12) { - hour = 0; - } - if (meridiem === 'enjing') { - return hour; - } else if (meridiem === 'siyang') { - return hour >= 11 ? hour : hour + 12; - } else if (meridiem === 'sonten' || meridiem === 'ndalu') { - return hour + 12; - } + calendar : { + sameDay: '[asdkh g] LT', + nextDay: '[aska g] LT', + nextWeek: 'dddd [g] LT', + lastDay: '[assant g] LT', + lastWeek: 'dddd [g] LT', + sameElse: 'L' }, - meridiem : function (hours, minutes, isLower) { - if (hours < 11) { - return 'enjing'; - } else if (hours < 15) { - return 'siyang'; - } else if (hours < 19) { - return 'sonten'; + relativeTime : { + future : 'dadkh s yan %s', + past : 'yan %s', + s : 'imik', + ss : '%d imik', + m : 'minuḍ', + mm : '%d minuḍ', + h : 'saɛa', + hh : '%d tassaɛin', + d : 'ass', + dd : '%d ossan', + M : 'ayowr', + MM : '%d iyyirn', + y : 'asgas', + yy : '%d isgasn' + }, + week : { + dow : 6, // Saturday is the first day of the week. + doy : 12 // The week that contains Jan 12th is the first week of the year. + } + }); + + return tzmLatn; + +}))); + + +/***/ }), +/* 129 */ +/***/ (function(module, exports, __webpack_require__) { + +//! moment.js language configuration + +;(function (global, factory) { + true ? factory(__webpack_require__(10)) : + undefined +}(this, (function (moment) { 'use strict'; + + + var ugCn = moment.defineLocale('ug-cn', { + months: 'يانۋار_فېۋرال_مارت_ئاپرېل_ماي_ئىيۇن_ئىيۇل_ئاۋغۇست_سېنتەبىر_ئۆكتەبىر_نويابىر_دېكابىر'.split( + '_' + ), + monthsShort: 'يانۋار_فېۋرال_مارت_ئاپرېل_ماي_ئىيۇن_ئىيۇل_ئاۋغۇست_سېنتەبىر_ئۆكتەبىر_نويابىر_دېكابىر'.split( + '_' + ), + weekdays: 'يەكشەنبە_دۈشەنبە_سەيشەنبە_چارشەنبە_پەيشەنبە_جۈمە_شەنبە'.split( + '_' + ), + weekdaysShort: 'يە_دۈ_سە_چا_پە_جۈ_شە'.split('_'), + weekdaysMin: 'يە_دۈ_سە_چا_پە_جۈ_شە'.split('_'), + longDateFormat: { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'YYYY-MM-DD', + LL: 'YYYY-يىلىM-ئاينىڭD-كۈنى', + LLL: 'YYYY-يىلىM-ئاينىڭD-كۈنى، HH:mm', + LLLL: 'dddd، YYYY-يىلىM-ئاينىڭD-كۈنى، HH:mm' + }, + meridiemParse: /يېرىم كېچە|سەھەر|چۈشتىن بۇرۇن|چۈش|چۈشتىن كېيىن|كەچ/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if ( + meridiem === 'يېرىم كېچە' || + meridiem === 'سەھەر' || + meridiem === 'چۈشتىن بۇرۇن' + ) { + return hour; + } else if (meridiem === 'چۈشتىن كېيىن' || meridiem === 'كەچ') { + return hour + 12; } else { - return 'ndalu'; + return hour >= 11 ? hour : hour + 12; } }, - calendar : { - sameDay : '[Dinten puniko pukul] LT', - nextDay : '[Mbenjang pukul] LT', - nextWeek : 'dddd [pukul] LT', - lastDay : '[Kala wingi pukul] LT', - lastWeek : 'dddd [kepengker pukul] LT', - sameElse : 'L' + meridiem: function (hour, minute, isLower) { + var hm = hour * 100 + minute; + if (hm < 600) { + return 'يېرىم كېچە'; + } else if (hm < 900) { + return 'سەھەر'; + } else if (hm < 1130) { + return 'چۈشتىن بۇرۇن'; + } else if (hm < 1230) { + return 'چۈش'; + } else if (hm < 1800) { + return 'چۈشتىن كېيىن'; + } else { + return 'كەچ'; + } }, - relativeTime : { - future : 'wonten ing %s', - past : '%s ingkang kepengker', - s : 'sawetawis detik', - ss : '%d detik', - m : 'setunggal menit', - mm : '%d menit', - h : 'setunggal jam', - hh : '%d jam', - d : 'sedinten', - dd : '%d dinten', - M : 'sewulan', - MM : '%d wulan', - y : 'setaun', - yy : '%d taun' + calendar: { + sameDay: '[بۈگۈن سائەت] LT', + nextDay: '[ئەتە سائەت] LT', + nextWeek: '[كېلەركى] dddd [سائەت] LT', + lastDay: '[تۆنۈگۈن] LT', + lastWeek: '[ئالدىنقى] dddd [سائەت] LT', + sameElse: 'L' }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. + relativeTime: { + future: '%s كېيىن', + past: '%s بۇرۇن', + s: 'نەچچە سېكونت', + ss: '%d سېكونت', + m: 'بىر مىنۇت', + mm: '%d مىنۇت', + h: 'بىر سائەت', + hh: '%d سائەت', + d: 'بىر كۈن', + dd: '%d كۈن', + M: 'بىر ئاي', + MM: '%d ئاي', + y: 'بىر يىل', + yy: '%d يىل' + }, + + dayOfMonthOrdinalParse: /\d{1,2}(-كۈنى|-ئاي|-ھەپتە)/, + ordinal: function (number, period) { + switch (period) { + case 'd': + case 'D': + case 'DDD': + return number + '-كۈنى'; + case 'w': + case 'W': + return number + '-ھەپتە'; + default: + return number; + } + }, + preparse: function (string) { + return string.replace(/،/g, ','); + }, + postformat: function (string) { + return string.replace(/,/g, '،'); + }, + week: { + // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效 + dow: 1, // Monday is the first day of the week. + doy: 7 // The week that contains Jan 1st is the first week of the year. } }); - return jv; + return ugCn; }))); /***/ }), -/* 104 */ +/* 130 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var ka = moment.defineLocale('ka', { + function plural(word, num) { + var forms = word.split('_'); + return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); + } + function relativeTimeWithPlural(number, withoutSuffix, key) { + var format = { + 'ss': withoutSuffix ? 'секунда_секунди_секунд' : 'секунду_секунди_секунд', + 'mm': withoutSuffix ? 'хвилина_хвилини_хвилин' : 'хвилину_хвилини_хвилин', + 'hh': withoutSuffix ? 'година_години_годин' : 'годину_години_годин', + 'dd': 'день_дні_днів', + 'MM': 'місяць_місяці_місяців', + 'yy': 'рік_роки_років' + }; + if (key === 'm') { + return withoutSuffix ? 'хвилина' : 'хвилину'; + } + else if (key === 'h') { + return withoutSuffix ? 'година' : 'годину'; + } + else { + return number + ' ' + plural(format[key], +number); + } + } + function weekdaysCaseReplace(m, format) { + var weekdays = { + 'nominative': 'неділя_понеділок_вівторок_середа_четвер_п’ятниця_субота'.split('_'), + 'accusative': 'неділю_понеділок_вівторок_середу_четвер_п’ятницю_суботу'.split('_'), + 'genitive': 'неділі_понеділка_вівторка_середи_четверга_п’ятниці_суботи'.split('_') + }; + + if (m === true) { + return weekdays['nominative'].slice(1, 7).concat(weekdays['nominative'].slice(0, 1)); + } + if (!m) { + return weekdays['nominative']; + } + + var nounCase = (/(\[[ВвУу]\]) ?dddd/).test(format) ? + 'accusative' : + ((/\[?(?:минулої|наступної)? ?\] ?dddd/).test(format) ? + 'genitive' : + 'nominative'); + return weekdays[nounCase][m.day()]; + } + function processHoursFunction(str) { + return function () { + return str + 'о' + (this.hours() === 11 ? 'б' : '') + '] LT'; + }; + } + + var uk = moment.defineLocale('uk', { months : { - standalone: 'იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი'.split('_'), - format: 'იანვარს_თებერვალს_მარტს_აპრილის_მაისს_ივნისს_ივლისს_აგვისტს_სექტემბერს_ოქტომბერს_ნოემბერს_დეკემბერს'.split('_') - }, - monthsShort : 'იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ'.split('_'), - weekdays : { - standalone: 'კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი'.split('_'), - format: 'კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს'.split('_'), - isFormat: /(წინა|შემდეგ)/ + 'format': 'січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня'.split('_'), + 'standalone': 'січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень'.split('_') }, - weekdaysShort : 'კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ'.split('_'), - weekdaysMin : 'კვ_ორ_სა_ოთ_ხუ_პა_შა'.split('_'), + monthsShort : 'січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд'.split('_'), + weekdays : weekdaysCaseReplace, + weekdaysShort : 'нд_пн_вт_ср_чт_пт_сб'.split('_'), + weekdaysMin : 'нд_пн_вт_ср_чт_пт_сб'.split('_'), longDateFormat : { - LT : 'h:mm A', - LTS : 'h:mm:ss A', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY h:mm A', - LLLL : 'dddd, D MMMM YYYY h:mm A' + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD.MM.YYYY', + LL : 'D MMMM YYYY р.', + LLL : 'D MMMM YYYY р., HH:mm', + LLLL : 'dddd, D MMMM YYYY р., HH:mm' }, calendar : { - sameDay : '[დღეს] LT[-ზე]', - nextDay : '[ხვალ] LT[-ზე]', - lastDay : '[გუშინ] LT[-ზე]', - nextWeek : '[შემდეგ] dddd LT[-ზე]', - lastWeek : '[წინა] dddd LT-ზე', - sameElse : 'L' - }, - relativeTime : { - future : function (s) { - return (/(წამი|წუთი|საათი|წელი)/).test(s) ? - s.replace(/ი$/, 'ში') : - s + 'ში'; - }, - past : function (s) { - if ((/(წამი|წუთი|საათი|დღე|თვე)/).test(s)) { - return s.replace(/(ი|ე)$/, 'ის წინ'); - } - if ((/წელი/).test(s)) { - return s.replace(/წელი$/, 'წლის წინ'); + sameDay: processHoursFunction('[Сьогодні '), + nextDay: processHoursFunction('[Завтра '), + lastDay: processHoursFunction('[Вчора '), + nextWeek: processHoursFunction('[У] dddd ['), + lastWeek: function () { + switch (this.day()) { + case 0: + case 3: + case 5: + case 6: + return processHoursFunction('[Минулої] dddd [').call(this); + case 1: + case 2: + case 4: + return processHoursFunction('[Минулого] dddd [').call(this); } }, - s : 'რამდენიმე წამი', - ss : '%d წამი', - m : 'წუთი', - mm : '%d წუთი', - h : 'საათი', - hh : '%d საათი', - d : 'დღე', - dd : '%d დღე', - M : 'თვე', - MM : '%d თვე', - y : 'წელი', - yy : '%d წელი' + sameElse: 'L' }, - dayOfMonthOrdinalParse: /0|1-ლი|მე-\d{1,2}|\d{1,2}-ე/, - ordinal : function (number) { - if (number === 0) { - return number; - } - if (number === 1) { - return number + '-ლი'; + relativeTime : { + future : 'за %s', + past : '%s тому', + s : 'декілька секунд', + ss : relativeTimeWithPlural, + m : relativeTimeWithPlural, + mm : relativeTimeWithPlural, + h : 'годину', + hh : relativeTimeWithPlural, + d : 'день', + dd : relativeTimeWithPlural, + M : 'місяць', + MM : relativeTimeWithPlural, + y : 'рік', + yy : relativeTimeWithPlural + }, + // M. E.: those two are virtually unused but a user might want to implement them for his/her website for some reason + meridiemParse: /ночі|ранку|дня|вечора/, + isPM: function (input) { + return /^(дня|вечора)$/.test(input); + }, + meridiem : function (hour, minute, isLower) { + if (hour < 4) { + return 'ночі'; + } else if (hour < 12) { + return 'ранку'; + } else if (hour < 17) { + return 'дня'; + } else { + return 'вечора'; } - if ((number < 20) || (number <= 100 && (number % 20 === 0)) || (number % 100 === 0)) { - return 'მე-' + number; + }, + dayOfMonthOrdinalParse: /\d{1,2}-(й|го)/, + ordinal: function (number, period) { + switch (period) { + case 'M': + case 'd': + case 'DDD': + case 'w': + case 'W': + return number + '-й'; + case 'D': + return number + '-го'; + default: + return number; } - return number + '-ე'; }, week : { - dow : 1, - doy : 7 + dow : 1, // Monday is the first day of the week. + doy : 7 // The week that contains Jan 7th is the first week of the year. } }); - return ka; + return uk; }))); /***/ }), -/* 105 */ +/* 131 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var suffixes = { - 0: '-ші', - 1: '-ші', - 2: '-ші', - 3: '-ші', - 4: '-ші', - 5: '-ші', - 6: '-шы', - 7: '-ші', - 8: '-ші', - 9: '-шы', - 10: '-шы', - 20: '-шы', - 30: '-шы', - 40: '-шы', - 50: '-ші', - 60: '-шы', - 70: '-ші', - 80: '-ші', - 90: '-шы', - 100: '-ші' - }; + var months = [ + 'جنوری', + 'فروری', + 'مارچ', + 'اپریل', + 'مئی', + 'جون', + 'جولائی', + 'اگست', + 'ستمبر', + 'اکتوبر', + 'نومبر', + 'دسمبر' + ]; + var days = [ + 'اتوار', + 'پیر', + 'منگل', + 'بدھ', + 'جمعرات', + 'جمعہ', + 'ہفتہ' + ]; - var kk = moment.defineLocale('kk', { - months : 'қаңтар_ақпан_наурыз_сәуір_мамыр_маусым_шілде_тамыз_қыркүйек_қазан_қараша_желтоқсан'.split('_'), - monthsShort : 'қаң_ақп_нау_сәу_мам_мау_шіл_там_қыр_қаз_қар_жел'.split('_'), - weekdays : 'жексенбі_дүйсенбі_сейсенбі_сәрсенбі_бейсенбі_жұма_сенбі'.split('_'), - weekdaysShort : 'жек_дүй_сей_сәр_бей_жұм_сен'.split('_'), - weekdaysMin : 'жк_дй_сй_ср_бй_жм_сн'.split('_'), + var ur = moment.defineLocale('ur', { + months : months, + monthsShort : months, + weekdays : days, + weekdaysShort : days, + weekdaysMin : days, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', - L : 'DD.MM.YYYY', + L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd, D MMMM YYYY HH:mm' + LLLL : 'dddd، D MMMM YYYY HH:mm' + }, + meridiemParse: /صبح|شام/, + isPM : function (input) { + return 'شام' === input; + }, + meridiem : function (hour, minute, isLower) { + if (hour < 12) { + return 'صبح'; + } + return 'شام'; }, calendar : { - sameDay : '[Бүгін сағат] LT', - nextDay : '[Ертең сағат] LT', - nextWeek : 'dddd [сағат] LT', - lastDay : '[Кеше сағат] LT', - lastWeek : '[Өткен аптаның] dddd [сағат] LT', + sameDay : '[آج بوقت] LT', + nextDay : '[کل بوقت] LT', + nextWeek : 'dddd [بوقت] LT', + lastDay : '[گذشتہ روز بوقت] LT', + lastWeek : '[گذشتہ] dddd [بوقت] LT', sameElse : 'L' }, relativeTime : { - future : '%s ішінде', - past : '%s бұрын', - s : 'бірнеше секунд', - ss : '%d секунд', - m : 'бір минут', - mm : '%d минут', - h : 'бір сағат', - hh : '%d сағат', - d : 'бір күн', - dd : '%d күн', - M : 'бір ай', - MM : '%d ай', - y : 'бір жыл', - yy : '%d жыл' + future : '%s بعد', + past : '%s قبل', + s : 'چند سیکنڈ', + ss : '%d سیکنڈ', + m : 'ایک منٹ', + mm : '%d منٹ', + h : 'ایک گھنٹہ', + hh : '%d گھنٹے', + d : 'ایک دن', + dd : '%d دن', + M : 'ایک ماہ', + MM : '%d ماہ', + y : 'ایک سال', + yy : '%d سال' }, - dayOfMonthOrdinalParse: /\d{1,2}-(ші|шы)/, - ordinal : function (number) { - var a = number % 10, - b = number >= 100 ? 100 : null; - return number + (suffixes[number] || suffixes[a] || suffixes[b]); + preparse: function (string) { + return string.replace(/،/g, ','); + }, + postformat: function (string) { + return string.replace(/,/g, '،'); }, week : { dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. + doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return kk; + return ur; }))); /***/ }), -/* 106 */ +/* 132 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var symbolMap = { - '1': '១', - '2': '២', - '3': '៣', - '4': '៤', - '5': '៥', - '6': '៦', - '7': '៧', - '8': '៨', - '9': '៩', - '0': '០' - }, numberMap = { - '១': '1', - '២': '2', - '៣': '3', - '៤': '4', - '៥': '5', - '៦': '6', - '៧': '7', - '៨': '8', - '៩': '9', - '០': '0' - }; - - var km = moment.defineLocale('km', { - months: 'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split( - '_' - ), - monthsShort: 'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split( - '_' - ), - weekdays: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'), - weekdaysShort: 'អា_ច_អ_ព_ព្រ_សុ_ស'.split('_'), - weekdaysMin: 'អា_ច_អ_ព_ព្រ_សុ_ស'.split('_'), - weekdaysParseExact: true, - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd, D MMMM YYYY HH:mm' - }, - meridiemParse: /ព្រឹក|ល្ងាច/, - isPM: function (input) { - return input === 'ល្ងាច'; - }, - meridiem: function (hour, minute, isLower) { - if (hour < 12) { - return 'ព្រឹក'; - } else { - return 'ល្ងាច'; - } - }, - calendar: { - sameDay: '[ថ្ងៃនេះ ម៉ោង] LT', - nextDay: '[ស្អែក ម៉ោង] LT', - nextWeek: 'dddd [ម៉ោង] LT', - lastDay: '[ម្សិលមិញ ម៉ោង] LT', - lastWeek: 'dddd [សប្តាហ៍មុន] [ម៉ោង] LT', - sameElse: 'L' - }, - relativeTime: { - future: '%sទៀត', - past: '%sមុន', - s: 'ប៉ុន្មានវិនាទី', - ss: '%d វិនាទី', - m: 'មួយនាទី', - mm: '%d នាទី', - h: 'មួយម៉ោង', - hh: '%d ម៉ោង', - d: 'មួយថ្ងៃ', - dd: '%d ថ្ងៃ', - M: 'មួយខែ', - MM: '%d ខែ', - y: 'មួយឆ្នាំ', - yy: '%d ឆ្នាំ' + var uz = moment.defineLocale('uz', { + months : 'январ_феврал_март_апрел_май_июн_июл_август_сентябр_октябр_ноябр_декабр'.split('_'), + monthsShort : 'янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек'.split('_'), + weekdays : 'Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба'.split('_'), + weekdaysShort : 'Якш_Душ_Сеш_Чор_Пай_Жум_Шан'.split('_'), + weekdaysMin : 'Як_Ду_Се_Чо_Па_Жу_Ша'.split('_'), + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM YYYY', + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'D MMMM YYYY, dddd HH:mm' }, - dayOfMonthOrdinalParse : /ទី\d{1,2}/, - ordinal : 'ទី%d', - preparse: function (string) { - return string.replace(/[១២៣៤៥៦៧៨៩០]/g, function (match) { - return numberMap[match]; - }); + calendar : { + sameDay : '[Бугун соат] LT [да]', + nextDay : '[Эртага] LT [да]', + nextWeek : 'dddd [куни соат] LT [да]', + lastDay : '[Кеча соат] LT [да]', + lastWeek : '[Утган] dddd [куни соат] LT [да]', + sameElse : 'L' }, - postformat: function (string) { - return string.replace(/\d/g, function (match) { - return symbolMap[match]; - }); + relativeTime : { + future : 'Якин %s ичида', + past : 'Бир неча %s олдин', + s : 'фурсат', + ss : '%d фурсат', + m : 'бир дакика', + mm : '%d дакика', + h : 'бир соат', + hh : '%d соат', + d : 'бир кун', + dd : '%d кун', + M : 'бир ой', + MM : '%d ой', + y : 'бир йил', + yy : '%d йил' }, - week: { - dow: 1, // Monday is the first day of the week. - doy: 4 // The week that contains Jan 4th is the first week of the year. + week : { + dow : 1, // Monday is the first day of the week. + doy : 7 // The week that contains Jan 4th is the first week of the year. } }); - return km; + return uz; }))); /***/ }), -/* 107 */ +/* 133 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var symbolMap = { - '1': '೧', - '2': '೨', - '3': '೩', - '4': '೪', - '5': '೫', - '6': '೬', - '7': '೭', - '8': '೮', - '9': '೯', - '0': '೦' - }, - numberMap = { - '೧': '1', - '೨': '2', - '೩': '3', - '೪': '4', - '೫': '5', - '೬': '6', - '೭': '7', - '೮': '8', - '೯': '9', - '೦': '0' - }; - - var kn = moment.defineLocale('kn', { - months : 'ಜನವರಿ_ಫೆಬ್ರವರಿ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂಬರ್_ಅಕ್ಟೋಬರ್_ನವೆಂಬರ್_ಡಿಸೆಂಬರ್'.split('_'), - monthsShort : 'ಜನ_ಫೆಬ್ರ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂ_ಅಕ್ಟೋ_ನವೆಂ_ಡಿಸೆಂ'.split('_'), - monthsParseExact: true, - weekdays : 'ಭಾನುವಾರ_ಸೋಮವಾರ_ಮಂಗಳವಾರ_ಬುಧವಾರ_ಗುರುವಾರ_ಶುಕ್ರವಾರ_ಶನಿವಾರ'.split('_'), - weekdaysShort : 'ಭಾನು_ಸೋಮ_ಮಂಗಳ_ಬುಧ_ಗುರು_ಶುಕ್ರ_ಶನಿ'.split('_'), - weekdaysMin : 'ಭಾ_ಸೋ_ಮಂ_ಬು_ಗು_ಶು_ಶ'.split('_'), + var uzLatn = moment.defineLocale('uz-latn', { + months : 'Yanvar_Fevral_Mart_Aprel_May_Iyun_Iyul_Avgust_Sentabr_Oktabr_Noyabr_Dekabr'.split('_'), + monthsShort : 'Yan_Fev_Mar_Apr_May_Iyun_Iyul_Avg_Sen_Okt_Noy_Dek'.split('_'), + weekdays : 'Yakshanba_Dushanba_Seshanba_Chorshanba_Payshanba_Juma_Shanba'.split('_'), + weekdaysShort : 'Yak_Dush_Sesh_Chor_Pay_Jum_Shan'.split('_'), + weekdaysMin : 'Ya_Du_Se_Cho_Pa_Ju_Sha'.split('_'), longDateFormat : { - LT : 'A h:mm', - LTS : 'A h:mm:ss', + LT : 'HH:mm', + LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY, A h:mm', - LLLL : 'dddd, D MMMM YYYY, A h:mm' + LLL : 'D MMMM YYYY HH:mm', + LLLL : 'D MMMM YYYY, dddd HH:mm' }, calendar : { - sameDay : '[ಇಂದು] LT', - nextDay : '[ನಾಳೆ] LT', - nextWeek : 'dddd, LT', - lastDay : '[ನಿನ್ನೆ] LT', - lastWeek : '[ಕೊನೆಯ] dddd, LT', + sameDay : '[Bugun soat] LT [da]', + nextDay : '[Ertaga] LT [da]', + nextWeek : 'dddd [kuni soat] LT [da]', + lastDay : '[Kecha soat] LT [da]', + lastWeek : '[O\'tgan] dddd [kuni soat] LT [da]', sameElse : 'L' }, relativeTime : { - future : '%s ನಂತರ', - past : '%s ಹಿಂದೆ', - s : 'ಕೆಲವು ಕ್ಷಣಗಳು', - ss : '%d ಸೆಕೆಂಡುಗಳು', - m : 'ಒಂದು ನಿಮಿಷ', - mm : '%d ನಿಮಿಷ', - h : 'ಒಂದು ಗಂಟೆ', - hh : '%d ಗಂಟೆ', - d : 'ಒಂದು ದಿನ', - dd : '%d ದಿನ', - M : 'ಒಂದು ತಿಂಗಳು', - MM : '%d ತಿಂಗಳು', - y : 'ಒಂದು ವರ್ಷ', - yy : '%d ವರ್ಷ' - }, - preparse: function (string) { - return string.replace(/[೧೨೩೪೫೬೭೮೯೦]/g, function (match) { - return numberMap[match]; - }); - }, - postformat: function (string) { - return string.replace(/\d/g, function (match) { - return symbolMap[match]; - }); - }, - meridiemParse: /ರಾತ್ರಿ|ಬೆಳಿಗ್ಗೆ|ಮಧ್ಯಾಹ್ನ|ಸಂಜೆ/, - meridiemHour : function (hour, meridiem) { - if (hour === 12) { - hour = 0; - } - if (meridiem === 'ರಾತ್ರಿ') { - return hour < 4 ? hour : hour + 12; - } else if (meridiem === 'ಬೆಳಿಗ್ಗೆ') { - return hour; - } else if (meridiem === 'ಮಧ್ಯಾಹ್ನ') { - return hour >= 10 ? hour : hour + 12; - } else if (meridiem === 'ಸಂಜೆ') { - return hour + 12; - } - }, - meridiem : function (hour, minute, isLower) { - if (hour < 4) { - return 'ರಾತ್ರಿ'; - } else if (hour < 10) { - return 'ಬೆಳಿಗ್ಗೆ'; - } else if (hour < 17) { - return 'ಮಧ್ಯಾಹ್ನ'; - } else if (hour < 20) { - return 'ಸಂಜೆ'; - } else { - return 'ರಾತ್ರಿ'; - } - }, - dayOfMonthOrdinalParse: /\d{1,2}(ನೇ)/, - ordinal : function (number) { - return number + 'ನೇ'; + future : 'Yaqin %s ichida', + past : 'Bir necha %s oldin', + s : 'soniya', + ss : '%d soniya', + m : 'bir daqiqa', + mm : '%d daqiqa', + h : 'bir soat', + hh : '%d soat', + d : 'bir kun', + dd : '%d kun', + M : 'bir oy', + MM : '%d oy', + y : 'bir yil', + yy : '%d yil' }, week : { - dow : 0, // Sunday is the first day of the week. - doy : 6 // The week that contains Jan 6th is the first week of the year. + dow : 1, // Monday is the first day of the week. + doy : 7 // The week that contains Jan 7th is the first week of the year. } }); - return kn; + return uzLatn; }))); /***/ }), -/* 108 */ +/* 134 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var ko = moment.defineLocale('ko', { - months : '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'), - monthsShort : '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'), - weekdays : '일요일_월요일_화요일_수요일_목요일_금요일_토요일'.split('_'), - weekdaysShort : '일_월_화_수_목_금_토'.split('_'), - weekdaysMin : '일_월_화_수_목_금_토'.split('_'), + var vi = moment.defineLocale('vi', { + months : 'tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12'.split('_'), + monthsShort : 'Th01_Th02_Th03_Th04_Th05_Th06_Th07_Th08_Th09_Th10_Th11_Th12'.split('_'), + monthsParseExact : true, + weekdays : 'chủ nhật_thứ hai_thứ ba_thứ tư_thứ năm_thứ sáu_thứ bảy'.split('_'), + weekdaysShort : 'CN_T2_T3_T4_T5_T6_T7'.split('_'), + weekdaysMin : 'CN_T2_T3_T4_T5_T6_T7'.split('_'), + weekdaysParseExact : true, + meridiemParse: /sa|ch/i, + isPM : function (input) { + return /^ch$/i.test(input); + }, + meridiem : function (hours, minutes, isLower) { + if (hours < 12) { + return isLower ? 'sa' : 'SA'; + } else { + return isLower ? 'ch' : 'CH'; + } + }, longDateFormat : { - LT : 'A h:mm', - LTS : 'A h:mm:ss', - L : 'YYYY.MM.DD.', - LL : 'YYYY년 MMMM D일', - LLL : 'YYYY년 MMMM D일 A h:mm', - LLLL : 'YYYY년 MMMM D일 dddd A h:mm', - l : 'YYYY.MM.DD.', - ll : 'YYYY년 MMMM D일', - lll : 'YYYY년 MMMM D일 A h:mm', - llll : 'YYYY년 MMMM D일 dddd A h:mm' + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'DD/MM/YYYY', + LL : 'D MMMM [năm] YYYY', + LLL : 'D MMMM [năm] YYYY HH:mm', + LLLL : 'dddd, D MMMM [năm] YYYY HH:mm', + l : 'DD/M/YYYY', + ll : 'D MMM YYYY', + lll : 'D MMM YYYY HH:mm', + llll : 'ddd, D MMM YYYY HH:mm' }, calendar : { - sameDay : '오늘 LT', - nextDay : '내일 LT', - nextWeek : 'dddd LT', - lastDay : '어제 LT', - lastWeek : '지난주 dddd LT', - sameElse : 'L' + sameDay: '[Hôm nay lúc] LT', + nextDay: '[Ngày mai lúc] LT', + nextWeek: 'dddd [tuần tới lúc] LT', + lastDay: '[Hôm qua lúc] LT', + lastWeek: 'dddd [tuần rồi lúc] LT', + sameElse: 'L' }, relativeTime : { - future : '%s 후', - past : '%s 전', - s : '몇 초', - ss : '%d초', - m : '1분', - mm : '%d분', - h : '한 시간', - hh : '%d시간', - d : '하루', - dd : '%d일', - M : '한 달', - MM : '%d달', - y : '일 년', - yy : '%d년' - }, - dayOfMonthOrdinalParse : /\d{1,2}(일|월|주)/, - ordinal : function (number, period) { - switch (period) { - case 'd': - case 'D': - case 'DDD': - return number + '일'; - case 'M': - return number + '월'; - case 'w': - case 'W': - return number + '주'; - default: - return number; - } + future : '%s tới', + past : '%s trước', + s : 'vài giây', + ss : '%d giây' , + m : 'một phút', + mm : '%d phút', + h : 'một giờ', + hh : '%d giờ', + d : 'một ngày', + dd : '%d ngày', + M : 'một tháng', + MM : '%d tháng', + y : 'một năm', + yy : '%d năm' }, - meridiemParse : /오전|오후/, - isPM : function (token) { - return token === '오후'; + dayOfMonthOrdinalParse: /\d{1,2}/, + ordinal : function (number) { + return number; }, - meridiem : function (hour, minute, isUpper) { - return hour < 12 ? '오전' : '오후'; + week : { + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return ko; + return vi; }))); /***/ }), -/* 109 */ +/* 135 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var symbolMap = { - '1': '١', - '2': '٢', - '3': '٣', - '4': '٤', - '5': '٥', - '6': '٦', - '7': '٧', - '8': '٨', - '9': '٩', - '0': '٠' - }, numberMap = { - '١': '1', - '٢': '2', - '٣': '3', - '٤': '4', - '٥': '5', - '٦': '6', - '٧': '7', - '٨': '8', - '٩': '9', - '٠': '0' - }, - months = [ - 'کانونی دووەم', - 'شوبات', - 'ئازار', - 'نیسان', - 'ئایار', - 'حوزەیران', - 'تەمموز', - 'ئاب', - 'ئەیلوول', - 'تشرینی یەكەم', - 'تشرینی دووەم', - 'كانونی یەکەم' - ]; - - - var ku = moment.defineLocale('ku', { - months : months, - monthsShort : months, - weekdays : 'یه‌كشه‌ممه‌_دووشه‌ممه‌_سێشه‌ممه‌_چوارشه‌ممه‌_پێنجشه‌ممه‌_هه‌ینی_شه‌ممه‌'.split('_'), - weekdaysShort : 'یه‌كشه‌م_دووشه‌م_سێشه‌م_چوارشه‌م_پێنجشه‌م_هه‌ینی_شه‌ممه‌'.split('_'), - weekdaysMin : 'ی_د_س_چ_پ_ه_ش'.split('_'), + var xPseudo = moment.defineLocale('x-pseudo', { + months : 'J~áñúá~rý_F~ébrú~árý_~Márc~h_Áp~ríl_~Máý_~Júñé~_Júl~ý_Áú~gúst~_Sép~témb~ér_Ó~ctób~ér_Ñ~óvém~bér_~Décé~mbér'.split('_'), + monthsShort : 'J~áñ_~Féb_~Már_~Ápr_~Máý_~Júñ_~Júl_~Áúg_~Sép_~Óct_~Ñóv_~Déc'.split('_'), + monthsParseExact : true, + weekdays : 'S~úñdá~ý_Mó~ñdáý~_Túé~sdáý~_Wéd~ñésd~áý_T~húrs~dáý_~Fríd~áý_S~átúr~dáý'.split('_'), + weekdaysShort : 'S~úñ_~Móñ_~Túé_~Wéd_~Thú_~Frí_~Sát'.split('_'), + weekdaysMin : 'S~ú_Mó~_Tú_~Wé_T~h_Fr~_Sá'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', - LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, - meridiemParse: /ئێواره‌|به‌یانی/, - isPM: function (input) { - return /ئێواره‌/.test(input); - }, - meridiem : function (hour, minute, isLower) { - if (hour < 12) { - return 'به‌یانی'; - } else { - return 'ئێواره‌'; - } - }, calendar : { - sameDay : '[ئه‌مرۆ كاتژمێر] LT', - nextDay : '[به‌یانی كاتژمێر] LT', - nextWeek : 'dddd [كاتژمێر] LT', - lastDay : '[دوێنێ كاتژمێر] LT', - lastWeek : 'dddd [كاتژمێر] LT', + sameDay : '[T~ódá~ý át] LT', + nextDay : '[T~ómó~rró~w át] LT', + nextWeek : 'dddd [át] LT', + lastDay : '[Ý~ést~érdá~ý át] LT', + lastWeek : '[L~ást] dddd [át] LT', sameElse : 'L' }, relativeTime : { - future : 'له‌ %s', - past : '%s', - s : 'چه‌ند چركه‌یه‌ك', - ss : 'چركه‌ %d', - m : 'یه‌ك خوله‌ك', - mm : '%d خوله‌ك', - h : 'یه‌ك كاتژمێر', - hh : '%d كاتژمێر', - d : 'یه‌ك ڕۆژ', - dd : '%d ڕۆژ', - M : 'یه‌ك مانگ', - MM : '%d مانگ', - y : 'یه‌ك ساڵ', - yy : '%d ساڵ' - }, - preparse: function (string) { - return string.replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) { - return numberMap[match]; - }).replace(/،/g, ','); + future : 'í~ñ %s', + past : '%s á~gó', + s : 'á ~féw ~sécó~ñds', + ss : '%d s~écóñ~ds', + m : 'á ~míñ~úté', + mm : '%d m~íñú~tés', + h : 'á~ñ hó~úr', + hh : '%d h~óúrs', + d : 'á ~dáý', + dd : '%d d~áýs', + M : 'á ~móñ~th', + MM : '%d m~óñt~hs', + y : 'á ~ýéár', + yy : '%d ý~éárs' }, - postformat: function (string) { - return string.replace(/\d/g, function (match) { - return symbolMap[match]; - }).replace(/,/g, '،'); + dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, + ordinal : function (number) { + var b = number % 10, + output = (~~(number % 100 / 10) === 1) ? 'th' : + (b === 1) ? 'st' : + (b === 2) ? 'nd' : + (b === 3) ? 'rd' : 'th'; + return number + output; }, week : { - dow : 6, // Saturday is the first day of the week. - doy : 12 // The week that contains Jan 12th is the first week of the year. + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return ku; + return xPseudo; }))); /***/ }), -/* 110 */ +/* 136 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var suffixes = { - 0: '-чү', - 1: '-чи', - 2: '-чи', - 3: '-чү', - 4: '-чү', - 5: '-чи', - 6: '-чы', - 7: '-чи', - 8: '-чи', - 9: '-чу', - 10: '-чу', - 20: '-чы', - 30: '-чу', - 40: '-чы', - 50: '-чү', - 60: '-чы', - 70: '-чи', - 80: '-чи', - 90: '-чу', - 100: '-чү' - }; - - var ky = moment.defineLocale('ky', { - months : 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'), - monthsShort : 'янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_'), - weekdays : 'Жекшемби_Дүйшөмбү_Шейшемби_Шаршемби_Бейшемби_Жума_Ишемби'.split('_'), - weekdaysShort : 'Жек_Дүй_Шей_Шар_Бей_Жум_Ише'.split('_'), - weekdaysMin : 'Жк_Дй_Шй_Шр_Бй_Жм_Иш'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD.MM.YYYY', + var yo = moment.defineLocale('yo', { + months : 'Sẹ́rẹ́_Èrèlè_Ẹrẹ̀nà_Ìgbé_Èbibi_Òkùdu_Agẹmo_Ògún_Owewe_Ọ̀wàrà_Bélú_Ọ̀pẹ̀̀'.split('_'), + monthsShort : 'Sẹ́r_Èrl_Ẹrn_Ìgb_Èbi_Òkù_Agẹ_Ògú_Owe_Ọ̀wà_Bél_Ọ̀pẹ̀̀'.split('_'), + weekdays : 'Àìkú_Ajé_Ìsẹ́gun_Ọjọ́rú_Ọjọ́bọ_Ẹtì_Àbámẹ́ta'.split('_'), + weekdaysShort : 'Àìk_Ajé_Ìsẹ́_Ọjr_Ọjb_Ẹtì_Àbá'.split('_'), + weekdaysMin : 'Àì_Aj_Ìs_Ọr_Ọb_Ẹt_Àb'.split('_'), + longDateFormat : { + LT : 'h:mm A', + LTS : 'h:mm:ss A', + L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd, D MMMM YYYY HH:mm' + LLL : 'D MMMM YYYY h:mm A', + LLLL : 'dddd, D MMMM YYYY h:mm A' }, calendar : { - sameDay : '[Бүгүн саат] LT', - nextDay : '[Эртең саат] LT', - nextWeek : 'dddd [саат] LT', - lastDay : '[Кечээ саат] LT', - lastWeek : '[Өткөн аптанын] dddd [күнү] [саат] LT', + sameDay : '[Ònì ni] LT', + nextDay : '[Ọ̀la ni] LT', + nextWeek : 'dddd [Ọsẹ̀ tón\'bọ] [ni] LT', + lastDay : '[Àna ni] LT', + lastWeek : 'dddd [Ọsẹ̀ tólọ́] [ni] LT', sameElse : 'L' }, relativeTime : { - future : '%s ичинде', - past : '%s мурун', - s : 'бирнече секунд', - ss : '%d секунд', - m : 'бир мүнөт', - mm : '%d мүнөт', - h : 'бир саат', - hh : '%d саат', - d : 'бир күн', - dd : '%d күн', - M : 'бир ай', - MM : '%d ай', - y : 'бир жыл', - yy : '%d жыл' - }, - dayOfMonthOrdinalParse: /\d{1,2}-(чи|чы|чү|чу)/, - ordinal : function (number) { - var a = number % 10, - b = number >= 100 ? 100 : null; - return number + (suffixes[number] || suffixes[a] || suffixes[b]); + future : 'ní %s', + past : '%s kọjá', + s : 'ìsẹjú aayá die', + ss :'aayá %d', + m : 'ìsẹjú kan', + mm : 'ìsẹjú %d', + h : 'wákati kan', + hh : 'wákati %d', + d : 'ọjọ́ kan', + dd : 'ọjọ́ %d', + M : 'osù kan', + MM : 'osù %d', + y : 'ọdún kan', + yy : 'ọdún %d' }, + dayOfMonthOrdinalParse : /ọjọ́\s\d{1,2}/, + ordinal : 'ọjọ́ %d', week : { dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. + doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return ky; + return yo; }))); /***/ }), -/* 111 */ +/* 137 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - function processRelativeTime(number, withoutSuffix, key, isFuture) { - var format = { - 'm': ['eng Minutt', 'enger Minutt'], - 'h': ['eng Stonn', 'enger Stonn'], - 'd': ['een Dag', 'engem Dag'], - 'M': ['ee Mount', 'engem Mount'], - 'y': ['ee Joer', 'engem Joer'] - }; - return withoutSuffix ? format[key][0] : format[key][1]; - } - function processFutureTime(string) { - var number = string.substr(0, string.indexOf(' ')); - if (eifelerRegelAppliesToNumber(number)) { - return 'a ' + string; - } - return 'an ' + string; - } - function processPastTime(string) { - var number = string.substr(0, string.indexOf(' ')); - if (eifelerRegelAppliesToNumber(number)) { - return 'viru ' + string; - } - return 'virun ' + string; - } - /** - * Returns true if the word before the given number loses the '-n' ending. - * e.g. 'an 10 Deeg' but 'a 5 Deeg' - * - * @param number {integer} - * @returns {boolean} - */ - function eifelerRegelAppliesToNumber(number) { - number = parseInt(number, 10); - if (isNaN(number)) { - return false; - } - if (number < 0) { - // Negative Number --> always true - return true; - } else if (number < 10) { - // Only 1 digit - if (4 <= number && number <= 7) { - return true; + var zhCn = moment.defineLocale('zh-cn', { + months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), + monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), + weekdays : '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), + weekdaysShort : '周日_周一_周二_周三_周四_周五_周六'.split('_'), + weekdaysMin : '日_一_二_三_四_五_六'.split('_'), + longDateFormat : { + LT : 'HH:mm', + LTS : 'HH:mm:ss', + L : 'YYYY/MM/DD', + LL : 'YYYY年M月D日', + LLL : 'YYYY年M月D日Ah点mm分', + LLLL : 'YYYY年M月D日ddddAh点mm分', + l : 'YYYY/M/D', + ll : 'YYYY年M月D日', + lll : 'YYYY年M月D日 HH:mm', + llll : 'YYYY年M月D日dddd HH:mm' + }, + meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, + meridiemHour: function (hour, meridiem) { + if (hour === 12) { + hour = 0; } - return false; - } else if (number < 100) { - // 2 digits - var lastDigit = number % 10, firstDigit = number / 10; - if (lastDigit === 0) { - return eifelerRegelAppliesToNumber(firstDigit); + if (meridiem === '凌晨' || meridiem === '早上' || + meridiem === '上午') { + return hour; + } else if (meridiem === '下午' || meridiem === '晚上') { + return hour + 12; + } else { + // '中午' + return hour >= 11 ? hour : hour + 12; } - return eifelerRegelAppliesToNumber(lastDigit); - } else if (number < 10000) { - // 3 or 4 digits --> recursively check first digit - while (number >= 10) { - number = number / 10; + }, + meridiem : function (hour, minute, isLower) { + var hm = hour * 100 + minute; + if (hm < 600) { + return '凌晨'; + } else if (hm < 900) { + return '早上'; + } else if (hm < 1130) { + return '上午'; + } else if (hm < 1230) { + return '中午'; + } else if (hm < 1800) { + return '下午'; + } else { + return '晚上'; } - return eifelerRegelAppliesToNumber(number); - } else { - // Anything larger than 4 digits: recursively check first n-3 digits - number = number / 1000; - return eifelerRegelAppliesToNumber(number); - } - } - - var lb = moment.defineLocale('lb', { - months: 'Januar_Februar_Mäerz_Abrëll_Mee_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), - monthsShort: 'Jan._Febr._Mrz._Abr._Mee_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'), - monthsParseExact : true, - weekdays: 'Sonndeg_Méindeg_Dënschdeg_Mëttwoch_Donneschdeg_Freideg_Samschdeg'.split('_'), - weekdaysShort: 'So._Mé._Dë._Më._Do._Fr._Sa.'.split('_'), - weekdaysMin: 'So_Mé_Dë_Më_Do_Fr_Sa'.split('_'), - weekdaysParseExact : true, - longDateFormat: { - LT: 'H:mm [Auer]', - LTS: 'H:mm:ss [Auer]', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY H:mm [Auer]', - LLLL: 'dddd, D. MMMM YYYY H:mm [Auer]' }, - calendar: { - sameDay: '[Haut um] LT', - sameElse: 'L', - nextDay: '[Muer um] LT', - nextWeek: 'dddd [um] LT', - lastDay: '[Gëschter um] LT', - lastWeek: function () { - // Different date string for 'Dënschdeg' (Tuesday) and 'Donneschdeg' (Thursday) due to phonological rule - switch (this.day()) { - case 2: - case 4: - return '[Leschten] dddd [um] LT'; - default: - return '[Leschte] dddd [um] LT'; - } + calendar : { + sameDay : '[今天]LT', + nextDay : '[明天]LT', + nextWeek : '[下]ddddLT', + lastDay : '[昨天]LT', + lastWeek : '[上]ddddLT', + sameElse : 'L' + }, + dayOfMonthOrdinalParse: /\d{1,2}(日|月|周)/, + ordinal : function (number, period) { + switch (period) { + case 'd': + case 'D': + case 'DDD': + return number + '日'; + case 'M': + return number + '月'; + case 'w': + case 'W': + return number + '周'; + default: + return number; } }, relativeTime : { - future : processFutureTime, - past : processPastTime, - s : 'e puer Sekonnen', - ss : '%d Sekonnen', - m : processRelativeTime, - mm : '%d Minutten', - h : processRelativeTime, - hh : '%d Stonnen', - d : processRelativeTime, - dd : '%d Deeg', - M : processRelativeTime, - MM : '%d Méint', - y : processRelativeTime, - yy : '%d Joer' + future : '%s内', + past : '%s前', + s : '几秒', + ss : '%d 秒', + m : '1 分钟', + mm : '%d 分钟', + h : '1 小时', + hh : '%d 小时', + d : '1 天', + dd : '%d 天', + M : '1 个月', + MM : '%d 个月', + y : '1 年', + yy : '%d 年' }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal: '%d.', - week: { - dow: 1, // Monday is the first day of the week. - doy: 4 // The week that contains Jan 4th is the first week of the year. + week : { + // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效 + dow : 1, // Monday is the first day of the week. + doy : 4 // The week that contains Jan 4th is the first week of the year. } }); - return lb; + return zhCn; }))); /***/ }), -/* 112 */ +/* 138 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var lo = moment.defineLocale('lo', { - months : 'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split('_'), - monthsShort : 'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split('_'), - weekdays : 'ອາທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'), - weekdaysShort : 'ທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'), - weekdaysMin : 'ທ_ຈ_ອຄ_ພ_ພຫ_ສກ_ສ'.split('_'), - weekdaysParseExact : true, + var zhHk = moment.defineLocale('zh-hk', { + months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), + monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), + weekdays : '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), + weekdaysShort : '週日_週一_週二_週三_週四_週五_週六'.split('_'), + weekdaysMin : '日_一_二_三_四_五_六'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'ວັນdddd D MMMM YYYY HH:mm' + L : 'YYYY/MM/DD', + LL : 'YYYY年M月D日', + LLL : 'YYYY年M月D日 HH:mm', + LLLL : 'YYYY年M月D日dddd HH:mm', + l : 'YYYY/M/D', + ll : 'YYYY年M月D日', + lll : 'YYYY年M月D日 HH:mm', + llll : 'YYYY年M月D日dddd HH:mm' }, - meridiemParse: /ຕອນເຊົ້າ|ຕອນແລງ/, - isPM: function (input) { - return input === 'ຕອນແລງ'; + meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, + meridiemHour : function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') { + return hour; + } else if (meridiem === '中午') { + return hour >= 11 ? hour : hour + 12; + } else if (meridiem === '下午' || meridiem === '晚上') { + return hour + 12; + } }, meridiem : function (hour, minute, isLower) { - if (hour < 12) { - return 'ຕອນເຊົ້າ'; + var hm = hour * 100 + minute; + if (hm < 600) { + return '凌晨'; + } else if (hm < 900) { + return '早上'; + } else if (hm < 1130) { + return '上午'; + } else if (hm < 1230) { + return '中午'; + } else if (hm < 1800) { + return '下午'; } else { - return 'ຕອນແລງ'; + return '晚上'; } }, calendar : { - sameDay : '[ມື້ນີ້ເວລາ] LT', - nextDay : '[ມື້ອື່ນເວລາ] LT', - nextWeek : '[ວັນ]dddd[ໜ້າເວລາ] LT', - lastDay : '[ມື້ວານນີ້ເວລາ] LT', - lastWeek : '[ວັນ]dddd[ແລ້ວນີ້ເວລາ] LT', + sameDay : '[今天]LT', + nextDay : '[明天]LT', + nextWeek : '[下]ddddLT', + lastDay : '[昨天]LT', + lastWeek : '[上]ddddLT', sameElse : 'L' }, - relativeTime : { - future : 'ອີກ %s', - past : '%sຜ່ານມາ', - s : 'ບໍ່ເທົ່າໃດວິນາທີ', - ss : '%d ວິນາທີ' , - m : '1 ນາທີ', - mm : '%d ນາທີ', - h : '1 ຊົ່ວໂມງ', - hh : '%d ຊົ່ວໂມງ', - d : '1 ມື້', - dd : '%d ມື້', - M : '1 ເດືອນ', - MM : '%d ເດືອນ', - y : '1 ປີ', - yy : '%d ປີ' + dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/, + ordinal : function (number, period) { + switch (period) { + case 'd' : + case 'D' : + case 'DDD' : + return number + '日'; + case 'M' : + return number + '月'; + case 'w' : + case 'W' : + return number + '週'; + default : + return number; + } }, - dayOfMonthOrdinalParse: /(ທີ່)\d{1,2}/, - ordinal : function (number) { - return 'ທີ່' + number; + relativeTime : { + future : '%s內', + past : '%s前', + s : '幾秒', + ss : '%d 秒', + m : '1 分鐘', + mm : '%d 分鐘', + h : '1 小時', + hh : '%d 小時', + d : '1 天', + dd : '%d 天', + M : '1 個月', + MM : '%d 個月', + y : '1 年', + yy : '%d 年' } }); - return lo; + return zhHk; }))); /***/ }), -/* 113 */ +/* 139 */ /***/ (function(module, exports, __webpack_require__) { //! moment.js locale configuration ;(function (global, factory) { - true ? factory(__webpack_require__(40)) : + true ? factory(__webpack_require__(10)) : undefined }(this, (function (moment) { 'use strict'; - var units = { - 'ss' : 'sekundė_sekundžių_sekundes', - 'm' : 'minutė_minutės_minutę', - 'mm': 'minutės_minučių_minutes', - 'h' : 'valanda_valandos_valandą', - 'hh': 'valandos_valandų_valandas', - 'd' : 'diena_dienos_dieną', - 'dd': 'dienos_dienų_dienas', - 'M' : 'mėnuo_mėnesio_mėnesį', - 'MM': 'mėnesiai_mėnesių_mėnesius', - 'y' : 'metai_metų_metus', - 'yy': 'metai_metų_metus' - }; - function translateSeconds(number, withoutSuffix, key, isFuture) { - if (withoutSuffix) { - return 'kelios sekundės'; - } else { - return isFuture ? 'kelių sekundžių' : 'kelias sekundes'; - } - } - function translateSingular(number, withoutSuffix, key, isFuture) { - return withoutSuffix ? forms(key)[0] : (isFuture ? forms(key)[1] : forms(key)[2]); - } - function special(number) { - return number % 10 === 0 || (number > 10 && number < 20); - } - function forms(key) { - return units[key].split('_'); - } - function translate(number, withoutSuffix, key, isFuture) { - var result = number + ' '; - if (number === 1) { - return result + translateSingular(number, withoutSuffix, key[0], isFuture); - } else if (withoutSuffix) { - return result + (special(number) ? forms(key)[1] : forms(key)[0]); - } else { - if (isFuture) { - return result + forms(key)[1]; - } else { - return result + (special(number) ? forms(key)[1] : forms(key)[2]); - } - } - } - var lt = moment.defineLocale('lt', { - months : { - format: 'sausio_vasario_kovo_balandžio_gegužės_birželio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio'.split('_'), - standalone: 'sausis_vasaris_kovas_balandis_gegužė_birželis_liepa_rugpjūtis_rugsėjis_spalis_lapkritis_gruodis'.split('_'), - isFormat: /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?|MMMM?(\[[^\[\]]*\]|\s)+D[oD]?/ - }, - monthsShort : 'sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd'.split('_'), - weekdays : { - format: 'sekmadienį_pirmadienį_antradienį_trečiadienį_ketvirtadienį_penktadienį_šeštadienį'.split('_'), - standalone: 'sekmadienis_pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis'.split('_'), - isFormat: /dddd HH:mm/ - }, - weekdaysShort : 'Sek_Pir_Ant_Tre_Ket_Pen_Šeš'.split('_'), - weekdaysMin : 'S_P_A_T_K_Pn_Š'.split('_'), - weekdaysParseExact : true, + var zhTw = moment.defineLocale('zh-tw', { + months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), + monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), + weekdays : '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), + weekdaysShort : '週日_週一_週二_週三_週四_週五_週六'.split('_'), + weekdaysMin : '日_一_二_三_四_五_六'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', - L : 'YYYY-MM-DD', - LL : 'YYYY [m.] MMMM D [d.]', - LLL : 'YYYY [m.] MMMM D [d.], HH:mm [val.]', - LLLL : 'YYYY [m.] MMMM D [d.], dddd, HH:mm [val.]', - l : 'YYYY-MM-DD', - ll : 'YYYY [m.] MMMM D [d.]', - lll : 'YYYY [m.] MMMM D [d.], HH:mm [val.]', - llll : 'YYYY [m.] MMMM D [d.], ddd, HH:mm [val.]' + L : 'YYYY/MM/DD', + LL : 'YYYY年M月D日', + LLL : 'YYYY年M月D日 HH:mm', + LLLL : 'YYYY年M月D日dddd HH:mm', + l : 'YYYY/M/D', + ll : 'YYYY年M月D日', + lll : 'YYYY年M月D日 HH:mm', + llll : 'YYYY年M月D日dddd HH:mm' + }, + meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, + meridiemHour : function (hour, meridiem) { + if (hour === 12) { + hour = 0; + } + if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') { + return hour; + } else if (meridiem === '中午') { + return hour >= 11 ? hour : hour + 12; + } else if (meridiem === '下午' || meridiem === '晚上') { + return hour + 12; + } + }, + meridiem : function (hour, minute, isLower) { + var hm = hour * 100 + minute; + if (hm < 600) { + return '凌晨'; + } else if (hm < 900) { + return '早上'; + } else if (hm < 1130) { + return '上午'; + } else if (hm < 1230) { + return '中午'; + } else if (hm < 1800) { + return '下午'; + } else { + return '晚上'; + } }, calendar : { - sameDay : '[Šiandien] LT', - nextDay : '[Rytoj] LT', - nextWeek : 'dddd LT', - lastDay : '[Vakar] LT', - lastWeek : '[Praėjusį] dddd LT', + sameDay : '[今天] LT', + nextDay : '[明天] LT', + nextWeek : '[下]dddd LT', + lastDay : '[昨天] LT', + lastWeek : '[上]dddd LT', sameElse : 'L' }, - relativeTime : { - future : 'po %s', - past : 'prieš %s', - s : translateSeconds, - ss : translate, - m : translateSingular, - mm : translate, - h : translateSingular, - hh : translate, - d : translateSingular, - dd : translate, - M : translateSingular, - MM : translate, - y : translateSingular, - yy : translate - }, - dayOfMonthOrdinalParse: /\d{1,2}-oji/, - ordinal : function (number) { - return number + '-oji'; + dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/, + ordinal : function (number, period) { + switch (period) { + case 'd' : + case 'D' : + case 'DDD' : + return number + '日'; + case 'M' : + return number + '月'; + case 'w' : + case 'W' : + return number + '週'; + default : + return number; + } }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + relativeTime : { + future : '%s內', + past : '%s前', + s : '幾秒', + ss : '%d 秒', + m : '1 分鐘', + mm : '%d 分鐘', + h : '1 小時', + hh : '%d 小時', + d : '1 天', + dd : '%d 天', + M : '1 個月', + MM : '%d 個月', + y : '1 年', + yy : '%d 年' } }); - return lt; + return zhTw; }))); /***/ }), -/* 114 */ -/***/ (function(module, exports, __webpack_require__) { +/* 140 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -//! moment.js locale configuration +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _internal_Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Observable", function() { return _internal_Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]; }); -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +/* harmony import */ var _internal_observable_ConnectableObservable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(157); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ConnectableObservable", function() { return _internal_observable_ConnectableObservable__WEBPACK_IMPORTED_MODULE_1__["ConnectableObservable"]; }); +/* harmony import */ var _internal_operators_groupBy__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(162); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GroupedObservable", function() { return _internal_operators_groupBy__WEBPACK_IMPORTED_MODULE_2__["GroupedObservable"]; }); - var units = { - 'ss': 'sekundes_sekundēm_sekunde_sekundes'.split('_'), - 'm': 'minūtes_minūtēm_minūte_minūtes'.split('_'), - 'mm': 'minūtes_minūtēm_minūte_minūtes'.split('_'), - 'h': 'stundas_stundām_stunda_stundas'.split('_'), - 'hh': 'stundas_stundām_stunda_stundas'.split('_'), - 'd': 'dienas_dienām_diena_dienas'.split('_'), - 'dd': 'dienas_dienām_diena_dienas'.split('_'), - 'M': 'mēneša_mēnešiem_mēnesis_mēneši'.split('_'), - 'MM': 'mēneša_mēnešiem_mēnesis_mēneši'.split('_'), - 'y': 'gada_gadiem_gads_gadi'.split('_'), - 'yy': 'gada_gadiem_gads_gadi'.split('_') - }; - /** - * @param withoutSuffix boolean true = a length of time; false = before/after a period of time. - */ - function format(forms, number, withoutSuffix) { - if (withoutSuffix) { - // E.g. "21 minūte", "3 minūtes". - return number % 10 === 1 && number % 100 !== 11 ? forms[2] : forms[3]; - } else { - // E.g. "21 minūtes" as in "pēc 21 minūtes". - // E.g. "3 minūtēm" as in "pēc 3 minūtēm". - return number % 10 === 1 && number % 100 !== 11 ? forms[0] : forms[1]; - } - } - function relativeTimeWithPlural(number, withoutSuffix, key) { - return number + ' ' + format(units[key], number, withoutSuffix); - } - function relativeTimeWithSingular(number, withoutSuffix, key) { - return format(units[key], number, withoutSuffix); - } - function relativeSeconds(number, withoutSuffix) { - return withoutSuffix ? 'dažas sekundes' : 'dažām sekundēm'; - } +/* harmony import */ var _internal_symbol_observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(154); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "observable", function() { return _internal_symbol_observable__WEBPACK_IMPORTED_MODULE_3__["observable"]; }); - var lv = moment.defineLocale('lv', { - months : 'janvāris_februāris_marts_aprīlis_maijs_jūnijs_jūlijs_augusts_septembris_oktobris_novembris_decembris'.split('_'), - monthsShort : 'jan_feb_mar_apr_mai_jūn_jūl_aug_sep_okt_nov_dec'.split('_'), - weekdays : 'svētdiena_pirmdiena_otrdiena_trešdiena_ceturtdiena_piektdiena_sestdiena'.split('_'), - weekdaysShort : 'Sv_P_O_T_C_Pk_S'.split('_'), - weekdaysMin : 'Sv_P_O_T_C_Pk_S'.split('_'), - weekdaysParseExact : true, - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD.MM.YYYY.', - LL : 'YYYY. [gada] D. MMMM', - LLL : 'YYYY. [gada] D. MMMM, HH:mm', - LLLL : 'YYYY. [gada] D. MMMM, dddd, HH:mm' - }, - calendar : { - sameDay : '[Šodien pulksten] LT', - nextDay : '[Rīt pulksten] LT', - nextWeek : 'dddd [pulksten] LT', - lastDay : '[Vakar pulksten] LT', - lastWeek : '[Pagājušā] dddd [pulksten] LT', - sameElse : 'L' - }, - relativeTime : { - future : 'pēc %s', - past : 'pirms %s', - s : relativeSeconds, - ss : relativeTimeWithPlural, - m : relativeTimeWithSingular, - mm : relativeTimeWithPlural, - h : relativeTimeWithSingular, - hh : relativeTimeWithPlural, - d : relativeTimeWithSingular, - dd : relativeTimeWithPlural, - M : relativeTimeWithSingular, - MM : relativeTimeWithPlural, - y : relativeTimeWithSingular, - yy : relativeTimeWithPlural - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. - } - }); +/* harmony import */ var _internal_Subject__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(158); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subject", function() { return _internal_Subject__WEBPACK_IMPORTED_MODULE_4__["Subject"]; }); - return lv; +/* harmony import */ var _internal_BehaviorSubject__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(163); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BehaviorSubject", function() { return _internal_BehaviorSubject__WEBPACK_IMPORTED_MODULE_5__["BehaviorSubject"]; }); -}))); +/* harmony import */ var _internal_ReplaySubject__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(164); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReplaySubject", function() { return _internal_ReplaySubject__WEBPACK_IMPORTED_MODULE_6__["ReplaySubject"]; }); +/* harmony import */ var _internal_AsyncSubject__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(181); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AsyncSubject", function() { return _internal_AsyncSubject__WEBPACK_IMPORTED_MODULE_7__["AsyncSubject"]; }); -/***/ }), -/* 115 */ -/***/ (function(module, exports, __webpack_require__) { +/* harmony import */ var _internal_scheduler_asap__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(182); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "asapScheduler", function() { return _internal_scheduler_asap__WEBPACK_IMPORTED_MODULE_8__["asap"]; }); -//! moment.js locale configuration +/* harmony import */ var _internal_scheduler_async__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(186); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "asyncScheduler", function() { return _internal_scheduler_async__WEBPACK_IMPORTED_MODULE_9__["async"]; }); -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +/* harmony import */ var _internal_scheduler_queue__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(165); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "queueScheduler", function() { return _internal_scheduler_queue__WEBPACK_IMPORTED_MODULE_10__["queue"]; }); +/* harmony import */ var _internal_scheduler_animationFrame__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(187); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "animationFrameScheduler", function() { return _internal_scheduler_animationFrame__WEBPACK_IMPORTED_MODULE_11__["animationFrame"]; }); - var translator = { - words: { //Different grammatical cases - ss: ['sekund', 'sekunda', 'sekundi'], - m: ['jedan minut', 'jednog minuta'], - mm: ['minut', 'minuta', 'minuta'], - h: ['jedan sat', 'jednog sata'], - hh: ['sat', 'sata', 'sati'], - dd: ['dan', 'dana', 'dana'], - MM: ['mjesec', 'mjeseca', 'mjeseci'], - yy: ['godina', 'godine', 'godina'] - }, - correctGrammaticalCase: function (number, wordKey) { - return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]); - }, - translate: function (number, withoutSuffix, key) { - var wordKey = translator.words[key]; - if (key.length === 1) { - return withoutSuffix ? wordKey[0] : wordKey[1]; - } else { - return number + ' ' + translator.correctGrammaticalCase(number, wordKey); - } - } - }; +/* harmony import */ var _internal_scheduler_VirtualTimeScheduler__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(190); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VirtualTimeScheduler", function() { return _internal_scheduler_VirtualTimeScheduler__WEBPACK_IMPORTED_MODULE_12__["VirtualTimeScheduler"]; }); - var me = moment.defineLocale('me', { - months: 'januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar'.split('_'), - monthsShort: 'jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.'.split('_'), - monthsParseExact : true, - weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'), - weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'), - weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'), - weekdaysParseExact : true, - longDateFormat: { - LT: 'H:mm', - LTS : 'H:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY H:mm', - LLLL: 'dddd, D. MMMM YYYY H:mm' - }, - calendar: { - sameDay: '[danas u] LT', - nextDay: '[sjutra u] LT', +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VirtualAction", function() { return _internal_scheduler_VirtualTimeScheduler__WEBPACK_IMPORTED_MODULE_12__["VirtualAction"]; }); - nextWeek: function () { - switch (this.day()) { - case 0: - return '[u] [nedjelju] [u] LT'; - case 3: - return '[u] [srijedu] [u] LT'; - case 6: - return '[u] [subotu] [u] LT'; - case 1: - case 2: - case 4: - case 5: - return '[u] dddd [u] LT'; - } - }, - lastDay : '[juče u] LT', - lastWeek : function () { - var lastWeekDays = [ - '[prošle] [nedjelje] [u] LT', - '[prošlog] [ponedjeljka] [u] LT', - '[prošlog] [utorka] [u] LT', - '[prošle] [srijede] [u] LT', - '[prošlog] [četvrtka] [u] LT', - '[prošlog] [petka] [u] LT', - '[prošle] [subote] [u] LT' - ]; - return lastWeekDays[this.day()]; - }, - sameElse : 'L' - }, - relativeTime : { - future : 'za %s', - past : 'prije %s', - s : 'nekoliko sekundi', - ss : translator.translate, - m : translator.translate, - mm : translator.translate, - h : translator.translate, - hh : translator.translate, - d : 'dan', - dd : translator.translate, - M : 'mjesec', - MM : translator.translate, - y : 'godinu', - yy : translator.translate - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', - week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. - } - }); +/* harmony import */ var _internal_Scheduler__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(171); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Scheduler", function() { return _internal_Scheduler__WEBPACK_IMPORTED_MODULE_13__["Scheduler"]; }); - return me; +/* harmony import */ var _internal_Subscription__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(148); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subscription", function() { return _internal_Subscription__WEBPACK_IMPORTED_MODULE_14__["Subscription"]; }); -}))); +/* harmony import */ var _internal_Subscriber__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(143); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subscriber", function() { return _internal_Subscriber__WEBPACK_IMPORTED_MODULE_15__["Subscriber"]; }); +/* harmony import */ var _internal_Notification__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(173); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Notification", function() { return _internal_Notification__WEBPACK_IMPORTED_MODULE_16__["Notification"]; }); -/***/ }), -/* 116 */ -/***/ (function(module, exports, __webpack_require__) { +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotificationKind", function() { return _internal_Notification__WEBPACK_IMPORTED_MODULE_16__["NotificationKind"]; }); -//! moment.js locale configuration +/* harmony import */ var _internal_util_pipe__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(155); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "pipe", function() { return _internal_util_pipe__WEBPACK_IMPORTED_MODULE_17__["pipe"]; }); -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +/* harmony import */ var _internal_util_noop__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(156); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "noop", function() { return _internal_util_noop__WEBPACK_IMPORTED_MODULE_18__["noop"]; }); +/* harmony import */ var _internal_util_identity__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(191); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "identity", function() { return _internal_util_identity__WEBPACK_IMPORTED_MODULE_19__["identity"]; }); - var mi = moment.defineLocale('mi', { - months: 'Kohi-tāte_Hui-tanguru_Poutū-te-rangi_Paenga-whāwhā_Haratua_Pipiri_Hōngoingoi_Here-turi-kōkā_Mahuru_Whiringa-ā-nuku_Whiringa-ā-rangi_Hakihea'.split('_'), - monthsShort: 'Kohi_Hui_Pou_Pae_Hara_Pipi_Hōngoi_Here_Mahu_Whi-nu_Whi-ra_Haki'.split('_'), - monthsRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i, - monthsStrictRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i, - monthsShortRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i, - monthsShortStrictRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,2}/i, - weekdays: 'Rātapu_Mane_Tūrei_Wenerei_Tāite_Paraire_Hātarei'.split('_'), - weekdaysShort: 'Ta_Ma_Tū_We_Tāi_Pa_Hā'.split('_'), - weekdaysMin: 'Ta_Ma_Tū_We_Tāi_Pa_Hā'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY [i] HH:mm', - LLLL: 'dddd, D MMMM YYYY [i] HH:mm' - }, - calendar: { - sameDay: '[i teie mahana, i] LT', - nextDay: '[apopo i] LT', - nextWeek: 'dddd [i] LT', - lastDay: '[inanahi i] LT', - lastWeek: 'dddd [whakamutunga i] LT', - sameElse: 'L' - }, - relativeTime: { - future: 'i roto i %s', - past: '%s i mua', - s: 'te hēkona ruarua', - ss: '%d hēkona', - m: 'he meneti', - mm: '%d meneti', - h: 'te haora', - hh: '%d haora', - d: 'he ra', - dd: '%d ra', - M: 'he marama', - MM: '%d marama', - y: 'he tau', - yy: '%d tau' - }, - dayOfMonthOrdinalParse: /\d{1,2}º/, - ordinal: '%dº', - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. - } - }); +/* harmony import */ var _internal_util_isObservable__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(192); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isObservable", function() { return _internal_util_isObservable__WEBPACK_IMPORTED_MODULE_20__["isObservable"]; }); - return mi; +/* harmony import */ var _internal_util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(193); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArgumentOutOfRangeError", function() { return _internal_util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_21__["ArgumentOutOfRangeError"]; }); -}))); +/* harmony import */ var _internal_util_EmptyError__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(194); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EmptyError", function() { return _internal_util_EmptyError__WEBPACK_IMPORTED_MODULE_22__["EmptyError"]; }); +/* harmony import */ var _internal_util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(159); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ObjectUnsubscribedError", function() { return _internal_util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_23__["ObjectUnsubscribedError"]; }); -/***/ }), -/* 117 */ -/***/ (function(module, exports, __webpack_require__) { +/* harmony import */ var _internal_util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(151); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UnsubscriptionError", function() { return _internal_util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_24__["UnsubscriptionError"]; }); -//! moment.js locale configuration +/* harmony import */ var _internal_util_TimeoutError__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(195); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TimeoutError", function() { return _internal_util_TimeoutError__WEBPACK_IMPORTED_MODULE_25__["TimeoutError"]; }); -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +/* harmony import */ var _internal_observable_bindCallback__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(196); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bindCallback", function() { return _internal_observable_bindCallback__WEBPACK_IMPORTED_MODULE_26__["bindCallback"]; }); +/* harmony import */ var _internal_observable_bindNodeCallback__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(198); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bindNodeCallback", function() { return _internal_observable_bindNodeCallback__WEBPACK_IMPORTED_MODULE_27__["bindNodeCallback"]; }); - var mk = moment.defineLocale('mk', { - months : 'јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември'.split('_'), - monthsShort : 'јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек'.split('_'), - weekdays : 'недела_понеделник_вторник_среда_четврток_петок_сабота'.split('_'), - weekdaysShort : 'нед_пон_вто_сре_чет_пет_саб'.split('_'), - weekdaysMin : 'нe_пo_вт_ср_че_пе_сa'.split('_'), - longDateFormat : { - LT : 'H:mm', - LTS : 'H:mm:ss', - L : 'D.MM.YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY H:mm', - LLLL : 'dddd, D MMMM YYYY H:mm' - }, - calendar : { - sameDay : '[Денес во] LT', - nextDay : '[Утре во] LT', - nextWeek : '[Во] dddd [во] LT', - lastDay : '[Вчера во] LT', - lastWeek : function () { - switch (this.day()) { - case 0: - case 3: - case 6: - return '[Изминатата] dddd [во] LT'; - case 1: - case 2: - case 4: - case 5: - return '[Изминатиот] dddd [во] LT'; - } - }, - sameElse : 'L' - }, - relativeTime : { - future : 'после %s', - past : 'пред %s', - s : 'неколку секунди', - ss : '%d секунди', - m : 'минута', - mm : '%d минути', - h : 'час', - hh : '%d часа', - d : 'ден', - dd : '%d дена', - M : 'месец', - MM : '%d месеци', - y : 'година', - yy : '%d години' - }, - dayOfMonthOrdinalParse: /\d{1,2}-(ев|ен|ти|ви|ри|ми)/, - ordinal : function (number) { - var lastDigit = number % 10, - last2Digits = number % 100; - if (number === 0) { - return number + '-ев'; - } else if (last2Digits === 0) { - return number + '-ен'; - } else if (last2Digits > 10 && last2Digits < 20) { - return number + '-ти'; - } else if (lastDigit === 1) { - return number + '-ви'; - } else if (lastDigit === 2) { - return number + '-ри'; - } else if (lastDigit === 7 || lastDigit === 8) { - return number + '-ми'; - } else { - return number + '-ти'; - } - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. - } - }); +/* harmony import */ var _internal_observable_combineLatest__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(199); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "combineLatest", function() { return _internal_observable_combineLatest__WEBPACK_IMPORTED_MODULE_28__["combineLatest"]; }); - return mk; +/* harmony import */ var _internal_observable_concat__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(210); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "concat", function() { return _internal_observable_concat__WEBPACK_IMPORTED_MODULE_29__["concat"]; }); -}))); +/* harmony import */ var _internal_observable_defer__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(221); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defer", function() { return _internal_observable_defer__WEBPACK_IMPORTED_MODULE_30__["defer"]; }); +/* harmony import */ var _internal_observable_empty__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(174); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "empty", function() { return _internal_observable_empty__WEBPACK_IMPORTED_MODULE_31__["empty"]; }); -/***/ }), -/* 118 */ -/***/ (function(module, exports, __webpack_require__) { +/* harmony import */ var _internal_observable_forkJoin__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(222); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "forkJoin", function() { return _internal_observable_forkJoin__WEBPACK_IMPORTED_MODULE_32__["forkJoin"]; }); -//! moment.js locale configuration +/* harmony import */ var _internal_observable_from__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(214); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "from", function() { return _internal_observable_from__WEBPACK_IMPORTED_MODULE_33__["from"]; }); -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +/* harmony import */ var _internal_observable_fromEvent__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(223); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fromEvent", function() { return _internal_observable_fromEvent__WEBPACK_IMPORTED_MODULE_34__["fromEvent"]; }); +/* harmony import */ var _internal_observable_fromEventPattern__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(224); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fromEventPattern", function() { return _internal_observable_fromEventPattern__WEBPACK_IMPORTED_MODULE_35__["fromEventPattern"]; }); - var ml = moment.defineLocale('ml', { - months : 'ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ'.split('_'), - monthsShort : 'ജനു._ഫെബ്രു._മാർ._ഏപ്രി._മേയ്_ജൂൺ_ജൂലൈ._ഓഗ._സെപ്റ്റ._ഒക്ടോ._നവം._ഡിസം.'.split('_'), - monthsParseExact : true, - weekdays : 'ഞായറാഴ്ച_തിങ്കളാഴ്ച_ചൊവ്വാഴ്ച_ബുധനാഴ്ച_വ്യാഴാഴ്ച_വെള്ളിയാഴ്ച_ശനിയാഴ്ച'.split('_'), - weekdaysShort : 'ഞായർ_തിങ്കൾ_ചൊവ്വ_ബുധൻ_വ്യാഴം_വെള്ളി_ശനി'.split('_'), - weekdaysMin : 'ഞാ_തി_ചൊ_ബു_വ്യാ_വെ_ശ'.split('_'), - longDateFormat : { - LT : 'A h:mm -നു', - LTS : 'A h:mm:ss -നു', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY, A h:mm -നു', - LLLL : 'dddd, D MMMM YYYY, A h:mm -നു' - }, - calendar : { - sameDay : '[ഇന്ന്] LT', - nextDay : '[നാളെ] LT', - nextWeek : 'dddd, LT', - lastDay : '[ഇന്നലെ] LT', - lastWeek : '[കഴിഞ്ഞ] dddd, LT', - sameElse : 'L' - }, - relativeTime : { - future : '%s കഴിഞ്ഞ്', - past : '%s മുൻപ്', - s : 'അൽപ നിമിഷങ്ങൾ', - ss : '%d സെക്കൻഡ്', - m : 'ഒരു മിനിറ്റ്', - mm : '%d മിനിറ്റ്', - h : 'ഒരു മണിക്കൂർ', - hh : '%d മണിക്കൂർ', - d : 'ഒരു ദിവസം', - dd : '%d ദിവസം', - M : 'ഒരു മാസം', - MM : '%d മാസം', - y : 'ഒരു വർഷം', - yy : '%d വർഷം' - }, - meridiemParse: /രാത്രി|രാവിലെ|ഉച്ച കഴിഞ്ഞ്|വൈകുന്നേരം|രാത്രി/i, - meridiemHour : function (hour, meridiem) { - if (hour === 12) { - hour = 0; - } - if ((meridiem === 'രാത്രി' && hour >= 4) || - meridiem === 'ഉച്ച കഴിഞ്ഞ്' || - meridiem === 'വൈകുന്നേരം') { - return hour + 12; - } else { - return hour; - } - }, - meridiem : function (hour, minute, isLower) { - if (hour < 4) { - return 'രാത്രി'; - } else if (hour < 12) { - return 'രാവിലെ'; - } else if (hour < 17) { - return 'ഉച്ച കഴിഞ്ഞ്'; - } else if (hour < 20) { - return 'വൈകുന്നേരം'; - } else { - return 'രാത്രി'; - } - } - }); +/* harmony import */ var _internal_observable_generate__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(225); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "generate", function() { return _internal_observable_generate__WEBPACK_IMPORTED_MODULE_36__["generate"]; }); - return ml; +/* harmony import */ var _internal_observable_iif__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(226); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "iif", function() { return _internal_observable_iif__WEBPACK_IMPORTED_MODULE_37__["iif"]; }); -}))); +/* harmony import */ var _internal_observable_interval__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(227); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "interval", function() { return _internal_observable_interval__WEBPACK_IMPORTED_MODULE_38__["interval"]; }); +/* harmony import */ var _internal_observable_merge__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(229); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "merge", function() { return _internal_observable_merge__WEBPACK_IMPORTED_MODULE_39__["merge"]; }); -/***/ }), -/* 119 */ -/***/ (function(module, exports, __webpack_require__) { +/* harmony import */ var _internal_observable_never__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(230); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "never", function() { return _internal_observable_never__WEBPACK_IMPORTED_MODULE_40__["never"]; }); -//! moment.js locale configuration +/* harmony import */ var _internal_observable_of__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(175); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "of", function() { return _internal_observable_of__WEBPACK_IMPORTED_MODULE_41__["of"]; }); -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +/* harmony import */ var _internal_observable_onErrorResumeNext__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(231); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "onErrorResumeNext", function() { return _internal_observable_onErrorResumeNext__WEBPACK_IMPORTED_MODULE_42__["onErrorResumeNext"]; }); +/* harmony import */ var _internal_observable_pairs__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(232); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "pairs", function() { return _internal_observable_pairs__WEBPACK_IMPORTED_MODULE_43__["pairs"]; }); - function translate(number, withoutSuffix, key, isFuture) { - switch (key) { - case 's': - return withoutSuffix ? 'хэдхэн секунд' : 'хэдхэн секундын'; - case 'ss': - return number + (withoutSuffix ? ' секунд' : ' секундын'); - case 'm': - case 'mm': - return number + (withoutSuffix ? ' минут' : ' минутын'); - case 'h': - case 'hh': - return number + (withoutSuffix ? ' цаг' : ' цагийн'); - case 'd': - case 'dd': - return number + (withoutSuffix ? ' өдөр' : ' өдрийн'); - case 'M': - case 'MM': - return number + (withoutSuffix ? ' сар' : ' сарын'); - case 'y': - case 'yy': - return number + (withoutSuffix ? ' жил' : ' жилийн'); - default: - return number; - } - } +/* harmony import */ var _internal_observable_partition__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(233); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "partition", function() { return _internal_observable_partition__WEBPACK_IMPORTED_MODULE_44__["partition"]; }); - var mn = moment.defineLocale('mn', { - months : 'Нэгдүгээр сар_Хоёрдугаар сар_Гуравдугаар сар_Дөрөвдүгээр сар_Тавдугаар сар_Зургадугаар сар_Долдугаар сар_Наймдугаар сар_Есдүгээр сар_Аравдугаар сар_Арван нэгдүгээр сар_Арван хоёрдугаар сар'.split('_'), - monthsShort : '1 сар_2 сар_3 сар_4 сар_5 сар_6 сар_7 сар_8 сар_9 сар_10 сар_11 сар_12 сар'.split('_'), - monthsParseExact : true, - weekdays : 'Ням_Даваа_Мягмар_Лхагва_Пүрэв_Баасан_Бямба'.split('_'), - weekdaysShort : 'Ням_Дав_Мяг_Лха_Пүр_Баа_Бям'.split('_'), - weekdaysMin : 'Ня_Да_Мя_Лх_Пү_Ба_Бя'.split('_'), - weekdaysParseExact : true, - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'YYYY-MM-DD', - LL : 'YYYY оны MMMMын D', - LLL : 'YYYY оны MMMMын D HH:mm', - LLLL : 'dddd, YYYY оны MMMMын D HH:mm' - }, - meridiemParse: /ҮӨ|ҮХ/i, - isPM : function (input) { - return input === 'ҮХ'; - }, - meridiem : function (hour, minute, isLower) { - if (hour < 12) { - return 'ҮӨ'; - } else { - return 'ҮХ'; - } - }, - calendar : { - sameDay : '[Өнөөдөр] LT', - nextDay : '[Маргааш] LT', - nextWeek : '[Ирэх] dddd LT', - lastDay : '[Өчигдөр] LT', - lastWeek : '[Өнгөрсөн] dddd LT', - sameElse : 'L' - }, - relativeTime : { - future : '%s дараа', - past : '%s өмнө', - s : translate, - ss : translate, - m : translate, - mm : translate, - h : translate, - hh : translate, - d : translate, - dd : translate, - M : translate, - MM : translate, - y : translate, - yy : translate - }, - dayOfMonthOrdinalParse: /\d{1,2} өдөр/, - ordinal : function (number, period) { - switch (period) { - case 'd': - case 'D': - case 'DDD': - return number + ' өдөр'; - default: - return number; - } - } - }); +/* harmony import */ var _internal_observable_race__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(236); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "race", function() { return _internal_observable_race__WEBPACK_IMPORTED_MODULE_45__["race"]; }); - return mn; +/* harmony import */ var _internal_observable_range__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(237); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "range", function() { return _internal_observable_range__WEBPACK_IMPORTED_MODULE_46__["range"]; }); -}))); +/* harmony import */ var _internal_observable_throwError__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(180); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "throwError", function() { return _internal_observable_throwError__WEBPACK_IMPORTED_MODULE_47__["throwError"]; }); +/* harmony import */ var _internal_observable_timer__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(238); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "timer", function() { return _internal_observable_timer__WEBPACK_IMPORTED_MODULE_48__["timer"]; }); -/***/ }), -/* 120 */ -/***/ (function(module, exports, __webpack_require__) { +/* harmony import */ var _internal_observable_using__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(239); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "using", function() { return _internal_observable_using__WEBPACK_IMPORTED_MODULE_49__["using"]; }); -//! moment.js locale configuration +/* harmony import */ var _internal_observable_zip__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(240); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "zip", function() { return _internal_observable_zip__WEBPACK_IMPORTED_MODULE_50__["zip"]; }); -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +/* harmony import */ var _internal_scheduled_scheduled__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(215); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "scheduled", function() { return _internal_scheduled_scheduled__WEBPACK_IMPORTED_MODULE_51__["scheduled"]; }); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EMPTY", function() { return _internal_observable_empty__WEBPACK_IMPORTED_MODULE_31__["EMPTY"]; }); - var symbolMap = { - '1': '१', - '2': '२', - '3': '३', - '4': '४', - '5': '५', - '6': '६', - '7': '७', - '8': '८', - '9': '९', - '0': '०' - }, - numberMap = { - '१': '1', - '२': '2', - '३': '3', - '४': '4', - '५': '5', - '६': '6', - '७': '7', - '८': '8', - '९': '9', - '०': '0' - }; +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NEVER", function() { return _internal_observable_never__WEBPACK_IMPORTED_MODULE_40__["NEVER"]; }); - function relativeTimeMr(number, withoutSuffix, string, isFuture) - { - var output = ''; - if (withoutSuffix) { - switch (string) { - case 's': output = 'काही सेकंद'; break; - case 'ss': output = '%d सेकंद'; break; - case 'm': output = 'एक मिनिट'; break; - case 'mm': output = '%d मिनिटे'; break; - case 'h': output = 'एक तास'; break; - case 'hh': output = '%d तास'; break; - case 'd': output = 'एक दिवस'; break; - case 'dd': output = '%d दिवस'; break; - case 'M': output = 'एक महिना'; break; - case 'MM': output = '%d महिने'; break; - case 'y': output = 'एक वर्ष'; break; - case 'yy': output = '%d वर्षे'; break; - } - } - else { - switch (string) { - case 's': output = 'काही सेकंदां'; break; - case 'ss': output = '%d सेकंदां'; break; - case 'm': output = 'एका मिनिटा'; break; - case 'mm': output = '%d मिनिटां'; break; - case 'h': output = 'एका तासा'; break; - case 'hh': output = '%d तासां'; break; - case 'd': output = 'एका दिवसा'; break; - case 'dd': output = '%d दिवसां'; break; - case 'M': output = 'एका महिन्या'; break; - case 'MM': output = '%d महिन्यां'; break; - case 'y': output = 'एका वर्षा'; break; - case 'yy': output = '%d वर्षां'; break; - } - } - return output.replace(/%d/i, number); - } +/* harmony import */ var _internal_config__WEBPACK_IMPORTED_MODULE_52__ = __webpack_require__(146); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "config", function() { return _internal_config__WEBPACK_IMPORTED_MODULE_52__["config"]; }); - var mr = moment.defineLocale('mr', { - months : 'जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split('_'), - monthsShort: 'जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split('_'), - monthsParseExact : true, - weekdays : 'रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'), - weekdaysShort : 'रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि'.split('_'), - weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split('_'), - longDateFormat : { - LT : 'A h:mm वाजता', - LTS : 'A h:mm:ss वाजता', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY, A h:mm वाजता', - LLLL : 'dddd, D MMMM YYYY, A h:mm वाजता' - }, - calendar : { - sameDay : '[आज] LT', - nextDay : '[उद्या] LT', - nextWeek : 'dddd, LT', - lastDay : '[काल] LT', - lastWeek: '[मागील] dddd, LT', - sameElse : 'L' - }, - relativeTime : { - future: '%sमध्ये', - past: '%sपूर्वी', - s: relativeTimeMr, - ss: relativeTimeMr, - m: relativeTimeMr, - mm: relativeTimeMr, - h: relativeTimeMr, - hh: relativeTimeMr, - d: relativeTimeMr, - dd: relativeTimeMr, - M: relativeTimeMr, - MM: relativeTimeMr, - y: relativeTimeMr, - yy: relativeTimeMr - }, - preparse: function (string) { - return string.replace(/[१२३४५६७८९०]/g, function (match) { - return numberMap[match]; - }); - }, - postformat: function (string) { - return string.replace(/\d/g, function (match) { - return symbolMap[match]; - }); - }, - meridiemParse: /रात्री|सकाळी|दुपारी|सायंकाळी/, - meridiemHour : function (hour, meridiem) { - if (hour === 12) { - hour = 0; - } - if (meridiem === 'रात्री') { - return hour < 4 ? hour : hour + 12; - } else if (meridiem === 'सकाळी') { - return hour; - } else if (meridiem === 'दुपारी') { - return hour >= 10 ? hour : hour + 12; - } else if (meridiem === 'सायंकाळी') { - return hour + 12; - } - }, - meridiem: function (hour, minute, isLower) { - if (hour < 4) { - return 'रात्री'; - } else if (hour < 10) { - return 'सकाळी'; - } else if (hour < 17) { - return 'दुपारी'; - } else if (hour < 20) { - return 'सायंकाळी'; - } else { - return 'रात्री'; - } - }, - week : { - dow : 0, // Sunday is the first day of the week. - doy : 6 // The week that contains Jan 6th is the first week of the year. - } - }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ - return mr; -}))); -/***/ }), -/* 121 */ -/***/ (function(module, exports, __webpack_require__) { -//! moment.js locale configuration -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - var ms = moment.defineLocale('ms', { - months : 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split('_'), - monthsShort : 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'), - weekdays : 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'), - weekdaysShort : 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'), - weekdaysMin : 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'), - longDateFormat : { - LT : 'HH.mm', - LTS : 'HH.mm.ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY [pukul] HH.mm', - LLLL : 'dddd, D MMMM YYYY [pukul] HH.mm' - }, - meridiemParse: /pagi|tengahari|petang|malam/, - meridiemHour: function (hour, meridiem) { - if (hour === 12) { - hour = 0; - } - if (meridiem === 'pagi') { - return hour; - } else if (meridiem === 'tengahari') { - return hour >= 11 ? hour : hour + 12; - } else if (meridiem === 'petang' || meridiem === 'malam') { - return hour + 12; - } - }, - meridiem : function (hours, minutes, isLower) { - if (hours < 11) { - return 'pagi'; - } else if (hours < 15) { - return 'tengahari'; - } else if (hours < 19) { - return 'petang'; - } else { - return 'malam'; - } - }, - calendar : { - sameDay : '[Hari ini pukul] LT', - nextDay : '[Esok pukul] LT', - nextWeek : 'dddd [pukul] LT', - lastDay : '[Kelmarin pukul] LT', - lastWeek : 'dddd [lepas pukul] LT', - sameElse : 'L' - }, - relativeTime : { - future : 'dalam %s', - past : '%s yang lepas', - s : 'beberapa saat', - ss : '%d saat', - m : 'seminit', - mm : '%d minit', - h : 'sejam', - hh : '%d jam', - d : 'sehari', - dd : '%d hari', - M : 'sebulan', - MM : '%d bulan', - y : 'setahun', - yy : '%d tahun' - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. - } - }); - return ms; -}))); -/***/ }), -/* 122 */ -/***/ (function(module, exports, __webpack_require__) { -//! moment.js locale configuration -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - var msMy = moment.defineLocale('ms-my', { - months : 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split('_'), - monthsShort : 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'), - weekdays : 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'), - weekdaysShort : 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'), - weekdaysMin : 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'), - longDateFormat : { - LT : 'HH.mm', - LTS : 'HH.mm.ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY [pukul] HH.mm', - LLLL : 'dddd, D MMMM YYYY [pukul] HH.mm' - }, - meridiemParse: /pagi|tengahari|petang|malam/, - meridiemHour: function (hour, meridiem) { - if (hour === 12) { - hour = 0; - } - if (meridiem === 'pagi') { - return hour; - } else if (meridiem === 'tengahari') { - return hour >= 11 ? hour : hour + 12; - } else if (meridiem === 'petang' || meridiem === 'malam') { - return hour + 12; - } - }, - meridiem : function (hours, minutes, isLower) { - if (hours < 11) { - return 'pagi'; - } else if (hours < 15) { - return 'tengahari'; - } else if (hours < 19) { - return 'petang'; - } else { - return 'malam'; - } - }, - calendar : { - sameDay : '[Hari ini pukul] LT', - nextDay : '[Esok pukul] LT', - nextWeek : 'dddd [pukul] LT', - lastDay : '[Kelmarin pukul] LT', - lastWeek : 'dddd [lepas pukul] LT', - sameElse : 'L' - }, - relativeTime : { - future : 'dalam %s', - past : '%s yang lepas', - s : 'beberapa saat', - ss : '%d saat', - m : 'seminit', - mm : '%d minit', - h : 'sejam', - hh : '%d jam', - d : 'sehari', - dd : '%d hari', - M : 'sebulan', - MM : '%d bulan', - y : 'setahun', - yy : '%d tahun' - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. - } - }); - return msMy; -}))); -/***/ }), -/* 123 */ -/***/ (function(module, exports, __webpack_require__) { -//! moment.js locale configuration -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - var mt = moment.defineLocale('mt', { - months : 'Jannar_Frar_Marzu_April_Mejju_Ġunju_Lulju_Awwissu_Settembru_Ottubru_Novembru_Diċembru'.split('_'), - monthsShort : 'Jan_Fra_Mar_Apr_Mej_Ġun_Lul_Aww_Set_Ott_Nov_Diċ'.split('_'), - weekdays : 'Il-Ħadd_It-Tnejn_It-Tlieta_L-Erbgħa_Il-Ħamis_Il-Ġimgħa_Is-Sibt'.split('_'), - weekdaysShort : 'Ħad_Tne_Tli_Erb_Ħam_Ġim_Sib'.split('_'), - weekdaysMin : 'Ħa_Tn_Tl_Er_Ħa_Ġi_Si'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd, D MMMM YYYY HH:mm' - }, - calendar : { - sameDay : '[Illum fil-]LT', - nextDay : '[Għada fil-]LT', - nextWeek : 'dddd [fil-]LT', - lastDay : '[Il-bieraħ fil-]LT', - lastWeek : 'dddd [li għadda] [fil-]LT', - sameElse : 'L' - }, - relativeTime : { - future : 'f’ %s', - past : '%s ilu', - s : 'ftit sekondi', - ss : '%d sekondi', - m : 'minuta', - mm : '%d minuti', - h : 'siegħa', - hh : '%d siegħat', - d : 'ġurnata', - dd : '%d ġranet', - M : 'xahar', - MM : '%d xhur', - y : 'sena', - yy : '%d sni' - }, - dayOfMonthOrdinalParse : /\d{1,2}º/, - ordinal: '%dº', - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. - } - }); - return mt; -}))); -/***/ }), -/* 124 */ -/***/ (function(module, exports, __webpack_require__) { -//! moment.js locale configuration -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - var symbolMap = { - '1': '၁', - '2': '၂', - '3': '၃', - '4': '၄', - '5': '၅', - '6': '၆', - '7': '၇', - '8': '၈', - '9': '၉', - '0': '၀' - }, numberMap = { - '၁': '1', - '၂': '2', - '၃': '3', - '၄': '4', - '၅': '5', - '၆': '6', - '၇': '7', - '၈': '8', - '၉': '9', - '၀': '0' - }; - var my = moment.defineLocale('my', { - months: 'ဇန်နဝါရီ_ဖေဖော်ဝါရီ_မတ်_ဧပြီ_မေ_ဇွန်_ဇူလိုင်_သြဂုတ်_စက်တင်ဘာ_အောက်တိုဘာ_နိုဝင်ဘာ_ဒီဇင်ဘာ'.split('_'), - monthsShort: 'ဇန်_ဖေ_မတ်_ပြီ_မေ_ဇွန်_လိုင်_သြ_စက်_အောက်_နို_ဒီ'.split('_'), - weekdays: 'တနင်္ဂနွေ_တနင်္လာ_အင်္ဂါ_ဗုဒ္ဓဟူး_ကြာသပတေး_သောကြာ_စနေ'.split('_'), - weekdaysShort: 'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'), - weekdaysMin: 'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'DD/MM/YYYY', - LL: 'D MMMM YYYY', - LLL: 'D MMMM YYYY HH:mm', - LLLL: 'dddd D MMMM YYYY HH:mm' - }, - calendar: { - sameDay: '[ယနေ.] LT [မှာ]', - nextDay: '[မနက်ဖြန်] LT [မှာ]', - nextWeek: 'dddd LT [မှာ]', - lastDay: '[မနေ.က] LT [မှာ]', - lastWeek: '[ပြီးခဲ့သော] dddd LT [မှာ]', - sameElse: 'L' - }, - relativeTime: { - future: 'လာမည့် %s မှာ', - past: 'လွန်ခဲ့သော %s က', - s: 'စက္ကန်.အနည်းငယ်', - ss : '%d စက္ကန့်', - m: 'တစ်မိနစ်', - mm: '%d မိနစ်', - h: 'တစ်နာရီ', - hh: '%d နာရီ', - d: 'တစ်ရက်', - dd: '%d ရက်', - M: 'တစ်လ', - MM: '%d လ', - y: 'တစ်နှစ်', - yy: '%d နှစ်' - }, - preparse: function (string) { - return string.replace(/[၁၂၃၄၅၆၇၈၉၀]/g, function (match) { - return numberMap[match]; - }); - }, - postformat: function (string) { - return string.replace(/\d/g, function (match) { - return symbolMap[match]; - }); - }, - week: { - dow: 1, // Monday is the first day of the week. - doy: 4 // The week that contains Jan 4th is the first week of the year. - } - }); - - return my; -}))); -/***/ }), -/* 125 */ -/***/ (function(module, exports, __webpack_require__) { -//! moment.js locale configuration -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - var nb = moment.defineLocale('nb', { - months : 'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split('_'), - monthsShort : 'jan._feb._mars_april_mai_juni_juli_aug._sep._okt._nov._des.'.split('_'), - monthsParseExact : true, - weekdays : 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'), - weekdaysShort : 'sø._ma._ti._on._to._fr._lø.'.split('_'), - weekdaysMin : 'sø_ma_ti_on_to_fr_lø'.split('_'), - weekdaysParseExact : true, - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D. MMMM YYYY', - LLL : 'D. MMMM YYYY [kl.] HH:mm', - LLLL : 'dddd D. MMMM YYYY [kl.] HH:mm' - }, - calendar : { - sameDay: '[i dag kl.] LT', - nextDay: '[i morgen kl.] LT', - nextWeek: 'dddd [kl.] LT', - lastDay: '[i går kl.] LT', - lastWeek: '[forrige] dddd [kl.] LT', - sameElse: 'L' - }, - relativeTime : { - future : 'om %s', - past : '%s siden', - s : 'noen sekunder', - ss : '%d sekunder', - m : 'ett minutt', - mm : '%d minutter', - h : 'en time', - hh : '%d timer', - d : 'en dag', - dd : '%d dager', - M : 'en måned', - MM : '%d måneder', - y : 'ett år', - yy : '%d år' - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. - } - }); - return nb; -}))); -/***/ }), -/* 126 */ -/***/ (function(module, exports, __webpack_require__) { -//! moment.js locale configuration -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - var symbolMap = { - '1': '१', - '2': '२', - '3': '३', - '4': '४', - '5': '५', - '6': '६', - '7': '७', - '8': '८', - '9': '९', - '0': '०' - }, - numberMap = { - '१': '1', - '२': '2', - '३': '3', - '४': '4', - '५': '5', - '६': '6', - '७': '7', - '८': '8', - '९': '9', - '०': '0' - }; - var ne = moment.defineLocale('ne', { - months : 'जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर'.split('_'), - monthsShort : 'जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.'.split('_'), - monthsParseExact : true, - weekdays : 'आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार'.split('_'), - weekdaysShort : 'आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.'.split('_'), - weekdaysMin : 'आ._सो._मं._बु._बि._शु._श.'.split('_'), - weekdaysParseExact : true, - longDateFormat : { - LT : 'Aको h:mm बजे', - LTS : 'Aको h:mm:ss बजे', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY, Aको h:mm बजे', - LLLL : 'dddd, D MMMM YYYY, Aको h:mm बजे' - }, - preparse: function (string) { - return string.replace(/[१२३४५६७८९०]/g, function (match) { - return numberMap[match]; - }); - }, - postformat: function (string) { - return string.replace(/\d/g, function (match) { - return symbolMap[match]; - }); - }, - meridiemParse: /राति|बिहान|दिउँसो|साँझ/, - meridiemHour : function (hour, meridiem) { - if (hour === 12) { - hour = 0; - } - if (meridiem === 'राति') { - return hour < 4 ? hour : hour + 12; - } else if (meridiem === 'बिहान') { - return hour; - } else if (meridiem === 'दिउँसो') { - return hour >= 10 ? hour : hour + 12; - } else if (meridiem === 'साँझ') { - return hour + 12; - } - }, - meridiem : function (hour, minute, isLower) { - if (hour < 3) { - return 'राति'; - } else if (hour < 12) { - return 'बिहान'; - } else if (hour < 16) { - return 'दिउँसो'; - } else if (hour < 20) { - return 'साँझ'; - } else { - return 'राति'; - } - }, - calendar : { - sameDay : '[आज] LT', - nextDay : '[भोलि] LT', - nextWeek : '[आउँदो] dddd[,] LT', - lastDay : '[हिजो] LT', - lastWeek : '[गएको] dddd[,] LT', - sameElse : 'L' - }, - relativeTime : { - future : '%sमा', - past : '%s अगाडि', - s : 'केही क्षण', - ss : '%d सेकेण्ड', - m : 'एक मिनेट', - mm : '%d मिनेट', - h : 'एक घण्टा', - hh : '%d घण्टा', - d : 'एक दिन', - dd : '%d दिन', - M : 'एक महिना', - MM : '%d महिना', - y : 'एक बर्ष', - yy : '%d बर्ष' - }, - week : { - dow : 0, // Sunday is the first day of the week. - doy : 6 // The week that contains Jan 6th is the first week of the year. - } - }); - return ne; -}))); -/***/ }), -/* 127 */ -/***/ (function(module, exports, __webpack_require__) { -//! moment.js locale configuration +//# sourceMappingURL=index.js.map -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +/***/ }), +/* 141 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - var monthsShortWithDots = 'jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'), - monthsShortWithoutDots = 'jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_'); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Observable", function() { return Observable; }); +/* harmony import */ var _util_canReportError__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(142); +/* harmony import */ var _util_toSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(153); +/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(154); +/* harmony import */ var _util_pipe__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(155); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(146); +/** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */ - var monthsParse = [/^jan/i, /^feb/i, /^maart|mrt.?$/i, /^apr/i, /^mei$/i, /^jun[i.]?$/i, /^jul[i.]?$/i, /^aug/i, /^sep/i, /^okt/i, /^nov/i, /^dec/i]; - var monthsRegex = /^(januari|februari|maart|april|mei|ju[nl]i|augustus|september|oktober|november|december|jan\.?|feb\.?|mrt\.?|apr\.?|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i; - var nl = moment.defineLocale('nl', { - months : 'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split('_'), - monthsShort : function (m, format) { - if (!m) { - return monthsShortWithDots; - } else if (/-MMM-/.test(format)) { - return monthsShortWithoutDots[m.month()]; - } else { - return monthsShortWithDots[m.month()]; - } - }, - monthsRegex: monthsRegex, - monthsShortRegex: monthsRegex, - monthsStrictRegex: /^(januari|februari|maart|april|mei|ju[nl]i|augustus|september|oktober|november|december)/i, - monthsShortStrictRegex: /^(jan\.?|feb\.?|mrt\.?|apr\.?|mei|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i, - monthsParse : monthsParse, - longMonthsParse : monthsParse, - shortMonthsParse : monthsParse, - weekdays : 'zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag'.split('_'), - weekdaysShort : 'zo._ma._di._wo._do._vr._za.'.split('_'), - weekdaysMin : 'zo_ma_di_wo_do_vr_za'.split('_'), - weekdaysParseExact : true, - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD-MM-YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd D MMMM YYYY HH:mm' - }, - calendar : { - sameDay: '[vandaag om] LT', - nextDay: '[morgen om] LT', - nextWeek: 'dddd [om] LT', - lastDay: '[gisteren om] LT', - lastWeek: '[afgelopen] dddd [om] LT', - sameElse: 'L' - }, - relativeTime : { - future : 'over %s', - past : '%s geleden', - s : 'een paar seconden', - ss : '%d seconden', - m : 'één minuut', - mm : '%d minuten', - h : 'één uur', - hh : '%d uur', - d : 'één dag', - dd : '%d dagen', - M : 'één maand', - MM : '%d maanden', - y : 'één jaar', - yy : '%d jaar' - }, - dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, - ordinal : function (number) { - return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. +var Observable = /*@__PURE__*/ (function () { + function Observable(subscribe) { + this._isScalar = false; + if (subscribe) { + this._subscribe = subscribe; } - }); - - return nl; + } + Observable.prototype.lift = function (operator) { + var observable = new Observable(); + observable.source = this; + observable.operator = operator; + return observable; + }; + Observable.prototype.subscribe = function (observerOrNext, error, complete) { + var operator = this.operator; + var sink = Object(_util_toSubscriber__WEBPACK_IMPORTED_MODULE_1__["toSubscriber"])(observerOrNext, error, complete); + if (operator) { + sink.add(operator.call(sink, this.source)); + } + else { + sink.add(this.source || (_config__WEBPACK_IMPORTED_MODULE_4__["config"].useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ? + this._subscribe(sink) : + this._trySubscribe(sink)); + } + if (_config__WEBPACK_IMPORTED_MODULE_4__["config"].useDeprecatedSynchronousErrorHandling) { + if (sink.syncErrorThrowable) { + sink.syncErrorThrowable = false; + if (sink.syncErrorThrown) { + throw sink.syncErrorValue; + } + } + } + return sink; + }; + Observable.prototype._trySubscribe = function (sink) { + try { + return this._subscribe(sink); + } + catch (err) { + if (_config__WEBPACK_IMPORTED_MODULE_4__["config"].useDeprecatedSynchronousErrorHandling) { + sink.syncErrorThrown = true; + sink.syncErrorValue = err; + } + if (Object(_util_canReportError__WEBPACK_IMPORTED_MODULE_0__["canReportError"])(sink)) { + sink.error(err); + } + else { + console.warn(err); + } + } + }; + Observable.prototype.forEach = function (next, promiseCtor) { + var _this = this; + promiseCtor = getPromiseCtor(promiseCtor); + return new promiseCtor(function (resolve, reject) { + var subscription; + subscription = _this.subscribe(function (value) { + try { + next(value); + } + catch (err) { + reject(err); + if (subscription) { + subscription.unsubscribe(); + } + } + }, reject, resolve); + }); + }; + Observable.prototype._subscribe = function (subscriber) { + var source = this.source; + return source && source.subscribe(subscriber); + }; + Observable.prototype[_symbol_observable__WEBPACK_IMPORTED_MODULE_2__["observable"]] = function () { + return this; + }; + Observable.prototype.pipe = function () { + var operations = []; + for (var _i = 0; _i < arguments.length; _i++) { + operations[_i] = arguments[_i]; + } + if (operations.length === 0) { + return this; + } + return Object(_util_pipe__WEBPACK_IMPORTED_MODULE_3__["pipeFromArray"])(operations)(this); + }; + Observable.prototype.toPromise = function (promiseCtor) { + var _this = this; + promiseCtor = getPromiseCtor(promiseCtor); + return new promiseCtor(function (resolve, reject) { + var value; + _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); }); + }); + }; + Observable.create = function (subscribe) { + return new Observable(subscribe); + }; + return Observable; +}()); -}))); +function getPromiseCtor(promiseCtor) { + if (!promiseCtor) { + promiseCtor = _config__WEBPACK_IMPORTED_MODULE_4__["config"].Promise || Promise; + } + if (!promiseCtor) { + throw new Error('no Promise impl found'); + } + return promiseCtor; +} +//# sourceMappingURL=Observable.js.map /***/ }), -/* 128 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js locale configuration - -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - +/* 142 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - var monthsShortWithDots = 'jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'), - monthsShortWithoutDots = 'jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_'); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canReportError", function() { return canReportError; }); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(143); +/** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */ - var monthsParse = [/^jan/i, /^feb/i, /^maart|mrt.?$/i, /^apr/i, /^mei$/i, /^jun[i.]?$/i, /^jul[i.]?$/i, /^aug/i, /^sep/i, /^okt/i, /^nov/i, /^dec/i]; - var monthsRegex = /^(januari|februari|maart|april|mei|ju[nl]i|augustus|september|oktober|november|december|jan\.?|feb\.?|mrt\.?|apr\.?|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i; +function canReportError(observer) { + while (observer) { + var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped; + if (closed_1 || isStopped) { + return false; + } + else if (destination && destination instanceof _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"]) { + observer = destination; + } + else { + observer = null; + } + } + return true; +} +//# sourceMappingURL=canReportError.js.map - var nlBe = moment.defineLocale('nl-be', { - months : 'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split('_'), - monthsShort : function (m, format) { - if (!m) { - return monthsShortWithDots; - } else if (/-MMM-/.test(format)) { - return monthsShortWithoutDots[m.month()]; - } else { - return monthsShortWithDots[m.month()]; - } - }, - monthsRegex: monthsRegex, - monthsShortRegex: monthsRegex, - monthsStrictRegex: /^(januari|februari|maart|april|mei|ju[nl]i|augustus|september|oktober|november|december)/i, - monthsShortStrictRegex: /^(jan\.?|feb\.?|mrt\.?|apr\.?|mei|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i, +/***/ }), +/* 143 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - monthsParse : monthsParse, - longMonthsParse : monthsParse, - shortMonthsParse : monthsParse, +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Subscriber", function() { return Subscriber; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SafeSubscriber", function() { return SafeSubscriber; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(144); +/* harmony import */ var _Observer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(145); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(148); +/* harmony import */ var _internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(152); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(146); +/* harmony import */ var _util_hostReportError__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(147); +/** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */ - weekdays : 'zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag'.split('_'), - weekdaysShort : 'zo._ma._di._wo._do._vr._za.'.split('_'), - weekdaysMin : 'zo_ma_di_wo_do_vr_za'.split('_'), - weekdaysParseExact : true, - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd D MMMM YYYY HH:mm' - }, - calendar : { - sameDay: '[vandaag om] LT', - nextDay: '[morgen om] LT', - nextWeek: 'dddd [om] LT', - lastDay: '[gisteren om] LT', - lastWeek: '[afgelopen] dddd [om] LT', - sameElse: 'L' - }, - relativeTime : { - future : 'over %s', - past : '%s geleden', - s : 'een paar seconden', - ss : '%d seconden', - m : 'één minuut', - mm : '%d minuten', - h : 'één uur', - hh : '%d uur', - d : 'één dag', - dd : '%d dagen', - M : 'één maand', - MM : '%d maanden', - y : 'één jaar', - yy : '%d jaar' - }, - dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, - ordinal : function (number) { - return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. - } - }); - return nlBe; -}))); -/***/ }), -/* 129 */ -/***/ (function(module, exports, __webpack_require__) { -//! moment.js locale configuration -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - - - var nn = moment.defineLocale('nn', { - months : 'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split('_'), - monthsShort : 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'), - weekdays : 'sundag_måndag_tysdag_onsdag_torsdag_fredag_laurdag'.split('_'), - weekdaysShort : 'sun_mån_tys_ons_tor_fre_lau'.split('_'), - weekdaysMin : 'su_må_ty_on_to_fr_lø'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D. MMMM YYYY', - LLL : 'D. MMMM YYYY [kl.] H:mm', - LLLL : 'dddd D. MMMM YYYY [kl.] HH:mm' - }, - calendar : { - sameDay: '[I dag klokka] LT', - nextDay: '[I morgon klokka] LT', - nextWeek: 'dddd [klokka] LT', - lastDay: '[I går klokka] LT', - lastWeek: '[Føregåande] dddd [klokka] LT', - sameElse: 'L' - }, - relativeTime : { - future : 'om %s', - past : '%s sidan', - s : 'nokre sekund', - ss : '%d sekund', - m : 'eit minutt', - mm : '%d minutt', - h : 'ein time', - hh : '%d timar', - d : 'ein dag', - dd : '%d dagar', - M : 'ein månad', - MM : '%d månader', - y : 'eit år', - yy : '%d år' - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. +var Subscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Subscriber, _super); + function Subscriber(destinationOrNext, error, complete) { + var _this = _super.call(this) || this; + _this.syncErrorValue = null; + _this.syncErrorThrown = false; + _this.syncErrorThrowable = false; + _this.isStopped = false; + switch (arguments.length) { + case 0: + _this.destination = _Observer__WEBPACK_IMPORTED_MODULE_2__["empty"]; + break; + case 1: + if (!destinationOrNext) { + _this.destination = _Observer__WEBPACK_IMPORTED_MODULE_2__["empty"]; + break; + } + if (typeof destinationOrNext === 'object') { + if (destinationOrNext instanceof Subscriber) { + _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable; + _this.destination = destinationOrNext; + destinationOrNext.add(_this); + } + else { + _this.syncErrorThrowable = true; + _this.destination = new SafeSubscriber(_this, destinationOrNext); + } + break; + } + default: + _this.syncErrorThrowable = true; + _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete); + break; } - }); + return _this; + } + Subscriber.prototype[_internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_4__["rxSubscriber"]] = function () { return this; }; + Subscriber.create = function (next, error, complete) { + var subscriber = new Subscriber(next, error, complete); + subscriber.syncErrorThrowable = false; + return subscriber; + }; + Subscriber.prototype.next = function (value) { + if (!this.isStopped) { + this._next(value); + } + }; + Subscriber.prototype.error = function (err) { + if (!this.isStopped) { + this.isStopped = true; + this._error(err); + } + }; + Subscriber.prototype.complete = function () { + if (!this.isStopped) { + this.isStopped = true; + this._complete(); + } + }; + Subscriber.prototype.unsubscribe = function () { + if (this.closed) { + return; + } + this.isStopped = true; + _super.prototype.unsubscribe.call(this); + }; + Subscriber.prototype._next = function (value) { + this.destination.next(value); + }; + Subscriber.prototype._error = function (err) { + this.destination.error(err); + this.unsubscribe(); + }; + Subscriber.prototype._complete = function () { + this.destination.complete(); + this.unsubscribe(); + }; + Subscriber.prototype._unsubscribeAndRecycle = function () { + var _parentOrParents = this._parentOrParents; + this._parentOrParents = null; + this.unsubscribe(); + this.closed = false; + this.isStopped = false; + this._parentOrParents = _parentOrParents; + return this; + }; + return Subscriber; +}(_Subscription__WEBPACK_IMPORTED_MODULE_3__["Subscription"])); - return nn; +var SafeSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SafeSubscriber, _super); + function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) { + var _this = _super.call(this) || this; + _this._parentSubscriber = _parentSubscriber; + var next; + var context = _this; + if (Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_1__["isFunction"])(observerOrNext)) { + next = observerOrNext; + } + else if (observerOrNext) { + next = observerOrNext.next; + error = observerOrNext.error; + complete = observerOrNext.complete; + if (observerOrNext !== _Observer__WEBPACK_IMPORTED_MODULE_2__["empty"]) { + context = Object.create(observerOrNext); + if (Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_1__["isFunction"])(context.unsubscribe)) { + _this.add(context.unsubscribe.bind(context)); + } + context.unsubscribe = _this.unsubscribe.bind(_this); + } + } + _this._context = context; + _this._next = next; + _this._error = error; + _this._complete = complete; + return _this; + } + SafeSubscriber.prototype.next = function (value) { + if (!this.isStopped && this._next) { + var _parentSubscriber = this._parentSubscriber; + if (!_config__WEBPACK_IMPORTED_MODULE_5__["config"].useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(this._next, value); + } + else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) { + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.error = function (err) { + if (!this.isStopped) { + var _parentSubscriber = this._parentSubscriber; + var useDeprecatedSynchronousErrorHandling = _config__WEBPACK_IMPORTED_MODULE_5__["config"].useDeprecatedSynchronousErrorHandling; + if (this._error) { + if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(this._error, err); + this.unsubscribe(); + } + else { + this.__tryOrSetError(_parentSubscriber, this._error, err); + this.unsubscribe(); + } + } + else if (!_parentSubscriber.syncErrorThrowable) { + this.unsubscribe(); + if (useDeprecatedSynchronousErrorHandling) { + throw err; + } + Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_6__["hostReportError"])(err); + } + else { + if (useDeprecatedSynchronousErrorHandling) { + _parentSubscriber.syncErrorValue = err; + _parentSubscriber.syncErrorThrown = true; + } + else { + Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_6__["hostReportError"])(err); + } + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.complete = function () { + var _this = this; + if (!this.isStopped) { + var _parentSubscriber = this._parentSubscriber; + if (this._complete) { + var wrappedComplete = function () { return _this._complete.call(_this._context); }; + if (!_config__WEBPACK_IMPORTED_MODULE_5__["config"].useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(wrappedComplete); + this.unsubscribe(); + } + else { + this.__tryOrSetError(_parentSubscriber, wrappedComplete); + this.unsubscribe(); + } + } + else { + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) { + try { + fn.call(this._context, value); + } + catch (err) { + this.unsubscribe(); + if (_config__WEBPACK_IMPORTED_MODULE_5__["config"].useDeprecatedSynchronousErrorHandling) { + throw err; + } + else { + Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_6__["hostReportError"])(err); + } + } + }; + SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) { + if (!_config__WEBPACK_IMPORTED_MODULE_5__["config"].useDeprecatedSynchronousErrorHandling) { + throw new Error('bad call'); + } + try { + fn.call(this._context, value); + } + catch (err) { + if (_config__WEBPACK_IMPORTED_MODULE_5__["config"].useDeprecatedSynchronousErrorHandling) { + parent.syncErrorValue = err; + parent.syncErrorThrown = true; + return true; + } + else { + Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_6__["hostReportError"])(err); + return true; + } + } + return false; + }; + SafeSubscriber.prototype._unsubscribe = function () { + var _parentSubscriber = this._parentSubscriber; + this._context = null; + this._parentSubscriber = null; + _parentSubscriber.unsubscribe(); + }; + return SafeSubscriber; +}(Subscriber)); -}))); +//# sourceMappingURL=Subscriber.js.map /***/ }), -/* 130 */ -/***/ (function(module, exports, __webpack_require__) { +/* 144 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -//! moment.js locale configuration +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFunction", function() { return isFunction; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function isFunction(x) { + return typeof x === 'function'; +} +//# sourceMappingURL=isFunction.js.map -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +/***/ }), +/* 145 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "empty", function() { return empty; }); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(146); +/* harmony import */ var _util_hostReportError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(147); +/** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */ - var symbolMap = { - '1': '੧', - '2': '੨', - '3': '੩', - '4': '੪', - '5': '੫', - '6': '੬', - '7': '੭', - '8': '੮', - '9': '੯', - '0': '੦' + +var empty = { + closed: true, + next: function (value) { }, + error: function (err) { + if (_config__WEBPACK_IMPORTED_MODULE_0__["config"].useDeprecatedSynchronousErrorHandling) { + throw err; + } + else { + Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_1__["hostReportError"])(err); + } }, - numberMap = { - '੧': '1', - '੨': '2', - '੩': '3', - '੪': '4', - '੫': '5', - '੬': '6', - '੭': '7', - '੮': '8', - '੯': '9', - '੦': '0' - }; + complete: function () { } +}; +//# sourceMappingURL=Observer.js.map - var paIn = moment.defineLocale('pa-in', { - // There are months name as per Nanakshahi Calendar but they are not used as rigidly in modern Punjabi. - months : 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'), - monthsShort : 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'), - weekdays : 'ਐਤਵਾਰ_ਸੋਮਵਾਰ_ਮੰਗਲਵਾਰ_ਬੁਧਵਾਰ_ਵੀਰਵਾਰ_ਸ਼ੁੱਕਰਵਾਰ_ਸ਼ਨੀਚਰਵਾਰ'.split('_'), - weekdaysShort : 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'), - weekdaysMin : 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'), - longDateFormat : { - LT : 'A h:mm ਵਜੇ', - LTS : 'A h:mm:ss ਵਜੇ', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY, A h:mm ਵਜੇ', - LLLL : 'dddd, D MMMM YYYY, A h:mm ਵਜੇ' - }, - calendar : { - sameDay : '[ਅਜ] LT', - nextDay : '[ਕਲ] LT', - nextWeek : '[ਅਗਲਾ] dddd, LT', - lastDay : '[ਕਲ] LT', - lastWeek : '[ਪਿਛਲੇ] dddd, LT', - sameElse : 'L' - }, - relativeTime : { - future : '%s ਵਿੱਚ', - past : '%s ਪਿਛਲੇ', - s : 'ਕੁਝ ਸਕਿੰਟ', - ss : '%d ਸਕਿੰਟ', - m : 'ਇਕ ਮਿੰਟ', - mm : '%d ਮਿੰਟ', - h : 'ਇੱਕ ਘੰਟਾ', - hh : '%d ਘੰਟੇ', - d : 'ਇੱਕ ਦਿਨ', - dd : '%d ਦਿਨ', - M : 'ਇੱਕ ਮਹੀਨਾ', - MM : '%d ਮਹੀਨੇ', - y : 'ਇੱਕ ਸਾਲ', - yy : '%d ਸਾਲ' - }, - preparse: function (string) { - return string.replace(/[੧੨੩੪੫੬੭੮੯੦]/g, function (match) { - return numberMap[match]; - }); - }, - postformat: function (string) { - return string.replace(/\d/g, function (match) { - return symbolMap[match]; - }); - }, - // Punjabi notation for meridiems are quite fuzzy in practice. While there exists - // a rigid notion of a 'Pahar' it is not used as rigidly in modern Punjabi. - meridiemParse: /ਰਾਤ|ਸਵੇਰ|ਦੁਪਹਿਰ|ਸ਼ਾਮ/, - meridiemHour : function (hour, meridiem) { - if (hour === 12) { - hour = 0; - } - if (meridiem === 'ਰਾਤ') { - return hour < 4 ? hour : hour + 12; - } else if (meridiem === 'ਸਵੇਰ') { - return hour; - } else if (meridiem === 'ਦੁਪਹਿਰ') { - return hour >= 10 ? hour : hour + 12; - } else if (meridiem === 'ਸ਼ਾਮ') { - return hour + 12; - } - }, - meridiem : function (hour, minute, isLower) { - if (hour < 4) { - return 'ਰਾਤ'; - } else if (hour < 10) { - return 'ਸਵੇਰ'; - } else if (hour < 17) { - return 'ਦੁਪਹਿਰ'; - } else if (hour < 20) { - return 'ਸ਼ਾਮ'; - } else { - return 'ਰਾਤ'; - } - }, - week : { - dow : 0, // Sunday is the first day of the week. - doy : 6 // The week that contains Jan 6th is the first week of the year. + +/***/ }), +/* 146 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "config", function() { return config; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var _enable_super_gross_mode_that_will_cause_bad_things = false; +var config = { + Promise: undefined, + set useDeprecatedSynchronousErrorHandling(value) { + if (value) { + var error = /*@__PURE__*/ new Error(); + /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack); } - }); + else if (_enable_super_gross_mode_that_will_cause_bad_things) { + /*@__PURE__*/ console.log('RxJS: Back to a better error behavior. Thank you. <3'); + } + _enable_super_gross_mode_that_will_cause_bad_things = value; + }, + get useDeprecatedSynchronousErrorHandling() { + return _enable_super_gross_mode_that_will_cause_bad_things; + }, +}; +//# sourceMappingURL=config.js.map - return paIn; -}))); +/***/ }), +/* 147 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hostReportError", function() { return hostReportError; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function hostReportError(err) { + setTimeout(function () { throw err; }, 0); +} +//# sourceMappingURL=hostReportError.js.map /***/ }), -/* 131 */ -/***/ (function(module, exports, __webpack_require__) { +/* 148 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -//! moment.js locale configuration +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Subscription", function() { return Subscription; }); +/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); +/* harmony import */ var _util_isObject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(150); +/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(144); +/* harmony import */ var _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(151); +/** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */ -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - var monthsNominative = 'styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień'.split('_'), - monthsSubjective = 'stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia'.split('_'); - function plural(n) { - return (n % 10 < 5) && (n % 10 > 1) && ((~~(n / 10) % 10) !== 1); - } - function translate(number, withoutSuffix, key) { - var result = number + ' '; - switch (key) { - case 'ss': - return result + (plural(number) ? 'sekundy' : 'sekund'); - case 'm': - return withoutSuffix ? 'minuta' : 'minutę'; - case 'mm': - return result + (plural(number) ? 'minuty' : 'minut'); - case 'h': - return withoutSuffix ? 'godzina' : 'godzinę'; - case 'hh': - return result + (plural(number) ? 'godziny' : 'godzin'); - case 'MM': - return result + (plural(number) ? 'miesiące' : 'miesięcy'); - case 'yy': - return result + (plural(number) ? 'lata' : 'lat'); + +var Subscription = /*@__PURE__*/ (function () { + function Subscription(unsubscribe) { + this.closed = false; + this._parentOrParents = null; + this._subscriptions = null; + if (unsubscribe) { + this._unsubscribe = unsubscribe; } } - - var pl = moment.defineLocale('pl', { - months : function (momentToFormat, format) { - if (!momentToFormat) { - return monthsNominative; - } else if (format === '') { - // Hack: if format empty we know this is used to generate - // RegExp by moment. Give then back both valid forms of months - // in RegExp ready format. - return '(' + monthsSubjective[momentToFormat.month()] + '|' + monthsNominative[momentToFormat.month()] + ')'; - } else if (/D MMMM/.test(format)) { - return monthsSubjective[momentToFormat.month()]; - } else { - return monthsNominative[momentToFormat.month()]; - } - }, - monthsShort : 'sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru'.split('_'), - weekdays : 'niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota'.split('_'), - weekdaysShort : 'ndz_pon_wt_śr_czw_pt_sob'.split('_'), - weekdaysMin : 'Nd_Pn_Wt_Śr_Cz_Pt_So'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd, D MMMM YYYY HH:mm' - }, - calendar : { - sameDay: '[Dziś o] LT', - nextDay: '[Jutro o] LT', - nextWeek: function () { - switch (this.day()) { - case 0: - return '[W niedzielę o] LT'; - - case 2: - return '[We wtorek o] LT'; - - case 3: - return '[W środę o] LT'; - - case 6: - return '[W sobotę o] LT'; - - default: - return '[W] dddd [o] LT'; + Subscription.prototype.unsubscribe = function () { + var errors; + if (this.closed) { + return; + } + var _a = this, _parentOrParents = _a._parentOrParents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; + this.closed = true; + this._parentOrParents = null; + this._subscriptions = null; + if (_parentOrParents instanceof Subscription) { + _parentOrParents.remove(this); + } + else if (_parentOrParents !== null) { + for (var index = 0; index < _parentOrParents.length; ++index) { + var parent_1 = _parentOrParents[index]; + parent_1.remove(this); + } + } + if (Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_2__["isFunction"])(_unsubscribe)) { + try { + _unsubscribe.call(this); + } + catch (e) { + errors = e instanceof _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__["UnsubscriptionError"] ? flattenUnsubscriptionErrors(e.errors) : [e]; + } + } + if (Object(_util_isArray__WEBPACK_IMPORTED_MODULE_0__["isArray"])(_subscriptions)) { + var index = -1; + var len = _subscriptions.length; + while (++index < len) { + var sub = _subscriptions[index]; + if (Object(_util_isObject__WEBPACK_IMPORTED_MODULE_1__["isObject"])(sub)) { + try { + sub.unsubscribe(); + } + catch (e) { + errors = errors || []; + if (e instanceof _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__["UnsubscriptionError"]) { + errors = errors.concat(flattenUnsubscriptionErrors(e.errors)); + } + else { + errors.push(e); + } + } } - }, - lastDay: '[Wczoraj o] LT', - lastWeek: function () { - switch (this.day()) { - case 0: - return '[W zeszłą niedzielę o] LT'; - case 3: - return '[W zeszłą środę o] LT'; - case 6: - return '[W zeszłą sobotę o] LT'; - default: - return '[W zeszły] dddd [o] LT'; + } + } + if (errors) { + throw new _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__["UnsubscriptionError"](errors); + } + }; + Subscription.prototype.add = function (teardown) { + var subscription = teardown; + if (!teardown) { + return Subscription.EMPTY; + } + switch (typeof teardown) { + case 'function': + subscription = new Subscription(teardown); + case 'object': + if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') { + return subscription; } - }, - sameElse: 'L' - }, - relativeTime : { - future : 'za %s', - past : '%s temu', - s : 'kilka sekund', - ss : translate, - m : translate, - mm : translate, - h : translate, - hh : translate, - d : '1 dzień', - dd : '%d dni', - M : 'miesiąc', - MM : translate, - y : 'rok', - yy : translate - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + else if (this.closed) { + subscription.unsubscribe(); + return subscription; + } + else if (!(subscription instanceof Subscription)) { + var tmp = subscription; + subscription = new Subscription(); + subscription._subscriptions = [tmp]; + } + break; + default: { + throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); + } } - }); - - return pl; + var _parentOrParents = subscription._parentOrParents; + if (_parentOrParents === null) { + subscription._parentOrParents = this; + } + else if (_parentOrParents instanceof Subscription) { + if (_parentOrParents === this) { + return subscription; + } + subscription._parentOrParents = [_parentOrParents, this]; + } + else if (_parentOrParents.indexOf(this) === -1) { + _parentOrParents.push(this); + } + else { + return subscription; + } + var subscriptions = this._subscriptions; + if (subscriptions === null) { + this._subscriptions = [subscription]; + } + else { + subscriptions.push(subscription); + } + return subscription; + }; + Subscription.prototype.remove = function (subscription) { + var subscriptions = this._subscriptions; + if (subscriptions) { + var subscriptionIndex = subscriptions.indexOf(subscription); + if (subscriptionIndex !== -1) { + subscriptions.splice(subscriptionIndex, 1); + } + } + }; + Subscription.EMPTY = (function (empty) { + empty.closed = true; + return empty; + }(new Subscription())); + return Subscription; +}()); -}))); +function flattenUnsubscriptionErrors(errors) { + return errors.reduce(function (errs, err) { return errs.concat((err instanceof _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__["UnsubscriptionError"]) ? err.errors : err); }, []); +} +//# sourceMappingURL=Subscription.js.map /***/ }), -/* 132 */ -/***/ (function(module, exports, __webpack_require__) { +/* 149 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -//! moment.js locale configuration +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isArray", function() { return isArray; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var isArray = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })(); +//# sourceMappingURL=isArray.js.map -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +/***/ }), +/* 150 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - var pt = moment.defineLocale('pt', { - months : 'Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro'.split('_'), - monthsShort : 'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'), - weekdays : 'Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado'.split('_'), - weekdaysShort : 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'), - weekdaysMin : 'Do_2ª_3ª_4ª_5ª_6ª_Sá'.split('_'), - weekdaysParseExact : true, - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D [de] MMMM [de] YYYY', - LLL : 'D [de] MMMM [de] YYYY HH:mm', - LLLL : 'dddd, D [de] MMMM [de] YYYY HH:mm' - }, - calendar : { - sameDay: '[Hoje às] LT', - nextDay: '[Amanhã às] LT', - nextWeek: 'dddd [às] LT', - lastDay: '[Ontem às] LT', - lastWeek: function () { - return (this.day() === 0 || this.day() === 6) ? - '[Último] dddd [às] LT' : // Saturday + Sunday - '[Última] dddd [às] LT'; // Monday - Friday - }, - sameElse: 'L' - }, - relativeTime : { - future : 'em %s', - past : 'há %s', - s : 'segundos', - ss : '%d segundos', - m : 'um minuto', - mm : '%d minutos', - h : 'uma hora', - hh : '%d horas', - d : 'um dia', - dd : '%d dias', - M : 'um mês', - MM : '%d meses', - y : 'um ano', - yy : '%d anos' - }, - dayOfMonthOrdinalParse: /\d{1,2}º/, - ordinal : '%dº', - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. - } - }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isObject", function() { return isObject; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function isObject(x) { + return x !== null && typeof x === 'object'; +} +//# sourceMappingURL=isObject.js.map - return pt; -}))); +/***/ }), +/* 151 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UnsubscriptionError", function() { return UnsubscriptionError; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var UnsubscriptionErrorImpl = /*@__PURE__*/ (function () { + function UnsubscriptionErrorImpl(errors) { + Error.call(this); + this.message = errors ? + errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ') : ''; + this.name = 'UnsubscriptionError'; + this.errors = errors; + return this; + } + UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); + return UnsubscriptionErrorImpl; +})(); +var UnsubscriptionError = UnsubscriptionErrorImpl; +//# sourceMappingURL=UnsubscriptionError.js.map /***/ }), -/* 133 */ -/***/ (function(module, exports, __webpack_require__) { +/* 152 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -//! moment.js locale configuration +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rxSubscriber", function() { return rxSubscriber; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "$$rxSubscriber", function() { return $$rxSubscriber; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var rxSubscriber = /*@__PURE__*/ (function () { + return typeof Symbol === 'function' + ? /*@__PURE__*/ Symbol('rxSubscriber') + : '@@rxSubscriber_' + /*@__PURE__*/ Math.random(); +})(); +var $$rxSubscriber = rxSubscriber; +//# sourceMappingURL=rxSubscriber.js.map -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +/***/ }), +/* 153 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - var ptBr = moment.defineLocale('pt-br', { - months : 'Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro'.split('_'), - monthsShort : 'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'), - weekdays : 'Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado'.split('_'), - weekdaysShort : 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'), - weekdaysMin : 'Do_2ª_3ª_4ª_5ª_6ª_Sá'.split('_'), - weekdaysParseExact : true, - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D [de] MMMM [de] YYYY', - LLL : 'D [de] MMMM [de] YYYY [às] HH:mm', - LLLL : 'dddd, D [de] MMMM [de] YYYY [às] HH:mm' - }, - calendar : { - sameDay: '[Hoje às] LT', - nextDay: '[Amanhã às] LT', - nextWeek: 'dddd [às] LT', - lastDay: '[Ontem às] LT', - lastWeek: function () { - return (this.day() === 0 || this.day() === 6) ? - '[Último] dddd [às] LT' : // Saturday + Sunday - '[Última] dddd [às] LT'; // Monday - Friday - }, - sameElse: 'L' - }, - relativeTime : { - future : 'em %s', - past : 'há %s', - s : 'poucos segundos', - ss : '%d segundos', - m : 'um minuto', - mm : '%d minutos', - h : 'uma hora', - hh : '%d horas', - d : 'um dia', - dd : '%d dias', - M : 'um mês', - MM : '%d meses', - y : 'um ano', - yy : '%d anos' - }, - dayOfMonthOrdinalParse: /\d{1,2}º/, - ordinal : '%dº' - }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toSubscriber", function() { return toSubscriber; }); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(143); +/* harmony import */ var _symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(152); +/* harmony import */ var _Observer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(145); +/** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */ - return ptBr; -}))); + +function toSubscriber(nextOrObserver, error, complete) { + if (nextOrObserver) { + if (nextOrObserver instanceof _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"]) { + return nextOrObserver; + } + if (nextOrObserver[_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_1__["rxSubscriber"]]) { + return nextOrObserver[_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_1__["rxSubscriber"]](); + } + } + if (!nextOrObserver && !error && !complete) { + return new _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"](_Observer__WEBPACK_IMPORTED_MODULE_2__["empty"]); + } + return new _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"](nextOrObserver, error, complete); +} +//# sourceMappingURL=toSubscriber.js.map /***/ }), -/* 134 */ -/***/ (function(module, exports, __webpack_require__) { +/* 154 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -//! moment.js locale configuration +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "observable", function() { return observable; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })(); +//# sourceMappingURL=observable.js.map -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +/***/ }), +/* 155 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - function relativeTimeWithPlural(number, withoutSuffix, key) { - var format = { - 'ss': 'secunde', - 'mm': 'minute', - 'hh': 'ore', - 'dd': 'zile', - 'MM': 'luni', - 'yy': 'ani' - }, - separator = ' '; - if (number % 100 >= 20 || (number >= 100 && number % 100 === 0)) { - separator = ' de '; - } - return number + separator + format[key]; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pipe", function() { return pipe; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pipeFromArray", function() { return pipeFromArray; }); +/* harmony import */ var _noop__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(156); +/** PURE_IMPORTS_START _noop PURE_IMPORTS_END */ + +function pipe() { + var fns = []; + for (var _i = 0; _i < arguments.length; _i++) { + fns[_i] = arguments[_i]; + } + return pipeFromArray(fns); +} +function pipeFromArray(fns) { + if (!fns) { + return _noop__WEBPACK_IMPORTED_MODULE_0__["noop"]; + } + if (fns.length === 1) { + return fns[0]; } + return function piped(input) { + return fns.reduce(function (prev, fn) { return fn(prev); }, input); + }; +} +//# sourceMappingURL=pipe.js.map - var ro = moment.defineLocale('ro', { - months : 'ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie'.split('_'), - monthsShort : 'ian._febr._mart._apr._mai_iun._iul._aug._sept._oct._nov._dec.'.split('_'), - monthsParseExact: true, - weekdays : 'duminică_luni_marți_miercuri_joi_vineri_sâmbătă'.split('_'), - weekdaysShort : 'Dum_Lun_Mar_Mie_Joi_Vin_Sâm'.split('_'), - weekdaysMin : 'Du_Lu_Ma_Mi_Jo_Vi_Sâ'.split('_'), - longDateFormat : { - LT : 'H:mm', - LTS : 'H:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY H:mm', - LLLL : 'dddd, D MMMM YYYY H:mm' - }, - calendar : { - sameDay: '[azi la] LT', - nextDay: '[mâine la] LT', - nextWeek: 'dddd [la] LT', - lastDay: '[ieri la] LT', - lastWeek: '[fosta] dddd [la] LT', - sameElse: 'L' - }, - relativeTime : { - future : 'peste %s', - past : '%s în urmă', - s : 'câteva secunde', - ss : relativeTimeWithPlural, - m : 'un minut', - mm : relativeTimeWithPlural, - h : 'o oră', - hh : relativeTimeWithPlural, - d : 'o zi', - dd : relativeTimeWithPlural, - M : 'o lună', - MM : relativeTimeWithPlural, - y : 'un an', - yy : relativeTimeWithPlural - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. - } - }); - return ro; +/***/ }), +/* 156 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -}))); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "noop", function() { return noop; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function noop() { } +//# sourceMappingURL=noop.js.map /***/ }), -/* 135 */ -/***/ (function(module, exports, __webpack_require__) { +/* 157 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -//! moment.js locale configuration +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ConnectableObservable", function() { return ConnectableObservable; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "connectableObservableDescriptor", function() { return connectableObservableDescriptor; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(158); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(141); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(143); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(148); +/* harmony import */ var _operators_refCount__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(161); +/** PURE_IMPORTS_START tslib,_Subject,_Observable,_Subscriber,_Subscription,_operators_refCount PURE_IMPORTS_END */ -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - function plural(word, num) { - var forms = word.split('_'); - return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); - } - function relativeTimeWithPlural(number, withoutSuffix, key) { - var format = { - 'ss': withoutSuffix ? 'секунда_секунды_секунд' : 'секунду_секунды_секунд', - 'mm': withoutSuffix ? 'минута_минуты_минут' : 'минуту_минуты_минут', - 'hh': 'час_часа_часов', - 'dd': 'день_дня_дней', - 'MM': 'месяц_месяца_месяцев', - 'yy': 'год_года_лет' - }; - if (key === 'm') { - return withoutSuffix ? 'минута' : 'минуту'; - } - else { - return number + ' ' + plural(format[key], +number); - } - } - var monthsParse = [/^янв/i, /^фев/i, /^мар/i, /^апр/i, /^ма[йя]/i, /^июн/i, /^июл/i, /^авг/i, /^сен/i, /^окт/i, /^ноя/i, /^дек/i]; - - // http://new.gramota.ru/spravka/rules/139-prop : § 103 - // Сокращения месяцев: http://new.gramota.ru/spravka/buro/search-answer?s=242637 - // CLDR data: http://www.unicode.org/cldr/charts/28/summary/ru.html#1753 - var ru = moment.defineLocale('ru', { - months : { - format: 'января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря'.split('_'), - standalone: 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_') - }, - monthsShort : { - // по CLDR именно "июл." и "июн.", но какой смысл менять букву на точку ? - format: 'янв._февр._мар._апр._мая_июня_июля_авг._сент._окт._нояб._дек.'.split('_'), - standalone: 'янв._февр._март_апр._май_июнь_июль_авг._сент._окт._нояб._дек.'.split('_') - }, - weekdays : { - standalone: 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_'), - format: 'воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу'.split('_'), - isFormat: /\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/ - }, - weekdaysShort : 'вс_пн_вт_ср_чт_пт_сб'.split('_'), - weekdaysMin : 'вс_пн_вт_ср_чт_пт_сб'.split('_'), - monthsParse : monthsParse, - longMonthsParse : monthsParse, - shortMonthsParse : monthsParse, - - // полные названия с падежами, по три буквы, для некоторых, по 4 буквы, сокращения с точкой и без точки - monthsRegex: /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i, - // копия предыдущего - monthsShortRegex: /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i, - // полные названия с падежами - monthsStrictRegex: /^(январ[яь]|феврал[яь]|марта?|апрел[яь]|ма[яй]|июн[яь]|июл[яь]|августа?|сентябр[яь]|октябр[яь]|ноябр[яь]|декабр[яь])/i, - // Выражение, которое соотвествует только сокращённым формам - monthsShortStrictRegex: /^(янв\.|февр?\.|мар[т.]|апр\.|ма[яй]|июн[ья.]|июл[ья.]|авг\.|сент?\.|окт\.|нояб?\.|дек\.)/i, - longDateFormat : { - LT : 'H:mm', - LTS : 'H:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D MMMM YYYY г.', - LLL : 'D MMMM YYYY г., H:mm', - LLLL : 'dddd, D MMMM YYYY г., H:mm' - }, - calendar : { - sameDay: '[Сегодня, в] LT', - nextDay: '[Завтра, в] LT', - lastDay: '[Вчера, в] LT', - nextWeek: function (now) { - if (now.week() !== this.week()) { - switch (this.day()) { - case 0: - return '[В следующее] dddd, [в] LT'; - case 1: - case 2: - case 4: - return '[В следующий] dddd, [в] LT'; - case 3: - case 5: - case 6: - return '[В следующую] dddd, [в] LT'; - } - } else { - if (this.day() === 2) { - return '[Во] dddd, [в] LT'; - } else { - return '[В] dddd, [в] LT'; - } - } - }, - lastWeek: function (now) { - if (now.week() !== this.week()) { - switch (this.day()) { - case 0: - return '[В прошлое] dddd, [в] LT'; - case 1: - case 2: - case 4: - return '[В прошлый] dddd, [в] LT'; - case 3: - case 5: - case 6: - return '[В прошлую] dddd, [в] LT'; - } - } else { - if (this.day() === 2) { - return '[Во] dddd, [в] LT'; - } else { - return '[В] dddd, [в] LT'; - } - } - }, - sameElse: 'L' - }, - relativeTime : { - future : 'через %s', - past : '%s назад', - s : 'несколько секунд', - ss : relativeTimeWithPlural, - m : relativeTimeWithPlural, - mm : relativeTimeWithPlural, - h : 'час', - hh : relativeTimeWithPlural, - d : 'день', - dd : relativeTimeWithPlural, - M : 'месяц', - MM : relativeTimeWithPlural, - y : 'год', - yy : relativeTimeWithPlural - }, - meridiemParse: /ночи|утра|дня|вечера/i, - isPM : function (input) { - return /^(дня|вечера)$/.test(input); - }, - meridiem : function (hour, minute, isLower) { - if (hour < 4) { - return 'ночи'; - } else if (hour < 12) { - return 'утра'; - } else if (hour < 17) { - return 'дня'; - } else { - return 'вечера'; - } - }, - dayOfMonthOrdinalParse: /\d{1,2}-(й|го|я)/, - ordinal: function (number, period) { - switch (period) { - case 'M': - case 'd': - case 'DDD': - return number + '-й'; - case 'D': - return number + '-го'; - case 'w': - case 'W': - return number + '-я'; - default: - return number; +var ConnectableObservable = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ConnectableObservable, _super); + function ConnectableObservable(source, subjectFactory) { + var _this = _super.call(this) || this; + _this.source = source; + _this.subjectFactory = subjectFactory; + _this._refCount = 0; + _this._isComplete = false; + return _this; + } + ConnectableObservable.prototype._subscribe = function (subscriber) { + return this.getSubject().subscribe(subscriber); + }; + ConnectableObservable.prototype.getSubject = function () { + var subject = this._subject; + if (!subject || subject.isStopped) { + this._subject = this.subjectFactory(); + } + return this._subject; + }; + ConnectableObservable.prototype.connect = function () { + var connection = this._connection; + if (!connection) { + this._isComplete = false; + connection = this._connection = new _Subscription__WEBPACK_IMPORTED_MODULE_4__["Subscription"](); + connection.add(this.source + .subscribe(new ConnectableSubscriber(this.getSubject(), this))); + if (connection.closed) { + this._connection = null; + connection = _Subscription__WEBPACK_IMPORTED_MODULE_4__["Subscription"].EMPTY; } - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. } - }); - - return ru; - -}))); - - -/***/ }), -/* 136 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js locale configuration - -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - - - var months = [ - 'جنوري', - 'فيبروري', - 'مارچ', - 'اپريل', - 'مئي', - 'جون', - 'جولاءِ', - 'آگسٽ', - 'سيپٽمبر', - 'آڪٽوبر', - 'نومبر', - 'ڊسمبر' - ]; - var days = [ - 'آچر', - 'سومر', - 'اڱارو', - 'اربع', - 'خميس', - 'جمع', - 'ڇنڇر' - ]; + return connection; + }; + ConnectableObservable.prototype.refCount = function () { + return Object(_operators_refCount__WEBPACK_IMPORTED_MODULE_5__["refCount"])()(this); + }; + return ConnectableObservable; +}(_Observable__WEBPACK_IMPORTED_MODULE_2__["Observable"])); - var sd = moment.defineLocale('sd', { - months : months, - monthsShort : months, - weekdays : days, - weekdaysShort : days, - weekdaysMin : days, - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd، D MMMM YYYY HH:mm' - }, - meridiemParse: /صبح|شام/, - isPM : function (input) { - return 'شام' === input; - }, - meridiem : function (hour, minute, isLower) { - if (hour < 12) { - return 'صبح'; +var connectableObservableDescriptor = /*@__PURE__*/ (function () { + var connectableProto = ConnectableObservable.prototype; + return { + operator: { value: null }, + _refCount: { value: 0, writable: true }, + _subject: { value: null, writable: true }, + _connection: { value: null, writable: true }, + _subscribe: { value: connectableProto._subscribe }, + _isComplete: { value: connectableProto._isComplete, writable: true }, + getSubject: { value: connectableProto.getSubject }, + connect: { value: connectableProto.connect }, + refCount: { value: connectableProto.refCount } + }; +})(); +var ConnectableSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ConnectableSubscriber, _super); + function ConnectableSubscriber(destination, connectable) { + var _this = _super.call(this, destination) || this; + _this.connectable = connectable; + return _this; + } + ConnectableSubscriber.prototype._error = function (err) { + this._unsubscribe(); + _super.prototype._error.call(this, err); + }; + ConnectableSubscriber.prototype._complete = function () { + this.connectable._isComplete = true; + this._unsubscribe(); + _super.prototype._complete.call(this); + }; + ConnectableSubscriber.prototype._unsubscribe = function () { + var connectable = this.connectable; + if (connectable) { + this.connectable = null; + var connection = connectable._connection; + connectable._refCount = 0; + connectable._subject = null; + connectable._connection = null; + if (connection) { + connection.unsubscribe(); } - return 'شام'; - }, - calendar : { - sameDay : '[اڄ] LT', - nextDay : '[سڀاڻي] LT', - nextWeek : 'dddd [اڳين هفتي تي] LT', - lastDay : '[ڪالهه] LT', - lastWeek : '[گزريل هفتي] dddd [تي] LT', - sameElse : 'L' - }, - relativeTime : { - future : '%s پوء', - past : '%s اڳ', - s : 'چند سيڪنڊ', - ss : '%d سيڪنڊ', - m : 'هڪ منٽ', - mm : '%d منٽ', - h : 'هڪ ڪلاڪ', - hh : '%d ڪلاڪ', - d : 'هڪ ڏينهن', - dd : '%d ڏينهن', - M : 'هڪ مهينو', - MM : '%d مهينا', - y : 'هڪ سال', - yy : '%d سال' - }, - preparse: function (string) { - return string.replace(/،/g, ','); - }, - postformat: function (string) { - return string.replace(/,/g, '،'); - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. } - }); - - return sd; - -}))); + }; + return ConnectableSubscriber; +}(_Subject__WEBPACK_IMPORTED_MODULE_1__["SubjectSubscriber"])); +var RefCountOperator = /*@__PURE__*/ (function () { + function RefCountOperator(connectable) { + this.connectable = connectable; + } + RefCountOperator.prototype.call = function (subscriber, source) { + var connectable = this.connectable; + connectable._refCount++; + var refCounter = new RefCountSubscriber(subscriber, connectable); + var subscription = source.subscribe(refCounter); + if (!refCounter.closed) { + refCounter.connection = connectable.connect(); + } + return subscription; + }; + return RefCountOperator; +}()); +var RefCountSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RefCountSubscriber, _super); + function RefCountSubscriber(destination, connectable) { + var _this = _super.call(this, destination) || this; + _this.connectable = connectable; + return _this; + } + RefCountSubscriber.prototype._unsubscribe = function () { + var connectable = this.connectable; + if (!connectable) { + this.connection = null; + return; + } + this.connectable = null; + var refCount = connectable._refCount; + if (refCount <= 0) { + this.connection = null; + return; + } + connectable._refCount = refCount - 1; + if (refCount > 1) { + this.connection = null; + return; + } + var connection = this.connection; + var sharedConnection = connectable._connection; + this.connection = null; + if (sharedConnection && (!connection || sharedConnection === connection)) { + sharedConnection.unsubscribe(); + } + }; + return RefCountSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_3__["Subscriber"])); +//# sourceMappingURL=ConnectableObservable.js.map /***/ }), -/* 137 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js locale configuration - -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - +/* 158 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - var se = moment.defineLocale('se', { - months : 'ođđajagemánnu_guovvamánnu_njukčamánnu_cuoŋománnu_miessemánnu_geassemánnu_suoidnemánnu_borgemánnu_čakčamánnu_golggotmánnu_skábmamánnu_juovlamánnu'.split('_'), - monthsShort : 'ođđj_guov_njuk_cuo_mies_geas_suoi_borg_čakč_golg_skáb_juov'.split('_'), - weekdays : 'sotnabeaivi_vuossárga_maŋŋebárga_gaskavahkku_duorastat_bearjadat_lávvardat'.split('_'), - weekdaysShort : 'sotn_vuos_maŋ_gask_duor_bear_láv'.split('_'), - weekdaysMin : 's_v_m_g_d_b_L'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD.MM.YYYY', - LL : 'MMMM D. [b.] YYYY', - LLL : 'MMMM D. [b.] YYYY [ti.] HH:mm', - LLLL : 'dddd, MMMM D. [b.] YYYY [ti.] HH:mm' - }, - calendar : { - sameDay: '[otne ti] LT', - nextDay: '[ihttin ti] LT', - nextWeek: 'dddd [ti] LT', - lastDay: '[ikte ti] LT', - lastWeek: '[ovddit] dddd [ti] LT', - sameElse: 'L' - }, - relativeTime : { - future : '%s geažes', - past : 'maŋit %s', - s : 'moadde sekunddat', - ss: '%d sekunddat', - m : 'okta minuhta', - mm : '%d minuhtat', - h : 'okta diimmu', - hh : '%d diimmut', - d : 'okta beaivi', - dd : '%d beaivvit', - M : 'okta mánnu', - MM : '%d mánut', - y : 'okta jahki', - yy : '%d jagit' - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. - } - }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubjectSubscriber", function() { return SubjectSubscriber; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Subject", function() { return Subject; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnonymousSubject", function() { return AnonymousSubject; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(141); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(143); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(148); +/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(159); +/* harmony import */ var _SubjectSubscription__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(160); +/* harmony import */ var _internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(152); +/** PURE_IMPORTS_START tslib,_Observable,_Subscriber,_Subscription,_util_ObjectUnsubscribedError,_SubjectSubscription,_internal_symbol_rxSubscriber PURE_IMPORTS_END */ - return se; -}))); -/***/ }), -/* 138 */ -/***/ (function(module, exports, __webpack_require__) { -//! moment.js locale configuration -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +var SubjectSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SubjectSubscriber, _super); + function SubjectSubscriber(destination) { + var _this = _super.call(this, destination) || this; + _this.destination = destination; + return _this; + } + return SubjectSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_2__["Subscriber"])); - /*jshint -W100*/ - var si = moment.defineLocale('si', { - months : 'ජනවාරි_පෙබරවාරි_මාර්තු_අප්‍රේල්_මැයි_ජූනි_ජූලි_අගෝස්තු_සැප්තැම්බර්_ඔක්තෝබර්_නොවැම්බර්_දෙසැම්බර්'.split('_'), - monthsShort : 'ජන_පෙබ_මාර්_අප්_මැයි_ජූනි_ජූලි_අගෝ_සැප්_ඔක්_නොවැ_දෙසැ'.split('_'), - weekdays : 'ඉරිදා_සඳුදා_අඟහරුවාදා_බදාදා_බ්‍රහස්පතින්දා_සිකුරාදා_සෙනසුරාදා'.split('_'), - weekdaysShort : 'ඉරි_සඳු_අඟ_බදා_බ්‍රහ_සිකු_සෙන'.split('_'), - weekdaysMin : 'ඉ_ස_අ_බ_බ්‍ර_සි_සෙ'.split('_'), - weekdaysParseExact : true, - longDateFormat : { - LT : 'a h:mm', - LTS : 'a h:mm:ss', - L : 'YYYY/MM/DD', - LL : 'YYYY MMMM D', - LLL : 'YYYY MMMM D, a h:mm', - LLLL : 'YYYY MMMM D [වැනි] dddd, a h:mm:ss' - }, - calendar : { - sameDay : '[අද] LT[ට]', - nextDay : '[හෙට] LT[ට]', - nextWeek : 'dddd LT[ට]', - lastDay : '[ඊයේ] LT[ට]', - lastWeek : '[පසුගිය] dddd LT[ට]', - sameElse : 'L' - }, - relativeTime : { - future : '%sකින්', - past : '%sකට පෙර', - s : 'තත්පර කිහිපය', - ss : 'තත්පර %d', - m : 'මිනිත්තුව', - mm : 'මිනිත්තු %d', - h : 'පැය', - hh : 'පැය %d', - d : 'දිනය', - dd : 'දින %d', - M : 'මාසය', - MM : 'මාස %d', - y : 'වසර', - yy : 'වසර %d' - }, - dayOfMonthOrdinalParse: /\d{1,2} වැනි/, - ordinal : function (number) { - return number + ' වැනි'; - }, - meridiemParse : /පෙර වරු|පස් වරු|පෙ.ව|ප.ව./, - isPM : function (input) { - return input === 'ප.ව.' || input === 'පස් වරු'; - }, - meridiem : function (hours, minutes, isLower) { - if (hours > 11) { - return isLower ? 'ප.ව.' : 'පස් වරු'; - } else { - return isLower ? 'පෙ.ව.' : 'පෙර වරු'; +var Subject = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Subject, _super); + function Subject() { + var _this = _super.call(this) || this; + _this.observers = []; + _this.closed = false; + _this.isStopped = false; + _this.hasError = false; + _this.thrownError = null; + return _this; + } + Subject.prototype[_internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_6__["rxSubscriber"]] = function () { + return new SubjectSubscriber(this); + }; + Subject.prototype.lift = function (operator) { + var subject = new AnonymousSubject(this, this); + subject.operator = operator; + return subject; + }; + Subject.prototype.next = function (value) { + if (this.closed) { + throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__["ObjectUnsubscribedError"](); + } + if (!this.isStopped) { + var observers = this.observers; + var len = observers.length; + var copy = observers.slice(); + for (var i = 0; i < len; i++) { + copy[i].next(value); } } - }); + }; + Subject.prototype.error = function (err) { + if (this.closed) { + throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__["ObjectUnsubscribedError"](); + } + this.hasError = true; + this.thrownError = err; + this.isStopped = true; + var observers = this.observers; + var len = observers.length; + var copy = observers.slice(); + for (var i = 0; i < len; i++) { + copy[i].error(err); + } + this.observers.length = 0; + }; + Subject.prototype.complete = function () { + if (this.closed) { + throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__["ObjectUnsubscribedError"](); + } + this.isStopped = true; + var observers = this.observers; + var len = observers.length; + var copy = observers.slice(); + for (var i = 0; i < len; i++) { + copy[i].complete(); + } + this.observers.length = 0; + }; + Subject.prototype.unsubscribe = function () { + this.isStopped = true; + this.closed = true; + this.observers = null; + }; + Subject.prototype._trySubscribe = function (subscriber) { + if (this.closed) { + throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__["ObjectUnsubscribedError"](); + } + else { + return _super.prototype._trySubscribe.call(this, subscriber); + } + }; + Subject.prototype._subscribe = function (subscriber) { + if (this.closed) { + throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__["ObjectUnsubscribedError"](); + } + else if (this.hasError) { + subscriber.error(this.thrownError); + return _Subscription__WEBPACK_IMPORTED_MODULE_3__["Subscription"].EMPTY; + } + else if (this.isStopped) { + subscriber.complete(); + return _Subscription__WEBPACK_IMPORTED_MODULE_3__["Subscription"].EMPTY; + } + else { + this.observers.push(subscriber); + return new _SubjectSubscription__WEBPACK_IMPORTED_MODULE_5__["SubjectSubscription"](this, subscriber); + } + }; + Subject.prototype.asObservable = function () { + var observable = new _Observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + observable.source = this; + return observable; + }; + Subject.create = function (destination, source) { + return new AnonymousSubject(destination, source); + }; + return Subject; +}(_Observable__WEBPACK_IMPORTED_MODULE_1__["Observable"])); - return si; +var AnonymousSubject = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AnonymousSubject, _super); + function AnonymousSubject(destination, source) { + var _this = _super.call(this) || this; + _this.destination = destination; + _this.source = source; + return _this; + } + AnonymousSubject.prototype.next = function (value) { + var destination = this.destination; + if (destination && destination.next) { + destination.next(value); + } + }; + AnonymousSubject.prototype.error = function (err) { + var destination = this.destination; + if (destination && destination.error) { + this.destination.error(err); + } + }; + AnonymousSubject.prototype.complete = function () { + var destination = this.destination; + if (destination && destination.complete) { + this.destination.complete(); + } + }; + AnonymousSubject.prototype._subscribe = function (subscriber) { + var source = this.source; + if (source) { + return this.source.subscribe(subscriber); + } + else { + return _Subscription__WEBPACK_IMPORTED_MODULE_3__["Subscription"].EMPTY; + } + }; + return AnonymousSubject; +}(Subject)); -}))); +//# sourceMappingURL=Subject.js.map /***/ }), -/* 139 */ -/***/ (function(module, exports, __webpack_require__) { +/* 159 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -//! moment.js locale configuration +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ObjectUnsubscribedError", function() { return ObjectUnsubscribedError; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var ObjectUnsubscribedErrorImpl = /*@__PURE__*/ (function () { + function ObjectUnsubscribedErrorImpl() { + Error.call(this); + this.message = 'object unsubscribed'; + this.name = 'ObjectUnsubscribedError'; + return this; + } + ObjectUnsubscribedErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); + return ObjectUnsubscribedErrorImpl; +})(); +var ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl; +//# sourceMappingURL=ObjectUnsubscribedError.js.map -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +/***/ }), +/* 160 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - var months = 'január_február_marec_apríl_máj_jún_júl_august_september_október_november_december'.split('_'), - monthsShort = 'jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec'.split('_'); - function plural(n) { - return (n > 1) && (n < 5); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubjectSubscription", function() { return SubjectSubscription; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(148); +/** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */ + + +var SubjectSubscription = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SubjectSubscription, _super); + function SubjectSubscription(subject, subscriber) { + var _this = _super.call(this) || this; + _this.subject = subject; + _this.subscriber = subscriber; + _this.closed = false; + return _this; } - function translate(number, withoutSuffix, key, isFuture) { - var result = number + ' '; - switch (key) { - case 's': // a few seconds / in a few seconds / a few seconds ago - return (withoutSuffix || isFuture) ? 'pár sekúnd' : 'pár sekundami'; - case 'ss': // 9 seconds / in 9 seconds / 9 seconds ago - if (withoutSuffix || isFuture) { - return result + (plural(number) ? 'sekundy' : 'sekúnd'); - } else { - return result + 'sekundami'; - } - break; - case 'm': // a minute / in a minute / a minute ago - return withoutSuffix ? 'minúta' : (isFuture ? 'minútu' : 'minútou'); - case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago - if (withoutSuffix || isFuture) { - return result + (plural(number) ? 'minúty' : 'minút'); - } else { - return result + 'minútami'; - } - break; - case 'h': // an hour / in an hour / an hour ago - return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou'); - case 'hh': // 9 hours / in 9 hours / 9 hours ago - if (withoutSuffix || isFuture) { - return result + (plural(number) ? 'hodiny' : 'hodín'); - } else { - return result + 'hodinami'; - } - break; - case 'd': // a day / in a day / a day ago - return (withoutSuffix || isFuture) ? 'deň' : 'dňom'; - case 'dd': // 9 days / in 9 days / 9 days ago - if (withoutSuffix || isFuture) { - return result + (plural(number) ? 'dni' : 'dní'); - } else { - return result + 'dňami'; - } - break; - case 'M': // a month / in a month / a month ago - return (withoutSuffix || isFuture) ? 'mesiac' : 'mesiacom'; - case 'MM': // 9 months / in 9 months / 9 months ago - if (withoutSuffix || isFuture) { - return result + (plural(number) ? 'mesiace' : 'mesiacov'); - } else { - return result + 'mesiacmi'; - } - break; - case 'y': // a year / in a year / a year ago - return (withoutSuffix || isFuture) ? 'rok' : 'rokom'; - case 'yy': // 9 years / in 9 years / 9 years ago - if (withoutSuffix || isFuture) { - return result + (plural(number) ? 'roky' : 'rokov'); - } else { - return result + 'rokmi'; - } - break; + SubjectSubscription.prototype.unsubscribe = function () { + if (this.closed) { + return; } - } - - var sk = moment.defineLocale('sk', { - months : months, - monthsShort : monthsShort, - weekdays : 'nedeľa_pondelok_utorok_streda_štvrtok_piatok_sobota'.split('_'), - weekdaysShort : 'ne_po_ut_st_št_pi_so'.split('_'), - weekdaysMin : 'ne_po_ut_st_št_pi_so'.split('_'), - longDateFormat : { - LT: 'H:mm', - LTS : 'H:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D. MMMM YYYY', - LLL : 'D. MMMM YYYY H:mm', - LLLL : 'dddd D. MMMM YYYY H:mm' - }, - calendar : { - sameDay: '[dnes o] LT', - nextDay: '[zajtra o] LT', - nextWeek: function () { - switch (this.day()) { - case 0: - return '[v nedeľu o] LT'; - case 1: - case 2: - return '[v] dddd [o] LT'; - case 3: - return '[v stredu o] LT'; - case 4: - return '[vo štvrtok o] LT'; - case 5: - return '[v piatok o] LT'; - case 6: - return '[v sobotu o] LT'; - } - }, - lastDay: '[včera o] LT', - lastWeek: function () { - switch (this.day()) { - case 0: - return '[minulú nedeľu o] LT'; - case 1: - case 2: - return '[minulý] dddd [o] LT'; - case 3: - return '[minulú stredu o] LT'; - case 4: - case 5: - return '[minulý] dddd [o] LT'; - case 6: - return '[minulú sobotu o] LT'; - } - }, - sameElse: 'L' - }, - relativeTime : { - future : 'za %s', - past : 'pred %s', - s : translate, - ss : translate, - m : translate, - mm : translate, - h : translate, - hh : translate, - d : translate, - dd : translate, - M : translate, - MM : translate, - y : translate, - yy : translate - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + this.closed = true; + var subject = this.subject; + var observers = subject.observers; + this.subject = null; + if (!observers || observers.length === 0 || subject.isStopped || subject.closed) { + return; } - }); - - return sk; + var subscriberIndex = observers.indexOf(this.subscriber); + if (subscriberIndex !== -1) { + observers.splice(subscriberIndex, 1); + } + }; + return SubjectSubscription; +}(_Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"])); -}))); +//# sourceMappingURL=SubjectSubscription.js.map /***/ }), -/* 140 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js locale configuration +/* 161 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "refCount", function() { return refCount; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ - function processRelativeTime(number, withoutSuffix, key, isFuture) { - var result = number + ' '; - switch (key) { - case 's': - return withoutSuffix || isFuture ? 'nekaj sekund' : 'nekaj sekundami'; - case 'ss': - if (number === 1) { - result += withoutSuffix ? 'sekundo' : 'sekundi'; - } else if (number === 2) { - result += withoutSuffix || isFuture ? 'sekundi' : 'sekundah'; - } else if (number < 5) { - result += withoutSuffix || isFuture ? 'sekunde' : 'sekundah'; - } else { - result += 'sekund'; - } - return result; - case 'm': - return withoutSuffix ? 'ena minuta' : 'eno minuto'; - case 'mm': - if (number === 1) { - result += withoutSuffix ? 'minuta' : 'minuto'; - } else if (number === 2) { - result += withoutSuffix || isFuture ? 'minuti' : 'minutama'; - } else if (number < 5) { - result += withoutSuffix || isFuture ? 'minute' : 'minutami'; - } else { - result += withoutSuffix || isFuture ? 'minut' : 'minutami'; - } - return result; - case 'h': - return withoutSuffix ? 'ena ura' : 'eno uro'; - case 'hh': - if (number === 1) { - result += withoutSuffix ? 'ura' : 'uro'; - } else if (number === 2) { - result += withoutSuffix || isFuture ? 'uri' : 'urama'; - } else if (number < 5) { - result += withoutSuffix || isFuture ? 'ure' : 'urami'; - } else { - result += withoutSuffix || isFuture ? 'ur' : 'urami'; - } - return result; - case 'd': - return withoutSuffix || isFuture ? 'en dan' : 'enim dnem'; - case 'dd': - if (number === 1) { - result += withoutSuffix || isFuture ? 'dan' : 'dnem'; - } else if (number === 2) { - result += withoutSuffix || isFuture ? 'dni' : 'dnevoma'; - } else { - result += withoutSuffix || isFuture ? 'dni' : 'dnevi'; - } - return result; - case 'M': - return withoutSuffix || isFuture ? 'en mesec' : 'enim mesecem'; - case 'MM': - if (number === 1) { - result += withoutSuffix || isFuture ? 'mesec' : 'mesecem'; - } else if (number === 2) { - result += withoutSuffix || isFuture ? 'meseca' : 'mesecema'; - } else if (number < 5) { - result += withoutSuffix || isFuture ? 'mesece' : 'meseci'; - } else { - result += withoutSuffix || isFuture ? 'mesecev' : 'meseci'; - } - return result; - case 'y': - return withoutSuffix || isFuture ? 'eno leto' : 'enim letom'; - case 'yy': - if (number === 1) { - result += withoutSuffix || isFuture ? 'leto' : 'letom'; - } else if (number === 2) { - result += withoutSuffix || isFuture ? 'leti' : 'letoma'; - } else if (number < 5) { - result += withoutSuffix || isFuture ? 'leta' : 'leti'; - } else { - result += withoutSuffix || isFuture ? 'let' : 'leti'; - } - return result; +function refCount() { + return function refCountOperatorFunction(source) { + return source.lift(new RefCountOperator(source)); + }; +} +var RefCountOperator = /*@__PURE__*/ (function () { + function RefCountOperator(connectable) { + this.connectable = connectable; + } + RefCountOperator.prototype.call = function (subscriber, source) { + var connectable = this.connectable; + connectable._refCount++; + var refCounter = new RefCountSubscriber(subscriber, connectable); + var subscription = source.subscribe(refCounter); + if (!refCounter.closed) { + refCounter.connection = connectable.connect(); } + return subscription; + }; + return RefCountOperator; +}()); +var RefCountSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RefCountSubscriber, _super); + function RefCountSubscriber(destination, connectable) { + var _this = _super.call(this, destination) || this; + _this.connectable = connectable; + return _this; } + RefCountSubscriber.prototype._unsubscribe = function () { + var connectable = this.connectable; + if (!connectable) { + this.connection = null; + return; + } + this.connectable = null; + var refCount = connectable._refCount; + if (refCount <= 0) { + this.connection = null; + return; + } + connectable._refCount = refCount - 1; + if (refCount > 1) { + this.connection = null; + return; + } + var connection = this.connection; + var sharedConnection = connectable._connection; + this.connection = null; + if (sharedConnection && (!connection || sharedConnection === connection)) { + sharedConnection.unsubscribe(); + } + }; + return RefCountSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=refCount.js.map - var sl = moment.defineLocale('sl', { - months : 'januar_februar_marec_april_maj_junij_julij_avgust_september_oktober_november_december'.split('_'), - monthsShort : 'jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.'.split('_'), - monthsParseExact: true, - weekdays : 'nedelja_ponedeljek_torek_sreda_četrtek_petek_sobota'.split('_'), - weekdaysShort : 'ned._pon._tor._sre._čet._pet._sob.'.split('_'), - weekdaysMin : 'ne_po_to_sr_če_pe_so'.split('_'), - weekdaysParseExact : true, - longDateFormat : { - LT : 'H:mm', - LTS : 'H:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D. MMMM YYYY', - LLL : 'D. MMMM YYYY H:mm', - LLLL : 'dddd, D. MMMM YYYY H:mm' - }, - calendar : { - sameDay : '[danes ob] LT', - nextDay : '[jutri ob] LT', - nextWeek : function () { - switch (this.day()) { - case 0: - return '[v] [nedeljo] [ob] LT'; - case 3: - return '[v] [sredo] [ob] LT'; - case 6: - return '[v] [soboto] [ob] LT'; - case 1: - case 2: - case 4: - case 5: - return '[v] dddd [ob] LT'; - } - }, - lastDay : '[včeraj ob] LT', - lastWeek : function () { - switch (this.day()) { - case 0: - return '[prejšnjo] [nedeljo] [ob] LT'; - case 3: - return '[prejšnjo] [sredo] [ob] LT'; - case 6: - return '[prejšnjo] [soboto] [ob] LT'; - case 1: - case 2: - case 4: - case 5: - return '[prejšnji] dddd [ob] LT'; - } - }, - sameElse : 'L' - }, - relativeTime : { - future : 'čez %s', - past : 'pred %s', - s : processRelativeTime, - ss : processRelativeTime, - m : processRelativeTime, - mm : processRelativeTime, - h : processRelativeTime, - hh : processRelativeTime, - d : processRelativeTime, - dd : processRelativeTime, - M : processRelativeTime, - MM : processRelativeTime, - y : processRelativeTime, - yy : processRelativeTime - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', - week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. - } - }); - - return sl; - -}))); +/***/ }), +/* 162 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "groupBy", function() { return groupBy; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GroupedObservable", function() { return GroupedObservable; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(148); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(141); +/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(158); +/** PURE_IMPORTS_START tslib,_Subscriber,_Subscription,_Observable,_Subject PURE_IMPORTS_END */ -/***/ }), -/* 141 */ -/***/ (function(module, exports, __webpack_require__) { -//! moment.js locale configuration -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - var sq = moment.defineLocale('sq', { - months : 'Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor'.split('_'), - monthsShort : 'Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj'.split('_'), - weekdays : 'E Diel_E Hënë_E Martë_E Mërkurë_E Enjte_E Premte_E Shtunë'.split('_'), - weekdaysShort : 'Die_Hën_Mar_Mër_Enj_Pre_Sht'.split('_'), - weekdaysMin : 'D_H_Ma_Më_E_P_Sh'.split('_'), - weekdaysParseExact : true, - meridiemParse: /PD|MD/, - isPM: function (input) { - return input.charAt(0) === 'M'; - }, - meridiem : function (hours, minutes, isLower) { - return hours < 12 ? 'PD' : 'MD'; - }, - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd, D MMMM YYYY HH:mm' - }, - calendar : { - sameDay : '[Sot në] LT', - nextDay : '[Nesër në] LT', - nextWeek : 'dddd [në] LT', - lastDay : '[Dje në] LT', - lastWeek : 'dddd [e kaluar në] LT', - sameElse : 'L' - }, - relativeTime : { - future : 'në %s', - past : '%s më parë', - s : 'disa sekonda', - ss : '%d sekonda', - m : 'një minutë', - mm : '%d minuta', - h : 'një orë', - hh : '%d orë', - d : 'një ditë', - dd : '%d ditë', - M : 'një muaj', - MM : '%d muaj', - y : 'një vit', - yy : '%d vite' - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. +function groupBy(keySelector, elementSelector, durationSelector, subjectSelector) { + return function (source) { + return source.lift(new GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector)); + }; +} +var GroupByOperator = /*@__PURE__*/ (function () { + function GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector) { + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.durationSelector = durationSelector; + this.subjectSelector = subjectSelector; + } + GroupByOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new GroupBySubscriber(subscriber, this.keySelector, this.elementSelector, this.durationSelector, this.subjectSelector)); + }; + return GroupByOperator; +}()); +var GroupBySubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GroupBySubscriber, _super); + function GroupBySubscriber(destination, keySelector, elementSelector, durationSelector, subjectSelector) { + var _this = _super.call(this, destination) || this; + _this.keySelector = keySelector; + _this.elementSelector = elementSelector; + _this.durationSelector = durationSelector; + _this.subjectSelector = subjectSelector; + _this.groups = null; + _this.attemptedToUnsubscribe = false; + _this.count = 0; + return _this; + } + GroupBySubscriber.prototype._next = function (value) { + var key; + try { + key = this.keySelector(value); } - }); - - return sq; + catch (err) { + this.error(err); + return; + } + this._group(value, key); + }; + GroupBySubscriber.prototype._group = function (value, key) { + var groups = this.groups; + if (!groups) { + groups = this.groups = new Map(); + } + var group = groups.get(key); + var element; + if (this.elementSelector) { + try { + element = this.elementSelector(value); + } + catch (err) { + this.error(err); + } + } + else { + element = value; + } + if (!group) { + group = (this.subjectSelector ? this.subjectSelector() : new _Subject__WEBPACK_IMPORTED_MODULE_4__["Subject"]()); + groups.set(key, group); + var groupedObservable = new GroupedObservable(key, group, this); + this.destination.next(groupedObservable); + if (this.durationSelector) { + var duration = void 0; + try { + duration = this.durationSelector(new GroupedObservable(key, group)); + } + catch (err) { + this.error(err); + return; + } + this.add(duration.subscribe(new GroupDurationSubscriber(key, group, this))); + } + } + if (!group.closed) { + group.next(element); + } + }; + GroupBySubscriber.prototype._error = function (err) { + var groups = this.groups; + if (groups) { + groups.forEach(function (group, key) { + group.error(err); + }); + groups.clear(); + } + this.destination.error(err); + }; + GroupBySubscriber.prototype._complete = function () { + var groups = this.groups; + if (groups) { + groups.forEach(function (group, key) { + group.complete(); + }); + groups.clear(); + } + this.destination.complete(); + }; + GroupBySubscriber.prototype.removeGroup = function (key) { + this.groups.delete(key); + }; + GroupBySubscriber.prototype.unsubscribe = function () { + if (!this.closed) { + this.attemptedToUnsubscribe = true; + if (this.count === 0) { + _super.prototype.unsubscribe.call(this); + } + } + }; + return GroupBySubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +var GroupDurationSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GroupDurationSubscriber, _super); + function GroupDurationSubscriber(key, group, parent) { + var _this = _super.call(this, group) || this; + _this.key = key; + _this.group = group; + _this.parent = parent; + return _this; + } + GroupDurationSubscriber.prototype._next = function (value) { + this.complete(); + }; + GroupDurationSubscriber.prototype._unsubscribe = function () { + var _a = this, parent = _a.parent, key = _a.key; + this.key = this.parent = null; + if (parent) { + parent.removeGroup(key); + } + }; + return GroupDurationSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +var GroupedObservable = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GroupedObservable, _super); + function GroupedObservable(key, groupSubject, refCountSubscription) { + var _this = _super.call(this) || this; + _this.key = key; + _this.groupSubject = groupSubject; + _this.refCountSubscription = refCountSubscription; + return _this; + } + GroupedObservable.prototype._subscribe = function (subscriber) { + var subscription = new _Subscription__WEBPACK_IMPORTED_MODULE_2__["Subscription"](); + var _a = this, refCountSubscription = _a.refCountSubscription, groupSubject = _a.groupSubject; + if (refCountSubscription && !refCountSubscription.closed) { + subscription.add(new InnerRefCountSubscription(refCountSubscription)); + } + subscription.add(groupSubject.subscribe(subscriber)); + return subscription; + }; + return GroupedObservable; +}(_Observable__WEBPACK_IMPORTED_MODULE_3__["Observable"])); -}))); +var InnerRefCountSubscription = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](InnerRefCountSubscription, _super); + function InnerRefCountSubscription(parent) { + var _this = _super.call(this) || this; + _this.parent = parent; + parent.count++; + return _this; + } + InnerRefCountSubscription.prototype.unsubscribe = function () { + var parent = this.parent; + if (!parent.closed && !this.closed) { + _super.prototype.unsubscribe.call(this); + parent.count -= 1; + if (parent.count === 0 && parent.attemptedToUnsubscribe) { + parent.unsubscribe(); + } + } + }; + return InnerRefCountSubscription; +}(_Subscription__WEBPACK_IMPORTED_MODULE_2__["Subscription"])); +//# sourceMappingURL=groupBy.js.map /***/ }), -/* 142 */ -/***/ (function(module, exports, __webpack_require__) { +/* 163 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -//! moment.js locale configuration +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BehaviorSubject", function() { return BehaviorSubject; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(158); +/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(159); +/** PURE_IMPORTS_START tslib,_Subject,_util_ObjectUnsubscribedError PURE_IMPORTS_END */ -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - var translator = { - words: { //Different grammatical cases - ss: ['sekunda', 'sekunde', 'sekundi'], - m: ['jedan minut', 'jedne minute'], - mm: ['minut', 'minute', 'minuta'], - h: ['jedan sat', 'jednog sata'], - hh: ['sat', 'sata', 'sati'], - dd: ['dan', 'dana', 'dana'], - MM: ['mesec', 'meseca', 'meseci'], - yy: ['godina', 'godine', 'godina'] - }, - correctGrammaticalCase: function (number, wordKey) { - return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]); +var BehaviorSubject = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BehaviorSubject, _super); + function BehaviorSubject(_value) { + var _this = _super.call(this) || this; + _this._value = _value; + return _this; + } + Object.defineProperty(BehaviorSubject.prototype, "value", { + get: function () { + return this.getValue(); }, - translate: function (number, withoutSuffix, key) { - var wordKey = translator.words[key]; - if (key.length === 1) { - return withoutSuffix ? wordKey[0] : wordKey[1]; - } else { - return number + ' ' + translator.correctGrammaticalCase(number, wordKey); - } + enumerable: true, + configurable: true + }); + BehaviorSubject.prototype._subscribe = function (subscriber) { + var subscription = _super.prototype._subscribe.call(this, subscriber); + if (subscription && !subscription.closed) { + subscriber.next(this._value); } + return subscription; }; - - var sr = moment.defineLocale('sr', { - months: 'januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar'.split('_'), - monthsShort: 'jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.'.split('_'), - monthsParseExact: true, - weekdays: 'nedelja_ponedeljak_utorak_sreda_četvrtak_petak_subota'.split('_'), - weekdaysShort: 'ned._pon._uto._sre._čet._pet._sub.'.split('_'), - weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'), - weekdaysParseExact : true, - longDateFormat: { - LT: 'H:mm', - LTS : 'H:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY H:mm', - LLLL: 'dddd, D. MMMM YYYY H:mm' - }, - calendar: { - sameDay: '[danas u] LT', - nextDay: '[sutra u] LT', - nextWeek: function () { - switch (this.day()) { - case 0: - return '[u] [nedelju] [u] LT'; - case 3: - return '[u] [sredu] [u] LT'; - case 6: - return '[u] [subotu] [u] LT'; - case 1: - case 2: - case 4: - case 5: - return '[u] dddd [u] LT'; - } - }, - lastDay : '[juče u] LT', - lastWeek : function () { - var lastWeekDays = [ - '[prošle] [nedelje] [u] LT', - '[prošlog] [ponedeljka] [u] LT', - '[prošlog] [utorka] [u] LT', - '[prošle] [srede] [u] LT', - '[prošlog] [četvrtka] [u] LT', - '[prošlog] [petka] [u] LT', - '[prošle] [subote] [u] LT' - ]; - return lastWeekDays[this.day()]; - }, - sameElse : 'L' - }, - relativeTime : { - future : 'za %s', - past : 'pre %s', - s : 'nekoliko sekundi', - ss : translator.translate, - m : translator.translate, - mm : translator.translate, - h : translator.translate, - hh : translator.translate, - d : 'dan', - dd : translator.translate, - M : 'mesec', - MM : translator.translate, - y : 'godinu', - yy : translator.translate - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', - week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. + BehaviorSubject.prototype.getValue = function () { + if (this.hasError) { + throw this.thrownError; } - }); - - return sr; + else if (this.closed) { + throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_2__["ObjectUnsubscribedError"](); + } + else { + return this._value; + } + }; + BehaviorSubject.prototype.next = function (value) { + _super.prototype.next.call(this, this._value = value); + }; + return BehaviorSubject; +}(_Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"])); -}))); +//# sourceMappingURL=BehaviorSubject.js.map /***/ }), -/* 143 */ -/***/ (function(module, exports, __webpack_require__) { +/* 164 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -//! moment.js locale configuration +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReplaySubject", function() { return ReplaySubject; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(158); +/* harmony import */ var _scheduler_queue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(165); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(148); +/* harmony import */ var _operators_observeOn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(172); +/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(159); +/* harmony import */ var _SubjectSubscription__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(160); +/** PURE_IMPORTS_START tslib,_Subject,_scheduler_queue,_Subscription,_operators_observeOn,_util_ObjectUnsubscribedError,_SubjectSubscription PURE_IMPORTS_END */ -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - var translator = { - words: { //Different grammatical cases - ss: ['секунда', 'секунде', 'секунди'], - m: ['један минут', 'једне минуте'], - mm: ['минут', 'минуте', 'минута'], - h: ['један сат', 'једног сата'], - hh: ['сат', 'сата', 'сати'], - dd: ['дан', 'дана', 'дана'], - MM: ['месец', 'месеца', 'месеци'], - yy: ['година', 'године', 'година'] - }, - correctGrammaticalCase: function (number, wordKey) { - return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]); - }, - translate: function (number, withoutSuffix, key) { - var wordKey = translator.words[key]; - if (key.length === 1) { - return withoutSuffix ? wordKey[0] : wordKey[1]; - } else { - return number + ' ' + translator.correctGrammaticalCase(number, wordKey); - } + + + + +var ReplaySubject = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ReplaySubject, _super); + function ReplaySubject(bufferSize, windowTime, scheduler) { + if (bufferSize === void 0) { + bufferSize = Number.POSITIVE_INFINITY; + } + if (windowTime === void 0) { + windowTime = Number.POSITIVE_INFINITY; + } + var _this = _super.call(this) || this; + _this.scheduler = scheduler; + _this._events = []; + _this._infiniteTimeWindow = false; + _this._bufferSize = bufferSize < 1 ? 1 : bufferSize; + _this._windowTime = windowTime < 1 ? 1 : windowTime; + if (windowTime === Number.POSITIVE_INFINITY) { + _this._infiniteTimeWindow = true; + _this.next = _this.nextInfiniteTimeWindow; + } + else { + _this.next = _this.nextTimeWindow; + } + return _this; + } + ReplaySubject.prototype.nextInfiniteTimeWindow = function (value) { + var _events = this._events; + _events.push(value); + if (_events.length > this._bufferSize) { + _events.shift(); } + _super.prototype.next.call(this, value); }; - - var srCyrl = moment.defineLocale('sr-cyrl', { - months: 'јануар_фебруар_март_април_мај_јун_јул_август_септембар_октобар_новембар_децембар'.split('_'), - monthsShort: 'јан._феб._мар._апр._мај_јун_јул_авг._сеп._окт._нов._дец.'.split('_'), - monthsParseExact: true, - weekdays: 'недеља_понедељак_уторак_среда_четвртак_петак_субота'.split('_'), - weekdaysShort: 'нед._пон._уто._сре._чет._пет._суб.'.split('_'), - weekdaysMin: 'не_по_ут_ср_че_пе_су'.split('_'), - weekdaysParseExact : true, - longDateFormat: { - LT: 'H:mm', - LTS : 'H:mm:ss', - L: 'DD.MM.YYYY', - LL: 'D. MMMM YYYY', - LLL: 'D. MMMM YYYY H:mm', - LLLL: 'dddd, D. MMMM YYYY H:mm' - }, - calendar: { - sameDay: '[данас у] LT', - nextDay: '[сутра у] LT', - nextWeek: function () { - switch (this.day()) { - case 0: - return '[у] [недељу] [у] LT'; - case 3: - return '[у] [среду] [у] LT'; - case 6: - return '[у] [суботу] [у] LT'; - case 1: - case 2: - case 4: - case 5: - return '[у] dddd [у] LT'; - } - }, - lastDay : '[јуче у] LT', - lastWeek : function () { - var lastWeekDays = [ - '[прошле] [недеље] [у] LT', - '[прошлог] [понедељка] [у] LT', - '[прошлог] [уторка] [у] LT', - '[прошле] [среде] [у] LT', - '[прошлог] [четвртка] [у] LT', - '[прошлог] [петка] [у] LT', - '[прошле] [суботе] [у] LT' - ]; - return lastWeekDays[this.day()]; - }, - sameElse : 'L' - }, - relativeTime : { - future : 'за %s', - past : 'пре %s', - s : 'неколико секунди', - ss : translator.translate, - m : translator.translate, - mm : translator.translate, - h : translator.translate, - hh : translator.translate, - d : 'дан', - dd : translator.translate, - M : 'месец', - MM : translator.translate, - y : 'годину', - yy : translator.translate - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', - week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. + ReplaySubject.prototype.nextTimeWindow = function (value) { + this._events.push(new ReplayEvent(this._getNow(), value)); + this._trimBufferThenGetEvents(); + _super.prototype.next.call(this, value); + }; + ReplaySubject.prototype._subscribe = function (subscriber) { + var _infiniteTimeWindow = this._infiniteTimeWindow; + var _events = _infiniteTimeWindow ? this._events : this._trimBufferThenGetEvents(); + var scheduler = this.scheduler; + var len = _events.length; + var subscription; + if (this.closed) { + throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_5__["ObjectUnsubscribedError"](); } - }); - - return srCyrl; + else if (this.isStopped || this.hasError) { + subscription = _Subscription__WEBPACK_IMPORTED_MODULE_3__["Subscription"].EMPTY; + } + else { + this.observers.push(subscriber); + subscription = new _SubjectSubscription__WEBPACK_IMPORTED_MODULE_6__["SubjectSubscription"](this, subscriber); + } + if (scheduler) { + subscriber.add(subscriber = new _operators_observeOn__WEBPACK_IMPORTED_MODULE_4__["ObserveOnSubscriber"](subscriber, scheduler)); + } + if (_infiniteTimeWindow) { + for (var i = 0; i < len && !subscriber.closed; i++) { + subscriber.next(_events[i]); + } + } + else { + for (var i = 0; i < len && !subscriber.closed; i++) { + subscriber.next(_events[i].value); + } + } + if (this.hasError) { + subscriber.error(this.thrownError); + } + else if (this.isStopped) { + subscriber.complete(); + } + return subscription; + }; + ReplaySubject.prototype._getNow = function () { + return (this.scheduler || _scheduler_queue__WEBPACK_IMPORTED_MODULE_2__["queue"]).now(); + }; + ReplaySubject.prototype._trimBufferThenGetEvents = function () { + var now = this._getNow(); + var _bufferSize = this._bufferSize; + var _windowTime = this._windowTime; + var _events = this._events; + var eventsCount = _events.length; + var spliceCount = 0; + while (spliceCount < eventsCount) { + if ((now - _events[spliceCount].time) < _windowTime) { + break; + } + spliceCount++; + } + if (eventsCount > _bufferSize) { + spliceCount = Math.max(spliceCount, eventsCount - _bufferSize); + } + if (spliceCount > 0) { + _events.splice(0, spliceCount); + } + return _events; + }; + return ReplaySubject; +}(_Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"])); -}))); +var ReplayEvent = /*@__PURE__*/ (function () { + function ReplayEvent(time, value) { + this.time = time; + this.value = value; + } + return ReplayEvent; +}()); +//# sourceMappingURL=ReplaySubject.js.map /***/ }), -/* 144 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js locale configuration - -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - +/* 165 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - var ss = moment.defineLocale('ss', { - months : "Bhimbidvwane_Indlovana_Indlov'lenkhulu_Mabasa_Inkhwekhweti_Inhlaba_Kholwane_Ingci_Inyoni_Imphala_Lweti_Ingongoni".split('_'), - monthsShort : 'Bhi_Ina_Inu_Mab_Ink_Inh_Kho_Igc_Iny_Imp_Lwe_Igo'.split('_'), - weekdays : 'Lisontfo_Umsombuluko_Lesibili_Lesitsatfu_Lesine_Lesihlanu_Umgcibelo'.split('_'), - weekdaysShort : 'Lis_Umb_Lsb_Les_Lsi_Lsh_Umg'.split('_'), - weekdaysMin : 'Li_Us_Lb_Lt_Ls_Lh_Ug'.split('_'), - weekdaysParseExact : true, - longDateFormat : { - LT : 'h:mm A', - LTS : 'h:mm:ss A', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY h:mm A', - LLLL : 'dddd, D MMMM YYYY h:mm A' - }, - calendar : { - sameDay : '[Namuhla nga] LT', - nextDay : '[Kusasa nga] LT', - nextWeek : 'dddd [nga] LT', - lastDay : '[Itolo nga] LT', - lastWeek : 'dddd [leliphelile] [nga] LT', - sameElse : 'L' - }, - relativeTime : { - future : 'nga %s', - past : 'wenteka nga %s', - s : 'emizuzwana lomcane', - ss : '%d mzuzwana', - m : 'umzuzu', - mm : '%d emizuzu', - h : 'lihora', - hh : '%d emahora', - d : 'lilanga', - dd : '%d emalanga', - M : 'inyanga', - MM : '%d tinyanga', - y : 'umnyaka', - yy : '%d iminyaka' - }, - meridiemParse: /ekuseni|emini|entsambama|ebusuku/, - meridiem : function (hours, minutes, isLower) { - if (hours < 11) { - return 'ekuseni'; - } else if (hours < 15) { - return 'emini'; - } else if (hours < 19) { - return 'entsambama'; - } else { - return 'ebusuku'; - } - }, - meridiemHour : function (hour, meridiem) { - if (hour === 12) { - hour = 0; - } - if (meridiem === 'ekuseni') { - return hour; - } else if (meridiem === 'emini') { - return hour >= 11 ? hour : hour + 12; - } else if (meridiem === 'entsambama' || meridiem === 'ebusuku') { - if (hour === 0) { - return 0; - } - return hour + 12; - } - }, - dayOfMonthOrdinalParse: /\d{1,2}/, - ordinal : '%d', - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. - } - }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "queue", function() { return queue; }); +/* harmony import */ var _QueueAction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(166); +/* harmony import */ var _QueueScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(169); +/** PURE_IMPORTS_START _QueueAction,_QueueScheduler PURE_IMPORTS_END */ - return ss; -}))); +var queue = /*@__PURE__*/ new _QueueScheduler__WEBPACK_IMPORTED_MODULE_1__["QueueScheduler"](_QueueAction__WEBPACK_IMPORTED_MODULE_0__["QueueAction"]); +//# sourceMappingURL=queue.js.map /***/ }), -/* 145 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js locale configuration +/* 166 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QueueAction", function() { return QueueAction; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(167); +/** PURE_IMPORTS_START tslib,_AsyncAction PURE_IMPORTS_END */ - var sv = moment.defineLocale('sv', { - months : 'januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december'.split('_'), - monthsShort : 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'), - weekdays : 'söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag'.split('_'), - weekdaysShort : 'sön_mån_tis_ons_tor_fre_lör'.split('_'), - weekdaysMin : 'sö_må_ti_on_to_fr_lö'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'YYYY-MM-DD', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY [kl.] HH:mm', - LLLL : 'dddd D MMMM YYYY [kl.] HH:mm', - lll : 'D MMM YYYY HH:mm', - llll : 'ddd D MMM YYYY HH:mm' - }, - calendar : { - sameDay: '[Idag] LT', - nextDay: '[Imorgon] LT', - lastDay: '[Igår] LT', - nextWeek: '[På] dddd LT', - lastWeek: '[I] dddd[s] LT', - sameElse: 'L' - }, - relativeTime : { - future : 'om %s', - past : 'för %s sedan', - s : 'några sekunder', - ss : '%d sekunder', - m : 'en minut', - mm : '%d minuter', - h : 'en timme', - hh : '%d timmar', - d : 'en dag', - dd : '%d dagar', - M : 'en månad', - MM : '%d månader', - y : 'ett år', - yy : '%d år' - }, - dayOfMonthOrdinalParse: /\d{1,2}(e|a)/, - ordinal : function (number) { - var b = number % 10, - output = (~~(number % 100 / 10) === 1) ? 'e' : - (b === 1) ? 'a' : - (b === 2) ? 'a' : - (b === 3) ? 'e' : 'e'; - return number + output; - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. +var QueueAction = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](QueueAction, _super); + function QueueAction(scheduler, work) { + var _this = _super.call(this, scheduler, work) || this; + _this.scheduler = scheduler; + _this.work = work; + return _this; + } + QueueAction.prototype.schedule = function (state, delay) { + if (delay === void 0) { + delay = 0; } - }); - - return sv; + if (delay > 0) { + return _super.prototype.schedule.call(this, state, delay); + } + this.delay = delay; + this.state = state; + this.scheduler.flush(this); + return this; + }; + QueueAction.prototype.execute = function (state, delay) { + return (delay > 0 || this.closed) ? + _super.prototype.execute.call(this, state, delay) : + this._execute(state, delay); + }; + QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { + delay = 0; + } + if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) { + return _super.prototype.requestAsyncId.call(this, scheduler, id, delay); + } + return scheduler.flush(this); + }; + return QueueAction; +}(_AsyncAction__WEBPACK_IMPORTED_MODULE_1__["AsyncAction"])); -}))); +//# sourceMappingURL=QueueAction.js.map /***/ }), -/* 146 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js locale configuration +/* 167 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AsyncAction", function() { return AsyncAction; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Action__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(168); +/** PURE_IMPORTS_START tslib,_Action PURE_IMPORTS_END */ - var sw = moment.defineLocale('sw', { - months : 'Januari_Februari_Machi_Aprili_Mei_Juni_Julai_Agosti_Septemba_Oktoba_Novemba_Desemba'.split('_'), - monthsShort : 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ago_Sep_Okt_Nov_Des'.split('_'), - weekdays : 'Jumapili_Jumatatu_Jumanne_Jumatano_Alhamisi_Ijumaa_Jumamosi'.split('_'), - weekdaysShort : 'Jpl_Jtat_Jnne_Jtan_Alh_Ijm_Jmos'.split('_'), - weekdaysMin : 'J2_J3_J4_J5_Al_Ij_J1'.split('_'), - weekdaysParseExact : true, - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd, D MMMM YYYY HH:mm' - }, - calendar : { - sameDay : '[leo saa] LT', - nextDay : '[kesho saa] LT', - nextWeek : '[wiki ijayo] dddd [saat] LT', - lastDay : '[jana] LT', - lastWeek : '[wiki iliyopita] dddd [saat] LT', - sameElse : 'L' - }, - relativeTime : { - future : '%s baadaye', - past : 'tokea %s', - s : 'hivi punde', - ss : 'sekunde %d', - m : 'dakika moja', - mm : 'dakika %d', - h : 'saa limoja', - hh : 'masaa %d', - d : 'siku moja', - dd : 'masiku %d', - M : 'mwezi mmoja', - MM : 'miezi %d', - y : 'mwaka mmoja', - yy : 'miaka %d' - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. +var AsyncAction = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AsyncAction, _super); + function AsyncAction(scheduler, work) { + var _this = _super.call(this, scheduler, work) || this; + _this.scheduler = scheduler; + _this.work = work; + _this.pending = false; + return _this; + } + AsyncAction.prototype.schedule = function (state, delay) { + if (delay === void 0) { + delay = 0; } - }); - - return sw; + if (this.closed) { + return this; + } + this.state = state; + var id = this.id; + var scheduler = this.scheduler; + if (id != null) { + this.id = this.recycleAsyncId(scheduler, id, delay); + } + this.pending = true; + this.delay = delay; + this.id = this.id || this.requestAsyncId(scheduler, this.id, delay); + return this; + }; + AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { + delay = 0; + } + return setInterval(scheduler.flush.bind(scheduler, this), delay); + }; + AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { + delay = 0; + } + if (delay !== null && this.delay === delay && this.pending === false) { + return id; + } + clearInterval(id); + return undefined; + }; + AsyncAction.prototype.execute = function (state, delay) { + if (this.closed) { + return new Error('executing a cancelled action'); + } + this.pending = false; + var error = this._execute(state, delay); + if (error) { + return error; + } + else if (this.pending === false && this.id != null) { + this.id = this.recycleAsyncId(this.scheduler, this.id, null); + } + }; + AsyncAction.prototype._execute = function (state, delay) { + var errored = false; + var errorValue = undefined; + try { + this.work(state); + } + catch (e) { + errored = true; + errorValue = !!e && e || new Error(e); + } + if (errored) { + this.unsubscribe(); + return errorValue; + } + }; + AsyncAction.prototype._unsubscribe = function () { + var id = this.id; + var scheduler = this.scheduler; + var actions = scheduler.actions; + var index = actions.indexOf(this); + this.work = null; + this.state = null; + this.pending = false; + this.scheduler = null; + if (index !== -1) { + actions.splice(index, 1); + } + if (id != null) { + this.id = this.recycleAsyncId(scheduler, id, null); + } + this.delay = null; + }; + return AsyncAction; +}(_Action__WEBPACK_IMPORTED_MODULE_1__["Action"])); -}))); +//# sourceMappingURL=AsyncAction.js.map /***/ }), -/* 147 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js locale configuration +/* 168 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Action", function() { return Action; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(148); +/** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */ - var symbolMap = { - '1': '௧', - '2': '௨', - '3': '௩', - '4': '௪', - '5': '௫', - '6': '௬', - '7': '௭', - '8': '௮', - '9': '௯', - '0': '௦' - }, numberMap = { - '௧': '1', - '௨': '2', - '௩': '3', - '௪': '4', - '௫': '5', - '௬': '6', - '௭': '7', - '௮': '8', - '௯': '9', - '௦': '0' +var Action = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Action, _super); + function Action(scheduler, work) { + return _super.call(this) || this; + } + Action.prototype.schedule = function (state, delay) { + if (delay === void 0) { + delay = 0; + } + return this; }; + return Action; +}(_Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"])); - var ta = moment.defineLocale('ta', { - months : 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split('_'), - monthsShort : 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split('_'), - weekdays : 'ஞாயிற்றுக்கிழமை_திங்கட்கிழமை_செவ்வாய்கிழமை_புதன்கிழமை_வியாழக்கிழமை_வெள்ளிக்கிழமை_சனிக்கிழமை'.split('_'), - weekdaysShort : 'ஞாயிறு_திங்கள்_செவ்வாய்_புதன்_வியாழன்_வெள்ளி_சனி'.split('_'), - weekdaysMin : 'ஞா_தி_செ_பு_வி_வெ_ச'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY, HH:mm', - LLLL : 'dddd, D MMMM YYYY, HH:mm' - }, - calendar : { - sameDay : '[இன்று] LT', - nextDay : '[நாளை] LT', - nextWeek : 'dddd, LT', - lastDay : '[நேற்று] LT', - lastWeek : '[கடந்த வாரம்] dddd, LT', - sameElse : 'L' - }, - relativeTime : { - future : '%s இல்', - past : '%s முன்', - s : 'ஒரு சில விநாடிகள்', - ss : '%d விநாடிகள்', - m : 'ஒரு நிமிடம்', - mm : '%d நிமிடங்கள்', - h : 'ஒரு மணி நேரம்', - hh : '%d மணி நேரம்', - d : 'ஒரு நாள்', - dd : '%d நாட்கள்', - M : 'ஒரு மாதம்', - MM : '%d மாதங்கள்', - y : 'ஒரு வருடம்', - yy : '%d ஆண்டுகள்' - }, - dayOfMonthOrdinalParse: /\d{1,2}வது/, - ordinal : function (number) { - return number + 'வது'; - }, - preparse: function (string) { - return string.replace(/[௧௨௩௪௫௬௭௮௯௦]/g, function (match) { - return numberMap[match]; - }); - }, - postformat: function (string) { - return string.replace(/\d/g, function (match) { - return symbolMap[match]; - }); - }, - // refer http://ta.wikipedia.org/s/1er1 - meridiemParse: /யாமம்|வைகறை|காலை|நண்பகல்|எற்பாடு|மாலை/, - meridiem : function (hour, minute, isLower) { - if (hour < 2) { - return ' யாமம்'; - } else if (hour < 6) { - return ' வைகறை'; // வைகறை - } else if (hour < 10) { - return ' காலை'; // காலை - } else if (hour < 14) { - return ' நண்பகல்'; // நண்பகல் - } else if (hour < 18) { - return ' எற்பாடு'; // எற்பாடு - } else if (hour < 22) { - return ' மாலை'; // மாலை - } else { - return ' யாமம்'; - } - }, - meridiemHour : function (hour, meridiem) { - if (hour === 12) { - hour = 0; - } - if (meridiem === 'யாமம்') { - return hour < 2 ? hour : hour + 12; - } else if (meridiem === 'வைகறை' || meridiem === 'காலை') { - return hour; - } else if (meridiem === 'நண்பகல்') { - return hour >= 10 ? hour : hour + 12; - } else { - return hour + 12; - } - }, - week : { - dow : 0, // Sunday is the first day of the week. - doy : 6 // The week that contains Jan 6th is the first week of the year. - } - }); +//# sourceMappingURL=Action.js.map - return ta; -}))); +/***/ }), +/* 169 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QueueScheduler", function() { return QueueScheduler; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(170); +/** PURE_IMPORTS_START tslib,_AsyncScheduler PURE_IMPORTS_END */ -/***/ }), -/* 148 */ -/***/ (function(module, exports, __webpack_require__) { -//! moment.js locale configuration +var QueueScheduler = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](QueueScheduler, _super); + function QueueScheduler() { + return _super !== null && _super.apply(this, arguments) || this; + } + return QueueScheduler; +}(_AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__["AsyncScheduler"])); -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +//# sourceMappingURL=QueueScheduler.js.map - var te = moment.defineLocale('te', { - months : 'జనవరి_ఫిబ్రవరి_మార్చి_ఏప్రిల్_మే_జూన్_జులై_ఆగస్టు_సెప్టెంబర్_అక్టోబర్_నవంబర్_డిసెంబర్'.split('_'), - monthsShort : 'జన._ఫిబ్ర._మార్చి_ఏప్రి._మే_జూన్_జులై_ఆగ._సెప్._అక్టో._నవ._డిసె.'.split('_'), - monthsParseExact : true, - weekdays : 'ఆదివారం_సోమవారం_మంగళవారం_బుధవారం_గురువారం_శుక్రవారం_శనివారం'.split('_'), - weekdaysShort : 'ఆది_సోమ_మంగళ_బుధ_గురు_శుక్ర_శని'.split('_'), - weekdaysMin : 'ఆ_సో_మం_బు_గు_శు_శ'.split('_'), - longDateFormat : { - LT : 'A h:mm', - LTS : 'A h:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY, A h:mm', - LLLL : 'dddd, D MMMM YYYY, A h:mm' - }, - calendar : { - sameDay : '[నేడు] LT', - nextDay : '[రేపు] LT', - nextWeek : 'dddd, LT', - lastDay : '[నిన్న] LT', - lastWeek : '[గత] dddd, LT', - sameElse : 'L' - }, - relativeTime : { - future : '%s లో', - past : '%s క్రితం', - s : 'కొన్ని క్షణాలు', - ss : '%d సెకన్లు', - m : 'ఒక నిమిషం', - mm : '%d నిమిషాలు', - h : 'ఒక గంట', - hh : '%d గంటలు', - d : 'ఒక రోజు', - dd : '%d రోజులు', - M : 'ఒక నెల', - MM : '%d నెలలు', - y : 'ఒక సంవత్సరం', - yy : '%d సంవత్సరాలు' - }, - dayOfMonthOrdinalParse : /\d{1,2}వ/, - ordinal : '%dవ', - meridiemParse: /రాత్రి|ఉదయం|మధ్యాహ్నం|సాయంత్రం/, - meridiemHour : function (hour, meridiem) { - if (hour === 12) { - hour = 0; +/***/ }), +/* 170 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AsyncScheduler", function() { return AsyncScheduler; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Scheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(171); +/** PURE_IMPORTS_START tslib,_Scheduler PURE_IMPORTS_END */ + + +var AsyncScheduler = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AsyncScheduler, _super); + function AsyncScheduler(SchedulerAction, now) { + if (now === void 0) { + now = _Scheduler__WEBPACK_IMPORTED_MODULE_1__["Scheduler"].now; + } + var _this = _super.call(this, SchedulerAction, function () { + if (AsyncScheduler.delegate && AsyncScheduler.delegate !== _this) { + return AsyncScheduler.delegate.now(); } - if (meridiem === 'రాత్రి') { - return hour < 4 ? hour : hour + 12; - } else if (meridiem === 'ఉదయం') { - return hour; - } else if (meridiem === 'మధ్యాహ్నం') { - return hour >= 10 ? hour : hour + 12; - } else if (meridiem === 'సాయంత్రం') { - return hour + 12; + else { + return now(); } - }, - meridiem : function (hour, minute, isLower) { - if (hour < 4) { - return 'రాత్రి'; - } else if (hour < 10) { - return 'ఉదయం'; - } else if (hour < 17) { - return 'మధ్యాహ్నం'; - } else if (hour < 20) { - return 'సాయంత్రం'; - } else { - return 'రాత్రి'; + }) || this; + _this.actions = []; + _this.active = false; + _this.scheduled = undefined; + return _this; + } + AsyncScheduler.prototype.schedule = function (work, delay, state) { + if (delay === void 0) { + delay = 0; + } + if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) { + return AsyncScheduler.delegate.schedule(work, delay, state); + } + else { + return _super.prototype.schedule.call(this, work, delay, state); + } + }; + AsyncScheduler.prototype.flush = function (action) { + var actions = this.actions; + if (this.active) { + actions.push(action); + return; + } + var error; + this.active = true; + do { + if (error = action.execute(action.state, action.delay)) { + break; } - }, - week : { - dow : 0, // Sunday is the first day of the week. - doy : 6 // The week that contains Jan 6th is the first week of the year. + } while (action = actions.shift()); + this.active = false; + if (error) { + while (action = actions.shift()) { + action.unsubscribe(); + } + throw error; } - }); + }; + return AsyncScheduler; +}(_Scheduler__WEBPACK_IMPORTED_MODULE_1__["Scheduler"])); - return te; +//# sourceMappingURL=AsyncScheduler.js.map -}))); + +/***/ }), +/* 171 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Scheduler", function() { return Scheduler; }); +var Scheduler = /*@__PURE__*/ (function () { + function Scheduler(SchedulerAction, now) { + if (now === void 0) { + now = Scheduler.now; + } + this.SchedulerAction = SchedulerAction; + this.now = now; + } + Scheduler.prototype.schedule = function (work, delay, state) { + if (delay === void 0) { + delay = 0; + } + return new this.SchedulerAction(this, work).schedule(state, delay); + }; + Scheduler.now = function () { return Date.now(); }; + return Scheduler; +}()); + +//# sourceMappingURL=Scheduler.js.map /***/ }), -/* 149 */ -/***/ (function(module, exports, __webpack_require__) { +/* 172 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -//! moment.js locale configuration +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "observeOn", function() { return observeOn; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ObserveOnOperator", function() { return ObserveOnOperator; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ObserveOnSubscriber", function() { return ObserveOnSubscriber; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ObserveOnMessage", function() { return ObserveOnMessage; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/* harmony import */ var _Notification__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(173); +/** PURE_IMPORTS_START tslib,_Subscriber,_Notification PURE_IMPORTS_END */ -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - var tet = moment.defineLocale('tet', { - months : 'Janeiru_Fevereiru_Marsu_Abril_Maiu_Juñu_Jullu_Agustu_Setembru_Outubru_Novembru_Dezembru'.split('_'), - monthsShort : 'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'), - weekdays : 'Domingu_Segunda_Tersa_Kuarta_Kinta_Sesta_Sabadu'.split('_'), - weekdaysShort : 'Dom_Seg_Ters_Kua_Kint_Sest_Sab'.split('_'), - weekdaysMin : 'Do_Seg_Te_Ku_Ki_Ses_Sa'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd, D MMMM YYYY HH:mm' - }, - calendar : { - sameDay: '[Ohin iha] LT', - nextDay: '[Aban iha] LT', - nextWeek: 'dddd [iha] LT', - lastDay: '[Horiseik iha] LT', - lastWeek: 'dddd [semana kotuk] [iha] LT', - sameElse: 'L' - }, - relativeTime : { - future : 'iha %s', - past : '%s liuba', - s : 'minutu balun', - ss : 'minutu %d', - m : 'minutu ida', - mm : 'minutu %d', - h : 'oras ida', - hh : 'oras %d', - d : 'loron ida', - dd : 'loron %d', - M : 'fulan ida', - MM : 'fulan %d', - y : 'tinan ida', - yy : 'tinan %d' - }, - dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, - ordinal : function (number) { - var b = number % 10, - output = (~~(number % 100 / 10) === 1) ? 'th' : - (b === 1) ? 'st' : - (b === 2) ? 'nd' : - (b === 3) ? 'rd' : 'th'; - return number + output; - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. +function observeOn(scheduler, delay) { + if (delay === void 0) { + delay = 0; + } + return function observeOnOperatorFunction(source) { + return source.lift(new ObserveOnOperator(scheduler, delay)); + }; +} +var ObserveOnOperator = /*@__PURE__*/ (function () { + function ObserveOnOperator(scheduler, delay) { + if (delay === void 0) { + delay = 0; } - }); + this.scheduler = scheduler; + this.delay = delay; + } + ObserveOnOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay)); + }; + return ObserveOnOperator; +}()); - return tet; +var ObserveOnSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ObserveOnSubscriber, _super); + function ObserveOnSubscriber(destination, scheduler, delay) { + if (delay === void 0) { + delay = 0; + } + var _this = _super.call(this, destination) || this; + _this.scheduler = scheduler; + _this.delay = delay; + return _this; + } + ObserveOnSubscriber.dispatch = function (arg) { + var notification = arg.notification, destination = arg.destination; + notification.observe(destination); + this.unsubscribe(); + }; + ObserveOnSubscriber.prototype.scheduleMessage = function (notification) { + var destination = this.destination; + destination.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination))); + }; + ObserveOnSubscriber.prototype._next = function (value) { + this.scheduleMessage(_Notification__WEBPACK_IMPORTED_MODULE_2__["Notification"].createNext(value)); + }; + ObserveOnSubscriber.prototype._error = function (err) { + this.scheduleMessage(_Notification__WEBPACK_IMPORTED_MODULE_2__["Notification"].createError(err)); + this.unsubscribe(); + }; + ObserveOnSubscriber.prototype._complete = function () { + this.scheduleMessage(_Notification__WEBPACK_IMPORTED_MODULE_2__["Notification"].createComplete()); + this.unsubscribe(); + }; + return ObserveOnSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -}))); +var ObserveOnMessage = /*@__PURE__*/ (function () { + function ObserveOnMessage(notification, destination) { + this.notification = notification; + this.destination = destination; + } + return ObserveOnMessage; +}()); + +//# sourceMappingURL=observeOn.js.map /***/ }), -/* 150 */ -/***/ (function(module, exports, __webpack_require__) { +/* 173 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -//! moment.js locale configuration +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NotificationKind", function() { return NotificationKind; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Notification", function() { return Notification; }); +/* harmony import */ var _observable_empty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(174); +/* harmony import */ var _observable_of__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(175); +/* harmony import */ var _observable_throwError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(180); +/** PURE_IMPORTS_START _observable_empty,_observable_of,_observable_throwError PURE_IMPORTS_END */ -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - var suffixes = { - 0: '-ум', - 1: '-ум', - 2: '-юм', - 3: '-юм', - 4: '-ум', - 5: '-ум', - 6: '-ум', - 7: '-ум', - 8: '-ум', - 9: '-ум', - 10: '-ум', - 12: '-ум', - 13: '-ум', - 20: '-ум', - 30: '-юм', - 40: '-ум', - 50: '-ум', - 60: '-ум', - 70: '-ум', - 80: '-ум', - 90: '-ум', - 100: '-ум' +var NotificationKind; +/*@__PURE__*/ (function (NotificationKind) { + NotificationKind["NEXT"] = "N"; + NotificationKind["ERROR"] = "E"; + NotificationKind["COMPLETE"] = "C"; +})(NotificationKind || (NotificationKind = {})); +var Notification = /*@__PURE__*/ (function () { + function Notification(kind, value, error) { + this.kind = kind; + this.value = value; + this.error = error; + this.hasValue = kind === 'N'; + } + Notification.prototype.observe = function (observer) { + switch (this.kind) { + case 'N': + return observer.next && observer.next(this.value); + case 'E': + return observer.error && observer.error(this.error); + case 'C': + return observer.complete && observer.complete(); + } }; - - var tg = moment.defineLocale('tg', { - months : 'январ_феврал_март_апрел_май_июн_июл_август_сентябр_октябр_ноябр_декабр'.split('_'), - monthsShort : 'янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек'.split('_'), - weekdays : 'якшанбе_душанбе_сешанбе_чоршанбе_панҷшанбе_ҷумъа_шанбе'.split('_'), - weekdaysShort : 'яшб_дшб_сшб_чшб_пшб_ҷум_шнб'.split('_'), - weekdaysMin : 'яш_дш_сш_чш_пш_ҷм_шб'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd, D MMMM YYYY HH:mm' - }, - calendar : { - sameDay : '[Имрӯз соати] LT', - nextDay : '[Пагоҳ соати] LT', - lastDay : '[Дирӯз соати] LT', - nextWeek : 'dddd[и] [ҳафтаи оянда соати] LT', - lastWeek : 'dddd[и] [ҳафтаи гузашта соати] LT', - sameElse : 'L' - }, - relativeTime : { - future : 'баъди %s', - past : '%s пеш', - s : 'якчанд сония', - m : 'як дақиқа', - mm : '%d дақиқа', - h : 'як соат', - hh : '%d соат', - d : 'як рӯз', - dd : '%d рӯз', - M : 'як моҳ', - MM : '%d моҳ', - y : 'як сол', - yy : '%d сол' - }, - meridiemParse: /шаб|субҳ|рӯз|бегоҳ/, - meridiemHour: function (hour, meridiem) { - if (hour === 12) { - hour = 0; - } - if (meridiem === 'шаб') { - return hour < 4 ? hour : hour + 12; - } else if (meridiem === 'субҳ') { - return hour; - } else if (meridiem === 'рӯз') { - return hour >= 11 ? hour : hour + 12; - } else if (meridiem === 'бегоҳ') { - return hour + 12; - } - }, - meridiem: function (hour, minute, isLower) { - if (hour < 4) { - return 'шаб'; - } else if (hour < 11) { - return 'субҳ'; - } else if (hour < 16) { - return 'рӯз'; - } else if (hour < 19) { - return 'бегоҳ'; - } else { - return 'шаб'; - } - }, - dayOfMonthOrdinalParse: /\d{1,2}-(ум|юм)/, - ordinal: function (number) { - var a = number % 10, - b = number >= 100 ? 100 : null; - return number + (suffixes[number] || suffixes[a] || suffixes[b]); - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 1th is the first week of the year. + Notification.prototype.do = function (next, error, complete) { + var kind = this.kind; + switch (kind) { + case 'N': + return next && next(this.value); + case 'E': + return error && error(this.error); + case 'C': + return complete && complete(); } - }); + }; + Notification.prototype.accept = function (nextOrObserver, error, complete) { + if (nextOrObserver && typeof nextOrObserver.next === 'function') { + return this.observe(nextOrObserver); + } + else { + return this.do(nextOrObserver, error, complete); + } + }; + Notification.prototype.toObservable = function () { + var kind = this.kind; + switch (kind) { + case 'N': + return Object(_observable_of__WEBPACK_IMPORTED_MODULE_1__["of"])(this.value); + case 'E': + return Object(_observable_throwError__WEBPACK_IMPORTED_MODULE_2__["throwError"])(this.error); + case 'C': + return Object(_observable_empty__WEBPACK_IMPORTED_MODULE_0__["empty"])(); + } + throw new Error('unexpected notification kind value'); + }; + Notification.createNext = function (value) { + if (typeof value !== 'undefined') { + return new Notification('N', value); + } + return Notification.undefinedValueNotification; + }; + Notification.createError = function (err) { + return new Notification('E', undefined, err); + }; + Notification.createComplete = function () { + return Notification.completeNotification; + }; + Notification.completeNotification = new Notification('C'); + Notification.undefinedValueNotification = new Notification('N', undefined); + return Notification; +}()); - return tg; +//# sourceMappingURL=Notification.js.map -}))); + +/***/ }), +/* 174 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EMPTY", function() { return EMPTY; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "empty", function() { return empty; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ + +var EMPTY = /*@__PURE__*/ new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { return subscriber.complete(); }); +function empty(scheduler) { + return scheduler ? emptyScheduled(scheduler) : EMPTY; +} +function emptyScheduled(scheduler) { + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { return scheduler.schedule(function () { return subscriber.complete(); }); }); +} +//# sourceMappingURL=empty.js.map /***/ }), -/* 151 */ -/***/ (function(module, exports, __webpack_require__) { +/* 175 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -//! moment.js locale configuration +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "of", function() { return of; }); +/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(176); +/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(177); +/* harmony import */ var _scheduled_scheduleArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(179); +/** PURE_IMPORTS_START _util_isScheduler,_fromArray,_scheduled_scheduleArray PURE_IMPORTS_END */ -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - var th = moment.defineLocale('th', { - months : 'มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม'.split('_'), - monthsShort : 'ม.ค._ก.พ._มี.ค._เม.ย._พ.ค._มิ.ย._ก.ค._ส.ค._ก.ย._ต.ค._พ.ย._ธ.ค.'.split('_'), - monthsParseExact: true, - weekdays : 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์'.split('_'), - weekdaysShort : 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัส_ศุกร์_เสาร์'.split('_'), // yes, three characters difference - weekdaysMin : 'อา._จ._อ._พ._พฤ._ศ._ส.'.split('_'), - weekdaysParseExact : true, - longDateFormat : { - LT : 'H:mm', - LTS : 'H:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY เวลา H:mm', - LLLL : 'วันddddที่ D MMMM YYYY เวลา H:mm' - }, - meridiemParse: /ก่อนเที่ยง|หลังเที่ยง/, - isPM: function (input) { - return input === 'หลังเที่ยง'; - }, - meridiem : function (hour, minute, isLower) { - if (hour < 12) { - return 'ก่อนเที่ยง'; - } else { - return 'หลังเที่ยง'; - } - }, - calendar : { - sameDay : '[วันนี้ เวลา] LT', - nextDay : '[พรุ่งนี้ เวลา] LT', - nextWeek : 'dddd[หน้า เวลา] LT', - lastDay : '[เมื่อวานนี้ เวลา] LT', - lastWeek : '[วัน]dddd[ที่แล้ว เวลา] LT', - sameElse : 'L' - }, - relativeTime : { - future : 'อีก %s', - past : '%sที่แล้ว', - s : 'ไม่กี่วินาที', - ss : '%d วินาที', - m : '1 นาที', - mm : '%d นาที', - h : '1 ชั่วโมง', - hh : '%d ชั่วโมง', - d : '1 วัน', - dd : '%d วัน', - M : '1 เดือน', - MM : '%d เดือน', - y : '1 ปี', - yy : '%d ปี' - } - }); +function of() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var scheduler = args[args.length - 1]; + if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_0__["isScheduler"])(scheduler)) { + args.pop(); + return Object(_scheduled_scheduleArray__WEBPACK_IMPORTED_MODULE_2__["scheduleArray"])(args, scheduler); + } + else { + return Object(_fromArray__WEBPACK_IMPORTED_MODULE_1__["fromArray"])(args); + } +} +//# sourceMappingURL=of.js.map - return th; -}))); +/***/ }), +/* 176 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isScheduler", function() { return isScheduler; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function isScheduler(value) { + return value && typeof value.schedule === 'function'; +} +//# sourceMappingURL=isScheduler.js.map /***/ }), -/* 152 */ -/***/ (function(module, exports, __webpack_require__) { +/* 177 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -//! moment.js locale configuration +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromArray", function() { return fromArray; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _util_subscribeToArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(178); +/* harmony import */ var _scheduled_scheduleArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(179); +/** PURE_IMPORTS_START _Observable,_util_subscribeToArray,_scheduled_scheduleArray PURE_IMPORTS_END */ -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - var tlPh = moment.defineLocale('tl-ph', { - months : 'Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre'.split('_'), - monthsShort : 'Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis'.split('_'), - weekdays : 'Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado'.split('_'), - weekdaysShort : 'Lin_Lun_Mar_Miy_Huw_Biy_Sab'.split('_'), - weekdaysMin : 'Li_Lu_Ma_Mi_Hu_Bi_Sab'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'MM/D/YYYY', - LL : 'MMMM D, YYYY', - LLL : 'MMMM D, YYYY HH:mm', - LLLL : 'dddd, MMMM DD, YYYY HH:mm' - }, - calendar : { - sameDay: 'LT [ngayong araw]', - nextDay: '[Bukas ng] LT', - nextWeek: 'LT [sa susunod na] dddd', - lastDay: 'LT [kahapon]', - lastWeek: 'LT [noong nakaraang] dddd', - sameElse: 'L' - }, - relativeTime : { - future : 'sa loob ng %s', - past : '%s ang nakalipas', - s : 'ilang segundo', - ss : '%d segundo', - m : 'isang minuto', - mm : '%d minuto', - h : 'isang oras', - hh : '%d oras', - d : 'isang araw', - dd : '%d araw', - M : 'isang buwan', - MM : '%d buwan', - y : 'isang taon', - yy : '%d taon' - }, - dayOfMonthOrdinalParse: /\d{1,2}/, - ordinal : function (number) { - return number; - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. - } - }); +function fromArray(input, scheduler) { + if (!scheduler) { + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](Object(_util_subscribeToArray__WEBPACK_IMPORTED_MODULE_1__["subscribeToArray"])(input)); + } + else { + return Object(_scheduled_scheduleArray__WEBPACK_IMPORTED_MODULE_2__["scheduleArray"])(input, scheduler); + } +} +//# sourceMappingURL=fromArray.js.map - return tlPh; -}))); +/***/ }), +/* 178 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeToArray", function() { return subscribeToArray; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var subscribeToArray = function (array) { + return function (subscriber) { + for (var i = 0, len = array.length; i < len && !subscriber.closed; i++) { + subscriber.next(array[i]); + } + subscriber.complete(); + }; +}; +//# sourceMappingURL=subscribeToArray.js.map /***/ }), -/* 153 */ -/***/ (function(module, exports, __webpack_require__) { +/* 179 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -//! moment.js locale configuration +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scheduleArray", function() { return scheduleArray; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(148); +/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; + +function scheduleArray(input, scheduler) { + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { + var sub = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"](); + var i = 0; + sub.add(scheduler.schedule(function () { + if (i === input.length) { + subscriber.complete(); + return; + } + subscriber.next(input[i++]); + if (!subscriber.closed) { + sub.add(this.schedule()); + } + })); + return sub; + }); +} +//# sourceMappingURL=scheduleArray.js.map - var numbersNouns = 'pagh_wa’_cha’_wej_loS_vagh_jav_Soch_chorgh_Hut'.split('_'); +/***/ }), +/* 180 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - function translateFuture(output) { - var time = output; - time = (output.indexOf('jaj') !== -1) ? - time.slice(0, -3) + 'leS' : - (output.indexOf('jar') !== -1) ? - time.slice(0, -3) + 'waQ' : - (output.indexOf('DIS') !== -1) ? - time.slice(0, -3) + 'nem' : - time + ' pIq'; - return time; - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "throwError", function() { return throwError; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ - function translatePast(output) { - var time = output; - time = (output.indexOf('jaj') !== -1) ? - time.slice(0, -3) + 'Hu’' : - (output.indexOf('jar') !== -1) ? - time.slice(0, -3) + 'wen' : - (output.indexOf('DIS') !== -1) ? - time.slice(0, -3) + 'ben' : - time + ' ret'; - return time; +function throwError(error, scheduler) { + if (!scheduler) { + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { return subscriber.error(error); }); } - - function translate(number, withoutSuffix, string, isFuture) { - var numberNoun = numberAsNoun(number); - switch (string) { - case 'ss': - return numberNoun + ' lup'; - case 'mm': - return numberNoun + ' tup'; - case 'hh': - return numberNoun + ' rep'; - case 'dd': - return numberNoun + ' jaj'; - case 'MM': - return numberNoun + ' jar'; - case 'yy': - return numberNoun + ' DIS'; - } + else { + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { return scheduler.schedule(dispatch, 0, { error: error, subscriber: subscriber }); }); } +} +function dispatch(_a) { + var error = _a.error, subscriber = _a.subscriber; + subscriber.error(error); +} +//# sourceMappingURL=throwError.js.map - function numberAsNoun(number) { - var hundred = Math.floor((number % 1000) / 100), - ten = Math.floor((number % 100) / 10), - one = number % 10, - word = ''; - if (hundred > 0) { - word += numbersNouns[hundred] + 'vatlh'; + +/***/ }), +/* 181 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AsyncSubject", function() { return AsyncSubject; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(158); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(148); +/** PURE_IMPORTS_START tslib,_Subject,_Subscription PURE_IMPORTS_END */ + + + +var AsyncSubject = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AsyncSubject, _super); + function AsyncSubject() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.value = null; + _this.hasNext = false; + _this.hasCompleted = false; + return _this; + } + AsyncSubject.prototype._subscribe = function (subscriber) { + if (this.hasError) { + subscriber.error(this.thrownError); + return _Subscription__WEBPACK_IMPORTED_MODULE_2__["Subscription"].EMPTY; } - if (ten > 0) { - word += ((word !== '') ? ' ' : '') + numbersNouns[ten] + 'maH'; + else if (this.hasCompleted && this.hasNext) { + subscriber.next(this.value); + subscriber.complete(); + return _Subscription__WEBPACK_IMPORTED_MODULE_2__["Subscription"].EMPTY; } - if (one > 0) { - word += ((word !== '') ? ' ' : '') + numbersNouns[one]; + return _super.prototype._subscribe.call(this, subscriber); + }; + AsyncSubject.prototype.next = function (value) { + if (!this.hasCompleted) { + this.value = value; + this.hasNext = true; } - return (word === '') ? 'pagh' : word; - } - - var tlh = moment.defineLocale('tlh', { - months : 'tera’ jar wa’_tera’ jar cha’_tera’ jar wej_tera’ jar loS_tera’ jar vagh_tera’ jar jav_tera’ jar Soch_tera’ jar chorgh_tera’ jar Hut_tera’ jar wa’maH_tera’ jar wa’maH wa’_tera’ jar wa’maH cha’'.split('_'), - monthsShort : 'jar wa’_jar cha’_jar wej_jar loS_jar vagh_jar jav_jar Soch_jar chorgh_jar Hut_jar wa’maH_jar wa’maH wa’_jar wa’maH cha’'.split('_'), - monthsParseExact : true, - weekdays : 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'), - weekdaysShort : 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'), - weekdaysMin : 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd, D MMMM YYYY HH:mm' - }, - calendar : { - sameDay: '[DaHjaj] LT', - nextDay: '[wa’leS] LT', - nextWeek: 'LLL', - lastDay: '[wa’Hu’] LT', - lastWeek: 'LLL', - sameElse: 'L' - }, - relativeTime : { - future : translateFuture, - past : translatePast, - s : 'puS lup', - ss : translate, - m : 'wa’ tup', - mm : translate, - h : 'wa’ rep', - hh : translate, - d : 'wa’ jaj', - dd : translate, - M : 'wa’ jar', - MM : translate, - y : 'wa’ DIS', - yy : translate - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + }; + AsyncSubject.prototype.error = function (error) { + if (!this.hasCompleted) { + _super.prototype.error.call(this, error); } - }); - - return tlh; + }; + AsyncSubject.prototype.complete = function () { + this.hasCompleted = true; + if (this.hasNext) { + _super.prototype.next.call(this, this.value); + } + _super.prototype.complete.call(this); + }; + return AsyncSubject; +}(_Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"])); -}))); +//# sourceMappingURL=AsyncSubject.js.map /***/ }), -/* 154 */ -/***/ (function(module, exports, __webpack_require__) { +/* 182 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "asap", function() { return asap; }); +/* harmony import */ var _AsapAction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(183); +/* harmony import */ var _AsapScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(185); +/** PURE_IMPORTS_START _AsapAction,_AsapScheduler PURE_IMPORTS_END */ -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - var suffixes = { - 1: '\'inci', - 5: '\'inci', - 8: '\'inci', - 70: '\'inci', - 80: '\'inci', - 2: '\'nci', - 7: '\'nci', - 20: '\'nci', - 50: '\'nci', - 3: '\'üncü', - 4: '\'üncü', - 100: '\'üncü', - 6: '\'ncı', - 9: '\'uncu', - 10: '\'uncu', - 30: '\'uncu', - 60: '\'ıncı', - 90: '\'ıncı' - }; +var asap = /*@__PURE__*/ new _AsapScheduler__WEBPACK_IMPORTED_MODULE_1__["AsapScheduler"](_AsapAction__WEBPACK_IMPORTED_MODULE_0__["AsapAction"]); +//# sourceMappingURL=asap.js.map - var tr = moment.defineLocale('tr', { - months : 'Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık'.split('_'), - monthsShort : 'Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara'.split('_'), - weekdays : 'Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi'.split('_'), - weekdaysShort : 'Paz_Pts_Sal_Çar_Per_Cum_Cts'.split('_'), - weekdaysMin : 'Pz_Pt_Sa_Ça_Pe_Cu_Ct'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd, D MMMM YYYY HH:mm' - }, - calendar : { - sameDay : '[bugün saat] LT', - nextDay : '[yarın saat] LT', - nextWeek : '[gelecek] dddd [saat] LT', - lastDay : '[dün] LT', - lastWeek : '[geçen] dddd [saat] LT', - sameElse : 'L' - }, - relativeTime : { - future : '%s sonra', - past : '%s önce', - s : 'birkaç saniye', - ss : '%d saniye', - m : 'bir dakika', - mm : '%d dakika', - h : 'bir saat', - hh : '%d saat', - d : 'bir gün', - dd : '%d gün', - M : 'bir ay', - MM : '%d ay', - y : 'bir yıl', - yy : '%d yıl' - }, - ordinal: function (number, period) { - switch (period) { - case 'd': - case 'D': - case 'Do': - case 'DD': - return number; - default: - if (number === 0) { // special case for zero - return number + '\'ıncı'; - } - var a = number % 10, - b = number % 100 - a, - c = number >= 100 ? 100 : null; - return number + (suffixes[a] || suffixes[b] || suffixes[c]); - } - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. - } - }); - return tr; +/***/ }), +/* 183 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -}))); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AsapAction", function() { return AsapAction; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _util_Immediate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(184); +/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(167); +/** PURE_IMPORTS_START tslib,_util_Immediate,_AsyncAction PURE_IMPORTS_END */ + + + +var AsapAction = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AsapAction, _super); + function AsapAction(scheduler, work) { + var _this = _super.call(this, scheduler, work) || this; + _this.scheduler = scheduler; + _this.work = work; + return _this; + } + AsapAction.prototype.requestAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { + delay = 0; + } + if (delay !== null && delay > 0) { + return _super.prototype.requestAsyncId.call(this, scheduler, id, delay); + } + scheduler.actions.push(this); + return scheduler.scheduled || (scheduler.scheduled = _util_Immediate__WEBPACK_IMPORTED_MODULE_1__["Immediate"].setImmediate(scheduler.flush.bind(scheduler, null))); + }; + AsapAction.prototype.recycleAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { + delay = 0; + } + if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) { + return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay); + } + if (scheduler.actions.length === 0) { + _util_Immediate__WEBPACK_IMPORTED_MODULE_1__["Immediate"].clearImmediate(id); + scheduler.scheduled = undefined; + } + return undefined; + }; + return AsapAction; +}(_AsyncAction__WEBPACK_IMPORTED_MODULE_2__["AsyncAction"])); + +//# sourceMappingURL=AsapAction.js.map /***/ }), -/* 155 */ -/***/ (function(module, exports, __webpack_require__) { +/* 184 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -//! moment.js locale configuration +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Immediate", function() { return Immediate; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var nextHandle = 1; +var tasksByHandle = {}; +function runIfPresent(handle) { + var cb = tasksByHandle[handle]; + if (cb) { + cb(); + } +} +var Immediate = { + setImmediate: function (cb) { + var handle = nextHandle++; + tasksByHandle[handle] = cb; + Promise.resolve().then(function () { return runIfPresent(handle); }); + return handle; + }, + clearImmediate: function (handle) { + delete tasksByHandle[handle]; + }, +}; +//# sourceMappingURL=Immediate.js.map -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +/***/ }), +/* 185 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AsapScheduler", function() { return AsapScheduler; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(170); +/** PURE_IMPORTS_START tslib,_AsyncScheduler PURE_IMPORTS_END */ - // After the year there should be a slash and the amount of years since December 26, 1979 in Roman numerals. - // This is currently too difficult (maybe even impossible) to add. - var tzl = moment.defineLocale('tzl', { - months : 'Januar_Fevraglh_Març_Avrïu_Mai_Gün_Julia_Guscht_Setemvar_Listopäts_Noemvar_Zecemvar'.split('_'), - monthsShort : 'Jan_Fev_Mar_Avr_Mai_Gün_Jul_Gus_Set_Lis_Noe_Zec'.split('_'), - weekdays : 'Súladi_Lúneçi_Maitzi_Márcuri_Xhúadi_Viénerçi_Sáturi'.split('_'), - weekdaysShort : 'Súl_Lún_Mai_Már_Xhú_Vié_Sát'.split('_'), - weekdaysMin : 'Sú_Lú_Ma_Má_Xh_Vi_Sá'.split('_'), - longDateFormat : { - LT : 'HH.mm', - LTS : 'HH.mm.ss', - L : 'DD.MM.YYYY', - LL : 'D. MMMM [dallas] YYYY', - LLL : 'D. MMMM [dallas] YYYY HH.mm', - LLLL : 'dddd, [li] D. MMMM [dallas] YYYY HH.mm' - }, - meridiemParse: /d\'o|d\'a/i, - isPM : function (input) { - return 'd\'o' === input.toLowerCase(); - }, - meridiem : function (hours, minutes, isLower) { - if (hours > 11) { - return isLower ? 'd\'o' : 'D\'O'; - } else { - return isLower ? 'd\'a' : 'D\'A'; + +var AsapScheduler = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AsapScheduler, _super); + function AsapScheduler() { + return _super !== null && _super.apply(this, arguments) || this; + } + AsapScheduler.prototype.flush = function (action) { + this.active = true; + this.scheduled = undefined; + var actions = this.actions; + var error; + var index = -1; + var count = actions.length; + action = action || actions.shift(); + do { + if (error = action.execute(action.state, action.delay)) { + break; } - }, - calendar : { - sameDay : '[oxhi à] LT', - nextDay : '[demà à] LT', - nextWeek : 'dddd [à] LT', - lastDay : '[ieiri à] LT', - lastWeek : '[sür el] dddd [lasteu à] LT', - sameElse : 'L' - }, - relativeTime : { - future : 'osprei %s', - past : 'ja%s', - s : processRelativeTime, - ss : processRelativeTime, - m : processRelativeTime, - mm : processRelativeTime, - h : processRelativeTime, - hh : processRelativeTime, - d : processRelativeTime, - dd : processRelativeTime, - M : processRelativeTime, - MM : processRelativeTime, - y : processRelativeTime, - yy : processRelativeTime - }, - dayOfMonthOrdinalParse: /\d{1,2}\./, - ordinal : '%d.', - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + } while (++index < count && (action = actions.shift())); + this.active = false; + if (error) { + while (++index < count && (action = actions.shift())) { + action.unsubscribe(); + } + throw error; } - }); + }; + return AsapScheduler; +}(_AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__["AsyncScheduler"])); - function processRelativeTime(number, withoutSuffix, key, isFuture) { - var format = { - 's': ['viensas secunds', '\'iensas secunds'], - 'ss': [number + ' secunds', '' + number + ' secunds'], - 'm': ['\'n míut', '\'iens míut'], - 'mm': [number + ' míuts', '' + number + ' míuts'], - 'h': ['\'n þora', '\'iensa þora'], - 'hh': [number + ' þoras', '' + number + ' þoras'], - 'd': ['\'n ziua', '\'iensa ziua'], - 'dd': [number + ' ziuas', '' + number + ' ziuas'], - 'M': ['\'n mes', '\'iens mes'], - 'MM': [number + ' mesen', '' + number + ' mesen'], - 'y': ['\'n ar', '\'iens ar'], - 'yy': [number + ' ars', '' + number + ' ars'] - }; - return isFuture ? format[key][0] : (withoutSuffix ? format[key][0] : format[key][1]); - } +//# sourceMappingURL=AsapScheduler.js.map - return tzl; -}))); +/***/ }), +/* 186 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "async", function() { return async; }); +/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(167); +/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(170); +/** PURE_IMPORTS_START _AsyncAction,_AsyncScheduler PURE_IMPORTS_END */ -/***/ }), -/* 156 */ -/***/ (function(module, exports, __webpack_require__) { -//! moment.js locale configuration +var async = /*@__PURE__*/ new _AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__["AsyncScheduler"](_AsyncAction__WEBPACK_IMPORTED_MODULE_0__["AsyncAction"]); +//# sourceMappingURL=async.js.map -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +/***/ }), +/* 187 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - var tzm = moment.defineLocale('tzm', { - months : 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'), - monthsShort : 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'), - weekdays : 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), - weekdaysShort : 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), - weekdaysMin : 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS: 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd D MMMM YYYY HH:mm' - }, - calendar : { - sameDay: '[ⴰⵙⴷⵅ ⴴ] LT', - nextDay: '[ⴰⵙⴽⴰ ⴴ] LT', - nextWeek: 'dddd [ⴴ] LT', - lastDay: '[ⴰⵚⴰⵏⵜ ⴴ] LT', - lastWeek: 'dddd [ⴴ] LT', - sameElse: 'L' - }, - relativeTime : { - future : 'ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ %s', - past : 'ⵢⴰⵏ %s', - s : 'ⵉⵎⵉⴽ', - ss : '%d ⵉⵎⵉⴽ', - m : 'ⵎⵉⵏⵓⴺ', - mm : '%d ⵎⵉⵏⵓⴺ', - h : 'ⵙⴰⵄⴰ', - hh : '%d ⵜⴰⵙⵙⴰⵄⵉⵏ', - d : 'ⴰⵙⵙ', - dd : '%d oⵙⵙⴰⵏ', - M : 'ⴰⵢoⵓⵔ', - MM : '%d ⵉⵢⵢⵉⵔⵏ', - y : 'ⴰⵙⴳⴰⵙ', - yy : '%d ⵉⵙⴳⴰⵙⵏ' - }, - week : { - dow : 6, // Saturday is the first day of the week. - doy : 12 // The week that contains Jan 12th is the first week of the year. - } - }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "animationFrame", function() { return animationFrame; }); +/* harmony import */ var _AnimationFrameAction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(188); +/* harmony import */ var _AnimationFrameScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(189); +/** PURE_IMPORTS_START _AnimationFrameAction,_AnimationFrameScheduler PURE_IMPORTS_END */ - return tzm; -}))); +var animationFrame = /*@__PURE__*/ new _AnimationFrameScheduler__WEBPACK_IMPORTED_MODULE_1__["AnimationFrameScheduler"](_AnimationFrameAction__WEBPACK_IMPORTED_MODULE_0__["AnimationFrameAction"]); +//# sourceMappingURL=animationFrame.js.map /***/ }), -/* 157 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js locale configuration +/* 188 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationFrameAction", function() { return AnimationFrameAction; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(167); +/** PURE_IMPORTS_START tslib,_AsyncAction PURE_IMPORTS_END */ - var tzmLatn = moment.defineLocale('tzm-latn', { - months : 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'), - monthsShort : 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'), - weekdays : 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), - weekdaysShort : 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), - weekdaysMin : 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd D MMMM YYYY HH:mm' - }, - calendar : { - sameDay: '[asdkh g] LT', - nextDay: '[aska g] LT', - nextWeek: 'dddd [g] LT', - lastDay: '[assant g] LT', - lastWeek: 'dddd [g] LT', - sameElse: 'L' - }, - relativeTime : { - future : 'dadkh s yan %s', - past : 'yan %s', - s : 'imik', - ss : '%d imik', - m : 'minuḍ', - mm : '%d minuḍ', - h : 'saɛa', - hh : '%d tassaɛin', - d : 'ass', - dd : '%d ossan', - M : 'ayowr', - MM : '%d iyyirn', - y : 'asgas', - yy : '%d isgasn' - }, - week : { - dow : 6, // Saturday is the first day of the week. - doy : 12 // The week that contains Jan 12th is the first week of the year. +var AnimationFrameAction = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AnimationFrameAction, _super); + function AnimationFrameAction(scheduler, work) { + var _this = _super.call(this, scheduler, work) || this; + _this.scheduler = scheduler; + _this.work = work; + return _this; + } + AnimationFrameAction.prototype.requestAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { + delay = 0; } - }); - - return tzmLatn; + if (delay !== null && delay > 0) { + return _super.prototype.requestAsyncId.call(this, scheduler, id, delay); + } + scheduler.actions.push(this); + return scheduler.scheduled || (scheduler.scheduled = requestAnimationFrame(function () { return scheduler.flush(null); })); + }; + AnimationFrameAction.prototype.recycleAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { + delay = 0; + } + if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) { + return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay); + } + if (scheduler.actions.length === 0) { + cancelAnimationFrame(id); + scheduler.scheduled = undefined; + } + return undefined; + }; + return AnimationFrameAction; +}(_AsyncAction__WEBPACK_IMPORTED_MODULE_1__["AsyncAction"])); -}))); +//# sourceMappingURL=AnimationFrameAction.js.map /***/ }), -/* 158 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js language configuration +/* 189 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationFrameScheduler", function() { return AnimationFrameScheduler; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(170); +/** PURE_IMPORTS_START tslib,_AsyncScheduler PURE_IMPORTS_END */ - var ugCn = moment.defineLocale('ug-cn', { - months: 'يانۋار_فېۋرال_مارت_ئاپرېل_ماي_ئىيۇن_ئىيۇل_ئاۋغۇست_سېنتەبىر_ئۆكتەبىر_نويابىر_دېكابىر'.split( - '_' - ), - monthsShort: 'يانۋار_فېۋرال_مارت_ئاپرېل_ماي_ئىيۇن_ئىيۇل_ئاۋغۇست_سېنتەبىر_ئۆكتەبىر_نويابىر_دېكابىر'.split( - '_' - ), - weekdays: 'يەكشەنبە_دۈشەنبە_سەيشەنبە_چارشەنبە_پەيشەنبە_جۈمە_شەنبە'.split( - '_' - ), - weekdaysShort: 'يە_دۈ_سە_چا_پە_جۈ_شە'.split('_'), - weekdaysMin: 'يە_دۈ_سە_چا_پە_جۈ_شە'.split('_'), - longDateFormat: { - LT: 'HH:mm', - LTS: 'HH:mm:ss', - L: 'YYYY-MM-DD', - LL: 'YYYY-يىلىM-ئاينىڭD-كۈنى', - LLL: 'YYYY-يىلىM-ئاينىڭD-كۈنى، HH:mm', - LLLL: 'dddd، YYYY-يىلىM-ئاينىڭD-كۈنى، HH:mm' - }, - meridiemParse: /يېرىم كېچە|سەھەر|چۈشتىن بۇرۇن|چۈش|چۈشتىن كېيىن|كەچ/, - meridiemHour: function (hour, meridiem) { - if (hour === 12) { - hour = 0; +var AnimationFrameScheduler = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AnimationFrameScheduler, _super); + function AnimationFrameScheduler() { + return _super !== null && _super.apply(this, arguments) || this; + } + AnimationFrameScheduler.prototype.flush = function (action) { + this.active = true; + this.scheduled = undefined; + var actions = this.actions; + var error; + var index = -1; + var count = actions.length; + action = action || actions.shift(); + do { + if (error = action.execute(action.state, action.delay)) { + break; } - if ( - meridiem === 'يېرىم كېچە' || - meridiem === 'سەھەر' || - meridiem === 'چۈشتىن بۇرۇن' - ) { - return hour; - } else if (meridiem === 'چۈشتىن كېيىن' || meridiem === 'كەچ') { - return hour + 12; - } else { - return hour >= 11 ? hour : hour + 12; + } while (++index < count && (action = actions.shift())); + this.active = false; + if (error) { + while (++index < count && (action = actions.shift())) { + action.unsubscribe(); } - }, - meridiem: function (hour, minute, isLower) { - var hm = hour * 100 + minute; - if (hm < 600) { - return 'يېرىم كېچە'; - } else if (hm < 900) { - return 'سەھەر'; - } else if (hm < 1130) { - return 'چۈشتىن بۇرۇن'; - } else if (hm < 1230) { - return 'چۈش'; - } else if (hm < 1800) { - return 'چۈشتىن كېيىن'; - } else { - return 'كەچ'; - } - }, - calendar: { - sameDay: '[بۈگۈن سائەت] LT', - nextDay: '[ئەتە سائەت] LT', - nextWeek: '[كېلەركى] dddd [سائەت] LT', - lastDay: '[تۆنۈگۈن] LT', - lastWeek: '[ئالدىنقى] dddd [سائەت] LT', - sameElse: 'L' - }, - relativeTime: { - future: '%s كېيىن', - past: '%s بۇرۇن', - s: 'نەچچە سېكونت', - ss: '%d سېكونت', - m: 'بىر مىنۇت', - mm: '%d مىنۇت', - h: 'بىر سائەت', - hh: '%d سائەت', - d: 'بىر كۈن', - dd: '%d كۈن', - M: 'بىر ئاي', - MM: '%d ئاي', - y: 'بىر يىل', - yy: '%d يىل' - }, - - dayOfMonthOrdinalParse: /\d{1,2}(-كۈنى|-ئاي|-ھەپتە)/, - ordinal: function (number, period) { - switch (period) { - case 'd': - case 'D': - case 'DDD': - return number + '-كۈنى'; - case 'w': - case 'W': - return number + '-ھەپتە'; - default: - return number; - } - }, - preparse: function (string) { - return string.replace(/،/g, ','); - }, - postformat: function (string) { - return string.replace(/,/g, '،'); - }, - week: { - // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效 - dow: 1, // Monday is the first day of the week. - doy: 7 // The week that contains Jan 1st is the first week of the year. + throw error; } - }); - - return ugCn; + }; + return AnimationFrameScheduler; +}(_AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__["AsyncScheduler"])); -}))); +//# sourceMappingURL=AnimationFrameScheduler.js.map /***/ }), -/* 159 */ -/***/ (function(module, exports, __webpack_require__) { +/* 190 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -//! moment.js locale configuration +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VirtualTimeScheduler", function() { return VirtualTimeScheduler; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VirtualAction", function() { return VirtualAction; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(167); +/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(170); +/** PURE_IMPORTS_START tslib,_AsyncAction,_AsyncScheduler PURE_IMPORTS_END */ -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - function plural(word, num) { - var forms = word.split('_'); - return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); - } - function relativeTimeWithPlural(number, withoutSuffix, key) { - var format = { - 'ss': withoutSuffix ? 'секунда_секунди_секунд' : 'секунду_секунди_секунд', - 'mm': withoutSuffix ? 'хвилина_хвилини_хвилин' : 'хвилину_хвилини_хвилин', - 'hh': withoutSuffix ? 'година_години_годин' : 'годину_години_годин', - 'dd': 'день_дні_днів', - 'MM': 'місяць_місяці_місяців', - 'yy': 'рік_роки_років' - }; - if (key === 'm') { - return withoutSuffix ? 'хвилина' : 'хвилину'; - } - else if (key === 'h') { - return withoutSuffix ? 'година' : 'годину'; +var VirtualTimeScheduler = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VirtualTimeScheduler, _super); + function VirtualTimeScheduler(SchedulerAction, maxFrames) { + if (SchedulerAction === void 0) { + SchedulerAction = VirtualAction; } - else { - return number + ' ' + plural(format[key], +number); + if (maxFrames === void 0) { + maxFrames = Number.POSITIVE_INFINITY; } + var _this = _super.call(this, SchedulerAction, function () { return _this.frame; }) || this; + _this.maxFrames = maxFrames; + _this.frame = 0; + _this.index = -1; + return _this; } - function weekdaysCaseReplace(m, format) { - var weekdays = { - 'nominative': 'неділя_понеділок_вівторок_середа_четвер_п’ятниця_субота'.split('_'), - 'accusative': 'неділю_понеділок_вівторок_середу_четвер_п’ятницю_суботу'.split('_'), - 'genitive': 'неділі_понеділка_вівторка_середи_четверга_п’ятниці_суботи'.split('_') - }; - - if (m === true) { - return weekdays['nominative'].slice(1, 7).concat(weekdays['nominative'].slice(0, 1)); + VirtualTimeScheduler.prototype.flush = function () { + var _a = this, actions = _a.actions, maxFrames = _a.maxFrames; + var error, action; + while ((action = actions[0]) && action.delay <= maxFrames) { + actions.shift(); + this.frame = action.delay; + if (error = action.execute(action.state, action.delay)) { + break; + } } - if (!m) { - return weekdays['nominative']; + if (error) { + while (action = actions.shift()) { + action.unsubscribe(); + } + throw error; } + }; + VirtualTimeScheduler.frameTimeFactor = 10; + return VirtualTimeScheduler; +}(_AsyncScheduler__WEBPACK_IMPORTED_MODULE_2__["AsyncScheduler"])); - var nounCase = (/(\[[ВвУу]\]) ?dddd/).test(format) ? - 'accusative' : - ((/\[?(?:минулої|наступної)? ?\] ?dddd/).test(format) ? - 'genitive' : - 'nominative'); - return weekdays[nounCase][m.day()]; - } - function processHoursFunction(str) { - return function () { - return str + 'о' + (this.hours() === 11 ? 'б' : '') + '] LT'; - }; +var VirtualAction = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VirtualAction, _super); + function VirtualAction(scheduler, work, index) { + if (index === void 0) { + index = scheduler.index += 1; + } + var _this = _super.call(this, scheduler, work) || this; + _this.scheduler = scheduler; + _this.work = work; + _this.index = index; + _this.active = true; + _this.index = scheduler.index = index; + return _this; } - - var uk = moment.defineLocale('uk', { - months : { - 'format': 'січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня'.split('_'), - 'standalone': 'січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень'.split('_') - }, - monthsShort : 'січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд'.split('_'), - weekdays : weekdaysCaseReplace, - weekdaysShort : 'нд_пн_вт_ср_чт_пт_сб'.split('_'), - weekdaysMin : 'нд_пн_вт_ср_чт_пт_сб'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD.MM.YYYY', - LL : 'D MMMM YYYY р.', - LLL : 'D MMMM YYYY р., HH:mm', - LLLL : 'dddd, D MMMM YYYY р., HH:mm' - }, - calendar : { - sameDay: processHoursFunction('[Сьогодні '), - nextDay: processHoursFunction('[Завтра '), - lastDay: processHoursFunction('[Вчора '), - nextWeek: processHoursFunction('[У] dddd ['), - lastWeek: function () { - switch (this.day()) { - case 0: - case 3: - case 5: - case 6: - return processHoursFunction('[Минулої] dddd [').call(this); - case 1: - case 2: - case 4: - return processHoursFunction('[Минулого] dddd [').call(this); - } - }, - sameElse: 'L' - }, - relativeTime : { - future : 'за %s', - past : '%s тому', - s : 'декілька секунд', - ss : relativeTimeWithPlural, - m : relativeTimeWithPlural, - mm : relativeTimeWithPlural, - h : 'годину', - hh : relativeTimeWithPlural, - d : 'день', - dd : relativeTimeWithPlural, - M : 'місяць', - MM : relativeTimeWithPlural, - y : 'рік', - yy : relativeTimeWithPlural - }, - // M. E.: those two are virtually unused but a user might want to implement them for his/her website for some reason - meridiemParse: /ночі|ранку|дня|вечора/, - isPM: function (input) { - return /^(дня|вечора)$/.test(input); - }, - meridiem : function (hour, minute, isLower) { - if (hour < 4) { - return 'ночі'; - } else if (hour < 12) { - return 'ранку'; - } else if (hour < 17) { - return 'дня'; - } else { - return 'вечора'; + VirtualAction.prototype.schedule = function (state, delay) { + if (delay === void 0) { + delay = 0; + } + if (!this.id) { + return _super.prototype.schedule.call(this, state, delay); + } + this.active = false; + var action = new VirtualAction(this.scheduler, this.work); + this.add(action); + return action.schedule(state, delay); + }; + VirtualAction.prototype.requestAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { + delay = 0; + } + this.delay = scheduler.frame + delay; + var actions = scheduler.actions; + actions.push(this); + actions.sort(VirtualAction.sortActions); + return true; + }; + VirtualAction.prototype.recycleAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { + delay = 0; + } + return undefined; + }; + VirtualAction.prototype._execute = function (state, delay) { + if (this.active === true) { + return _super.prototype._execute.call(this, state, delay); + } + }; + VirtualAction.sortActions = function (a, b) { + if (a.delay === b.delay) { + if (a.index === b.index) { + return 0; } - }, - dayOfMonthOrdinalParse: /\d{1,2}-(й|го)/, - ordinal: function (number, period) { - switch (period) { - case 'M': - case 'd': - case 'DDD': - case 'w': - case 'W': - return number + '-й'; - case 'D': - return number + '-го'; - default: - return number; + else if (a.index > b.index) { + return 1; + } + else { + return -1; } - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. } - }); - - return uk; + else if (a.delay > b.delay) { + return 1; + } + else { + return -1; + } + }; + return VirtualAction; +}(_AsyncAction__WEBPACK_IMPORTED_MODULE_1__["AsyncAction"])); -}))); +//# sourceMappingURL=VirtualTimeScheduler.js.map /***/ }), -/* 160 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js locale configuration - -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +/* 191 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "identity", function() { return identity; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function identity(x) { + return x; +} +//# sourceMappingURL=identity.js.map - var months = [ - 'جنوری', - 'فروری', - 'مارچ', - 'اپریل', - 'مئی', - 'جون', - 'جولائی', - 'اگست', - 'ستمبر', - 'اکتوبر', - 'نومبر', - 'دسمبر' - ]; - var days = [ - 'اتوار', - 'پیر', - 'منگل', - 'بدھ', - 'جمعرات', - 'جمعہ', - 'ہفتہ' - ]; - var ur = moment.defineLocale('ur', { - months : months, - monthsShort : months, - weekdays : days, - weekdaysShort : days, - weekdaysMin : days, - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd، D MMMM YYYY HH:mm' - }, - meridiemParse: /صبح|شام/, - isPM : function (input) { - return 'شام' === input; - }, - meridiem : function (hour, minute, isLower) { - if (hour < 12) { - return 'صبح'; - } - return 'شام'; - }, - calendar : { - sameDay : '[آج بوقت] LT', - nextDay : '[کل بوقت] LT', - nextWeek : 'dddd [بوقت] LT', - lastDay : '[گذشتہ روز بوقت] LT', - lastWeek : '[گذشتہ] dddd [بوقت] LT', - sameElse : 'L' - }, - relativeTime : { - future : '%s بعد', - past : '%s قبل', - s : 'چند سیکنڈ', - ss : '%d سیکنڈ', - m : 'ایک منٹ', - mm : '%d منٹ', - h : 'ایک گھنٹہ', - hh : '%d گھنٹے', - d : 'ایک دن', - dd : '%d دن', - M : 'ایک ماہ', - MM : '%d ماہ', - y : 'ایک سال', - yy : '%d سال' - }, - preparse: function (string) { - return string.replace(/،/g, ','); - }, - postformat: function (string) { - return string.replace(/,/g, '،'); - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. - } - }); +/***/ }), +/* 192 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - return ur; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isObservable", function() { return isObservable; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ -}))); +function isObservable(obj) { + return !!obj && (obj instanceof _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"] || (typeof obj.lift === 'function' && typeof obj.subscribe === 'function')); +} +//# sourceMappingURL=isObservable.js.map /***/ }), -/* 161 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js locale configuration - -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +/* 193 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArgumentOutOfRangeError", function() { return ArgumentOutOfRangeError; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var ArgumentOutOfRangeErrorImpl = /*@__PURE__*/ (function () { + function ArgumentOutOfRangeErrorImpl() { + Error.call(this); + this.message = 'argument out of range'; + this.name = 'ArgumentOutOfRangeError'; + return this; + } + ArgumentOutOfRangeErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); + return ArgumentOutOfRangeErrorImpl; +})(); +var ArgumentOutOfRangeError = ArgumentOutOfRangeErrorImpl; +//# sourceMappingURL=ArgumentOutOfRangeError.js.map - var uz = moment.defineLocale('uz', { - months : 'январ_феврал_март_апрел_май_июн_июл_август_сентябр_октябр_ноябр_декабр'.split('_'), - monthsShort : 'янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек'.split('_'), - weekdays : 'Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба'.split('_'), - weekdaysShort : 'Якш_Душ_Сеш_Чор_Пай_Жум_Шан'.split('_'), - weekdaysMin : 'Як_Ду_Се_Чо_Па_Жу_Ша'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'D MMMM YYYY, dddd HH:mm' - }, - calendar : { - sameDay : '[Бугун соат] LT [да]', - nextDay : '[Эртага] LT [да]', - nextWeek : 'dddd [куни соат] LT [да]', - lastDay : '[Кеча соат] LT [да]', - lastWeek : '[Утган] dddd [куни соат] LT [да]', - sameElse : 'L' - }, - relativeTime : { - future : 'Якин %s ичида', - past : 'Бир неча %s олдин', - s : 'фурсат', - ss : '%d фурсат', - m : 'бир дакика', - mm : '%d дакика', - h : 'бир соат', - hh : '%d соат', - d : 'бир кун', - dd : '%d кун', - M : 'бир ой', - MM : '%d ой', - y : 'бир йил', - yy : '%d йил' - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 4th is the first week of the year. - } - }); - return uz; +/***/ }), +/* 194 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -}))); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EmptyError", function() { return EmptyError; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var EmptyErrorImpl = /*@__PURE__*/ (function () { + function EmptyErrorImpl() { + Error.call(this); + this.message = 'no elements in sequence'; + this.name = 'EmptyError'; + return this; + } + EmptyErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); + return EmptyErrorImpl; +})(); +var EmptyError = EmptyErrorImpl; +//# sourceMappingURL=EmptyError.js.map /***/ }), -/* 162 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js locale configuration - -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +/* 195 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimeoutError", function() { return TimeoutError; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var TimeoutErrorImpl = /*@__PURE__*/ (function () { + function TimeoutErrorImpl() { + Error.call(this); + this.message = 'Timeout has occurred'; + this.name = 'TimeoutError'; + return this; + } + TimeoutErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); + return TimeoutErrorImpl; +})(); +var TimeoutError = TimeoutErrorImpl; +//# sourceMappingURL=TimeoutError.js.map - var uzLatn = moment.defineLocale('uz-latn', { - months : 'Yanvar_Fevral_Mart_Aprel_May_Iyun_Iyul_Avgust_Sentabr_Oktabr_Noyabr_Dekabr'.split('_'), - monthsShort : 'Yan_Fev_Mar_Apr_May_Iyun_Iyul_Avg_Sen_Okt_Noy_Dek'.split('_'), - weekdays : 'Yakshanba_Dushanba_Seshanba_Chorshanba_Payshanba_Juma_Shanba'.split('_'), - weekdaysShort : 'Yak_Dush_Sesh_Chor_Pay_Jum_Shan'.split('_'), - weekdaysMin : 'Ya_Du_Se_Cho_Pa_Ju_Sha'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'D MMMM YYYY, dddd HH:mm' - }, - calendar : { - sameDay : '[Bugun soat] LT [da]', - nextDay : '[Ertaga] LT [da]', - nextWeek : 'dddd [kuni soat] LT [da]', - lastDay : '[Kecha soat] LT [da]', - lastWeek : '[O\'tgan] dddd [kuni soat] LT [da]', - sameElse : 'L' - }, - relativeTime : { - future : 'Yaqin %s ichida', - past : 'Bir necha %s oldin', - s : 'soniya', - ss : '%d soniya', - m : 'bir daqiqa', - mm : '%d daqiqa', - h : 'bir soat', - hh : '%d soat', - d : 'bir kun', - dd : '%d kun', - M : 'bir oy', - MM : '%d oy', - y : 'bir yil', - yy : '%d yil' - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 7 // The week that contains Jan 7th is the first week of the year. - } - }); - return uzLatn; +/***/ }), +/* 196 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -}))); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bindCallback", function() { return bindCallback; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(181); +/* harmony import */ var _operators_map__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(197); +/* harmony import */ var _util_canReportError__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(142); +/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(149); +/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(176); +/** PURE_IMPORTS_START _Observable,_AsyncSubject,_operators_map,_util_canReportError,_util_isArray,_util_isScheduler PURE_IMPORTS_END */ -/***/ }), -/* 163 */ -/***/ (function(module, exports, __webpack_require__) { -//! moment.js locale configuration -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - var vi = moment.defineLocale('vi', { - months : 'tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12'.split('_'), - monthsShort : 'Th01_Th02_Th03_Th04_Th05_Th06_Th07_Th08_Th09_Th10_Th11_Th12'.split('_'), - monthsParseExact : true, - weekdays : 'chủ nhật_thứ hai_thứ ba_thứ tư_thứ năm_thứ sáu_thứ bảy'.split('_'), - weekdaysShort : 'CN_T2_T3_T4_T5_T6_T7'.split('_'), - weekdaysMin : 'CN_T2_T3_T4_T5_T6_T7'.split('_'), - weekdaysParseExact : true, - meridiemParse: /sa|ch/i, - isPM : function (input) { - return /^ch$/i.test(input); - }, - meridiem : function (hours, minutes, isLower) { - if (hours < 12) { - return isLower ? 'sa' : 'SA'; - } else { - return isLower ? 'ch' : 'CH'; +function bindCallback(callbackFunc, resultSelector, scheduler) { + if (resultSelector) { + if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_5__["isScheduler"])(resultSelector)) { + scheduler = resultSelector; + } + else { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return bindCallback(callbackFunc, scheduler).apply(void 0, args).pipe(Object(_operators_map__WEBPACK_IMPORTED_MODULE_2__["map"])(function (args) { return Object(_util_isArray__WEBPACK_IMPORTED_MODULE_4__["isArray"])(args) ? resultSelector.apply(void 0, args) : resultSelector(args); })); + }; + } + } + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var context = this; + var subject; + var params = { + context: context, + subject: subject, + callbackFunc: callbackFunc, + scheduler: scheduler, + }; + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { + if (!scheduler) { + if (!subject) { + subject = new _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__["AsyncSubject"](); + var handler = function () { + var innerArgs = []; + for (var _i = 0; _i < arguments.length; _i++) { + innerArgs[_i] = arguments[_i]; + } + subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs); + subject.complete(); + }; + try { + callbackFunc.apply(context, args.concat([handler])); + } + catch (err) { + if (Object(_util_canReportError__WEBPACK_IMPORTED_MODULE_3__["canReportError"])(subject)) { + subject.error(err); + } + else { + console.warn(err); + } + } + } + return subject.subscribe(subscriber); } - }, - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'DD/MM/YYYY', - LL : 'D MMMM [năm] YYYY', - LLL : 'D MMMM [năm] YYYY HH:mm', - LLLL : 'dddd, D MMMM [năm] YYYY HH:mm', - l : 'DD/M/YYYY', - ll : 'D MMM YYYY', - lll : 'D MMM YYYY HH:mm', - llll : 'ddd, D MMM YYYY HH:mm' - }, - calendar : { - sameDay: '[Hôm nay lúc] LT', - nextDay: '[Ngày mai lúc] LT', - nextWeek: 'dddd [tuần tới lúc] LT', - lastDay: '[Hôm qua lúc] LT', - lastWeek: 'dddd [tuần rồi lúc] LT', - sameElse: 'L' - }, - relativeTime : { - future : '%s tới', - past : '%s trước', - s : 'vài giây', - ss : '%d giây' , - m : 'một phút', - mm : '%d phút', - h : 'một giờ', - hh : '%d giờ', - d : 'một ngày', - dd : '%d ngày', - M : 'một tháng', - MM : '%d tháng', - y : 'một năm', - yy : '%d năm' - }, - dayOfMonthOrdinalParse: /\d{1,2}/, - ordinal : function (number) { - return number; - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + else { + var state = { + args: args, subscriber: subscriber, params: params, + }; + return scheduler.schedule(dispatch, 0, state); + } + }); + }; +} +function dispatch(state) { + var _this = this; + var self = this; + var args = state.args, subscriber = state.subscriber, params = state.params; + var callbackFunc = params.callbackFunc, context = params.context, scheduler = params.scheduler; + var subject = params.subject; + if (!subject) { + subject = params.subject = new _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__["AsyncSubject"](); + var handler = function () { + var innerArgs = []; + for (var _i = 0; _i < arguments.length; _i++) { + innerArgs[_i] = arguments[_i]; + } + var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs; + _this.add(scheduler.schedule(dispatchNext, 0, { value: value, subject: subject })); + }; + try { + callbackFunc.apply(context, args.concat([handler])); } - }); - - return vi; - -}))); + catch (err) { + subject.error(err); + } + } + this.add(subject.subscribe(subscriber)); +} +function dispatchNext(state) { + var value = state.value, subject = state.subject; + subject.next(value); + subject.complete(); +} +function dispatchError(state) { + var err = state.err, subject = state.subject; + subject.error(err); +} +//# sourceMappingURL=bindCallback.js.map /***/ }), -/* 164 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js locale configuration +/* 197 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "map", function() { return map; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MapOperator", function() { return MapOperator; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ - var xPseudo = moment.defineLocale('x-pseudo', { - months : 'J~áñúá~rý_F~ébrú~árý_~Márc~h_Áp~ríl_~Máý_~Júñé~_Júl~ý_Áú~gúst~_Sép~témb~ér_Ó~ctób~ér_Ñ~óvém~bér_~Décé~mbér'.split('_'), - monthsShort : 'J~áñ_~Féb_~Már_~Ápr_~Máý_~Júñ_~Júl_~Áúg_~Sép_~Óct_~Ñóv_~Déc'.split('_'), - monthsParseExact : true, - weekdays : 'S~úñdá~ý_Mó~ñdáý~_Túé~sdáý~_Wéd~ñésd~áý_T~húrs~dáý_~Fríd~áý_S~átúr~dáý'.split('_'), - weekdaysShort : 'S~úñ_~Móñ_~Túé_~Wéd_~Thú_~Frí_~Sát'.split('_'), - weekdaysMin : 'S~ú_Mó~_Tú_~Wé_T~h_Fr~_Sá'.split('_'), - weekdaysParseExact : true, - longDateFormat : { - LT : 'HH:mm', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY HH:mm', - LLLL : 'dddd, D MMMM YYYY HH:mm' - }, - calendar : { - sameDay : '[T~ódá~ý át] LT', - nextDay : '[T~ómó~rró~w át] LT', - nextWeek : 'dddd [át] LT', - lastDay : '[Ý~ést~érdá~ý át] LT', - lastWeek : '[L~ást] dddd [át] LT', - sameElse : 'L' - }, - relativeTime : { - future : 'í~ñ %s', - past : '%s á~gó', - s : 'á ~féw ~sécó~ñds', - ss : '%d s~écóñ~ds', - m : 'á ~míñ~úté', - mm : '%d m~íñú~tés', - h : 'á~ñ hó~úr', - hh : '%d h~óúrs', - d : 'á ~dáý', - dd : '%d d~áýs', - M : 'á ~móñ~th', - MM : '%d m~óñt~hs', - y : 'á ~ýéár', - yy : '%d ý~éárs' - }, - dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, - ordinal : function (number) { - var b = number % 10, - output = (~~(number % 100 / 10) === 1) ? 'th' : - (b === 1) ? 'st' : - (b === 2) ? 'nd' : - (b === 3) ? 'rd' : 'th'; - return number + output; - }, - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. +function map(project, thisArg) { + return function mapOperation(source) { + if (typeof project !== 'function') { + throw new TypeError('argument is not a function. Are you looking for `mapTo()`?'); } - }); - - return xPseudo; + return source.lift(new MapOperator(project, thisArg)); + }; +} +var MapOperator = /*@__PURE__*/ (function () { + function MapOperator(project, thisArg) { + this.project = project; + this.thisArg = thisArg; + } + MapOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg)); + }; + return MapOperator; +}()); -}))); +var MapSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MapSubscriber, _super); + function MapSubscriber(destination, project, thisArg) { + var _this = _super.call(this, destination) || this; + _this.project = project; + _this.count = 0; + _this.thisArg = thisArg || _this; + return _this; + } + MapSubscriber.prototype._next = function (value) { + var result; + try { + result = this.project.call(this.thisArg, value, this.count++); + } + catch (err) { + this.destination.error(err); + return; + } + this.destination.next(result); + }; + return MapSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=map.js.map /***/ }), -/* 165 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js locale configuration - -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - - - var yo = moment.defineLocale('yo', { - months : 'Sẹ́rẹ́_Èrèlè_Ẹrẹ̀nà_Ìgbé_Èbibi_Òkùdu_Agẹmo_Ògún_Owewe_Ọ̀wàrà_Bélú_Ọ̀pẹ̀̀'.split('_'), - monthsShort : 'Sẹ́r_Èrl_Ẹrn_Ìgb_Èbi_Òkù_Agẹ_Ògú_Owe_Ọ̀wà_Bél_Ọ̀pẹ̀̀'.split('_'), - weekdays : 'Àìkú_Ajé_Ìsẹ́gun_Ọjọ́rú_Ọjọ́bọ_Ẹtì_Àbámẹ́ta'.split('_'), - weekdaysShort : 'Àìk_Ajé_Ìsẹ́_Ọjr_Ọjb_Ẹtì_Àbá'.split('_'), - weekdaysMin : 'Àì_Aj_Ìs_Ọr_Ọb_Ẹt_Àb'.split('_'), - longDateFormat : { - LT : 'h:mm A', - LTS : 'h:mm:ss A', - L : 'DD/MM/YYYY', - LL : 'D MMMM YYYY', - LLL : 'D MMMM YYYY h:mm A', - LLLL : 'dddd, D MMMM YYYY h:mm A' - }, - calendar : { - sameDay : '[Ònì ni] LT', - nextDay : '[Ọ̀la ni] LT', - nextWeek : 'dddd [Ọsẹ̀ tón\'bọ] [ni] LT', - lastDay : '[Àna ni] LT', - lastWeek : 'dddd [Ọsẹ̀ tólọ́] [ni] LT', - sameElse : 'L' - }, - relativeTime : { - future : 'ní %s', - past : '%s kọjá', - s : 'ìsẹjú aayá die', - ss :'aayá %d', - m : 'ìsẹjú kan', - mm : 'ìsẹjú %d', - h : 'wákati kan', - hh : 'wákati %d', - d : 'ọjọ́ kan', - dd : 'ọjọ́ %d', - M : 'osù kan', - MM : 'osù %d', - y : 'ọdún kan', - yy : 'ọdún %d' - }, - dayOfMonthOrdinalParse : /ọjọ́\s\d{1,2}/, - ordinal : 'ọjọ́ %d', - week : { - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. - } - }); - - return yo; +/* 198 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -}))); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bindNodeCallback", function() { return bindNodeCallback; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(181); +/* harmony import */ var _operators_map__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(197); +/* harmony import */ var _util_canReportError__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(142); +/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(176); +/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(149); +/** PURE_IMPORTS_START _Observable,_AsyncSubject,_operators_map,_util_canReportError,_util_isScheduler,_util_isArray PURE_IMPORTS_END */ -/***/ }), -/* 166 */ -/***/ (function(module, exports, __webpack_require__) { -//! moment.js locale configuration -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - var zhCn = moment.defineLocale('zh-cn', { - months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), - monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), - weekdays : '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), - weekdaysShort : '周日_周一_周二_周三_周四_周五_周六'.split('_'), - weekdaysMin : '日_一_二_三_四_五_六'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'YYYY/MM/DD', - LL : 'YYYY年M月D日', - LLL : 'YYYY年M月D日Ah点mm分', - LLLL : 'YYYY年M月D日ddddAh点mm分', - l : 'YYYY/M/D', - ll : 'YYYY年M月D日', - lll : 'YYYY年M月D日 HH:mm', - llll : 'YYYY年M月D日dddd HH:mm' - }, - meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, - meridiemHour: function (hour, meridiem) { - if (hour === 12) { - hour = 0; +function bindNodeCallback(callbackFunc, resultSelector, scheduler) { + if (resultSelector) { + if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_4__["isScheduler"])(resultSelector)) { + scheduler = resultSelector; + } + else { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return bindNodeCallback(callbackFunc, scheduler).apply(void 0, args).pipe(Object(_operators_map__WEBPACK_IMPORTED_MODULE_2__["map"])(function (args) { return Object(_util_isArray__WEBPACK_IMPORTED_MODULE_5__["isArray"])(args) ? resultSelector.apply(void 0, args) : resultSelector(args); })); + }; + } + } + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var params = { + subject: undefined, + args: args, + callbackFunc: callbackFunc, + scheduler: scheduler, + context: this, + }; + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { + var context = params.context; + var subject = params.subject; + if (!scheduler) { + if (!subject) { + subject = params.subject = new _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__["AsyncSubject"](); + var handler = function () { + var innerArgs = []; + for (var _i = 0; _i < arguments.length; _i++) { + innerArgs[_i] = arguments[_i]; + } + var err = innerArgs.shift(); + if (err) { + subject.error(err); + return; + } + subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs); + subject.complete(); + }; + try { + callbackFunc.apply(context, args.concat([handler])); + } + catch (err) { + if (Object(_util_canReportError__WEBPACK_IMPORTED_MODULE_3__["canReportError"])(subject)) { + subject.error(err); + } + else { + console.warn(err); + } + } + } + return subject.subscribe(subscriber); } - if (meridiem === '凌晨' || meridiem === '早上' || - meridiem === '上午') { - return hour; - } else if (meridiem === '下午' || meridiem === '晚上') { - return hour + 12; - } else { - // '中午' - return hour >= 11 ? hour : hour + 12; + else { + return scheduler.schedule(dispatch, 0, { params: params, subscriber: subscriber, context: context }); } - }, - meridiem : function (hour, minute, isLower) { - var hm = hour * 100 + minute; - if (hm < 600) { - return '凌晨'; - } else if (hm < 900) { - return '早上'; - } else if (hm < 1130) { - return '上午'; - } else if (hm < 1230) { - return '中午'; - } else if (hm < 1800) { - return '下午'; - } else { - return '晚上'; + }); + }; +} +function dispatch(state) { + var _this = this; + var params = state.params, subscriber = state.subscriber, context = state.context; + var callbackFunc = params.callbackFunc, args = params.args, scheduler = params.scheduler; + var subject = params.subject; + if (!subject) { + subject = params.subject = new _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__["AsyncSubject"](); + var handler = function () { + var innerArgs = []; + for (var _i = 0; _i < arguments.length; _i++) { + innerArgs[_i] = arguments[_i]; } - }, - calendar : { - sameDay : '[今天]LT', - nextDay : '[明天]LT', - nextWeek : '[下]ddddLT', - lastDay : '[昨天]LT', - lastWeek : '[上]ddddLT', - sameElse : 'L' - }, - dayOfMonthOrdinalParse: /\d{1,2}(日|月|周)/, - ordinal : function (number, period) { - switch (period) { - case 'd': - case 'D': - case 'DDD': - return number + '日'; - case 'M': - return number + '月'; - case 'w': - case 'W': - return number + '周'; - default: - return number; + var err = innerArgs.shift(); + if (err) { + _this.add(scheduler.schedule(dispatchError, 0, { err: err, subject: subject })); } - }, - relativeTime : { - future : '%s内', - past : '%s前', - s : '几秒', - ss : '%d 秒', - m : '1 分钟', - mm : '%d 分钟', - h : '1 小时', - hh : '%d 小时', - d : '1 天', - dd : '%d 天', - M : '1 个月', - MM : '%d 个月', - y : '1 年', - yy : '%d 年' - }, - week : { - // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效 - dow : 1, // Monday is the first day of the week. - doy : 4 // The week that contains Jan 4th is the first week of the year. + else { + var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs; + _this.add(scheduler.schedule(dispatchNext, 0, { value: value, subject: subject })); + } + }; + try { + callbackFunc.apply(context, args.concat([handler])); } - }); - - return zhCn; - -}))); + catch (err) { + this.add(scheduler.schedule(dispatchError, 0, { err: err, subject: subject })); + } + } + this.add(subject.subscribe(subscriber)); +} +function dispatchNext(arg) { + var value = arg.value, subject = arg.subject; + subject.next(value); + subject.complete(); +} +function dispatchError(arg) { + var err = arg.err, subject = arg.subject; + subject.error(err); +} +//# sourceMappingURL=bindNodeCallback.js.map /***/ }), -/* 167 */ -/***/ (function(module, exports, __webpack_require__) { - -//! moment.js locale configuration - -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; - - - var zhHk = moment.defineLocale('zh-hk', { - months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), - monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), - weekdays : '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), - weekdaysShort : '週日_週一_週二_週三_週四_週五_週六'.split('_'), - weekdaysMin : '日_一_二_三_四_五_六'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'YYYY/MM/DD', - LL : 'YYYY年M月D日', - LLL : 'YYYY年M月D日 HH:mm', - LLLL : 'YYYY年M月D日dddd HH:mm', - l : 'YYYY/M/D', - ll : 'YYYY年M月D日', - lll : 'YYYY年M月D日 HH:mm', - llll : 'YYYY年M月D日dddd HH:mm' - }, - meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, - meridiemHour : function (hour, meridiem) { - if (hour === 12) { - hour = 0; - } - if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') { - return hour; - } else if (meridiem === '中午') { - return hour >= 11 ? hour : hour + 12; - } else if (meridiem === '下午' || meridiem === '晚上') { - return hour + 12; - } - }, - meridiem : function (hour, minute, isLower) { - var hm = hour * 100 + minute; - if (hm < 600) { - return '凌晨'; - } else if (hm < 900) { - return '早上'; - } else if (hm < 1130) { - return '上午'; - } else if (hm < 1230) { - return '中午'; - } else if (hm < 1800) { - return '下午'; - } else { - return '晚上'; - } - }, - calendar : { - sameDay : '[今天]LT', - nextDay : '[明天]LT', - nextWeek : '[下]ddddLT', - lastDay : '[昨天]LT', - lastWeek : '[上]ddddLT', - sameElse : 'L' - }, - dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/, - ordinal : function (number, period) { - switch (period) { - case 'd' : - case 'D' : - case 'DDD' : - return number + '日'; - case 'M' : - return number + '月'; - case 'w' : - case 'W' : - return number + '週'; - default : - return number; - } - }, - relativeTime : { - future : '%s內', - past : '%s前', - s : '幾秒', - ss : '%d 秒', - m : '1 分鐘', - mm : '%d 分鐘', - h : '1 小時', - hh : '%d 小時', - d : '1 天', - dd : '%d 天', - M : '1 個月', - MM : '%d 個月', - y : '1 年', - yy : '%d 年' - } - }); +/* 199 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - return zhHk; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "combineLatest", function() { return combineLatest; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CombineLatestOperator", function() { return CombineLatestOperator; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CombineLatestSubscriber", function() { return CombineLatestSubscriber; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(176); +/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(149); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(201); +/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(177); +/** PURE_IMPORTS_START tslib,_util_isScheduler,_util_isArray,_OuterSubscriber,_util_subscribeToResult,_fromArray PURE_IMPORTS_END */ -}))); -/***/ }), -/* 168 */ -/***/ (function(module, exports, __webpack_require__) { -//! moment.js locale configuration -;(function (global, factory) { - true ? factory(__webpack_require__(40)) : - undefined -}(this, (function (moment) { 'use strict'; +var NONE = {}; +function combineLatest() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; + } + var resultSelector = null; + var scheduler = null; + if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_1__["isScheduler"])(observables[observables.length - 1])) { + scheduler = observables.pop(); + } + if (typeof observables[observables.length - 1] === 'function') { + resultSelector = observables.pop(); + } + if (observables.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_2__["isArray"])(observables[0])) { + observables = observables[0]; + } + return Object(_fromArray__WEBPACK_IMPORTED_MODULE_5__["fromArray"])(observables, scheduler).lift(new CombineLatestOperator(resultSelector)); +} +var CombineLatestOperator = /*@__PURE__*/ (function () { + function CombineLatestOperator(resultSelector) { + this.resultSelector = resultSelector; + } + CombineLatestOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new CombineLatestSubscriber(subscriber, this.resultSelector)); + }; + return CombineLatestOperator; +}()); - var zhTw = moment.defineLocale('zh-tw', { - months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), - monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), - weekdays : '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), - weekdaysShort : '週日_週一_週二_週三_週四_週五_週六'.split('_'), - weekdaysMin : '日_一_二_三_四_五_六'.split('_'), - longDateFormat : { - LT : 'HH:mm', - LTS : 'HH:mm:ss', - L : 'YYYY/MM/DD', - LL : 'YYYY年M月D日', - LLL : 'YYYY年M月D日 HH:mm', - LLLL : 'YYYY年M月D日dddd HH:mm', - l : 'YYYY/M/D', - ll : 'YYYY年M月D日', - lll : 'YYYY年M月D日 HH:mm', - llll : 'YYYY年M月D日dddd HH:mm' - }, - meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, - meridiemHour : function (hour, meridiem) { - if (hour === 12) { - hour = 0; - } - if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') { - return hour; - } else if (meridiem === '中午') { - return hour >= 11 ? hour : hour + 12; - } else if (meridiem === '下午' || meridiem === '晚上') { - return hour + 12; +var CombineLatestSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CombineLatestSubscriber, _super); + function CombineLatestSubscriber(destination, resultSelector) { + var _this = _super.call(this, destination) || this; + _this.resultSelector = resultSelector; + _this.active = 0; + _this.values = []; + _this.observables = []; + return _this; + } + CombineLatestSubscriber.prototype._next = function (observable) { + this.values.push(NONE); + this.observables.push(observable); + }; + CombineLatestSubscriber.prototype._complete = function () { + var observables = this.observables; + var len = observables.length; + if (len === 0) { + this.destination.complete(); + } + else { + this.active = len; + this.toRespond = len; + for (var i = 0; i < len; i++) { + var observable = observables[i]; + this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__["subscribeToResult"])(this, observable, observable, i)); } - }, - meridiem : function (hour, minute, isLower) { - var hm = hour * 100 + minute; - if (hm < 600) { - return '凌晨'; - } else if (hm < 900) { - return '早上'; - } else if (hm < 1130) { - return '上午'; - } else if (hm < 1230) { - return '中午'; - } else if (hm < 1800) { - return '下午'; - } else { - return '晚上'; + } + }; + CombineLatestSubscriber.prototype.notifyComplete = function (unused) { + if ((this.active -= 1) === 0) { + this.destination.complete(); + } + }; + CombineLatestSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + var values = this.values; + var oldVal = values[outerIndex]; + var toRespond = !this.toRespond + ? 0 + : oldVal === NONE ? --this.toRespond : this.toRespond; + values[outerIndex] = innerValue; + if (toRespond === 0) { + if (this.resultSelector) { + this._tryResultSelector(values); } - }, - calendar : { - sameDay : '[今天] LT', - nextDay : '[明天] LT', - nextWeek : '[下]dddd LT', - lastDay : '[昨天] LT', - lastWeek : '[上]dddd LT', - sameElse : 'L' - }, - dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/, - ordinal : function (number, period) { - switch (period) { - case 'd' : - case 'D' : - case 'DDD' : - return number + '日'; - case 'M' : - return number + '月'; - case 'w' : - case 'W' : - return number + '週'; - default : - return number; + else { + this.destination.next(values.slice()); } - }, - relativeTime : { - future : '%s內', - past : '%s前', - s : '幾秒', - ss : '%d 秒', - m : '1 分鐘', - mm : '%d 分鐘', - h : '1 小時', - hh : '%d 小時', - d : '1 天', - dd : '%d 天', - M : '1 個月', - MM : '%d 個月', - y : '1 年', - yy : '%d 年' } - }); - - return zhTw; + }; + CombineLatestSubscriber.prototype._tryResultSelector = function (values) { + var result; + try { + result = this.resultSelector.apply(this, values); + } + catch (err) { + this.destination.error(err); + return; + } + this.destination.next(result); + }; + return CombineLatestSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__["OuterSubscriber"])); -}))); +//# sourceMappingURL=combineLatest.js.map /***/ }), -/* 169 */ +/* 200 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony import */ var _internal_Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Observable", function() { return _internal_Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]; }); - -/* harmony import */ var _internal_observable_ConnectableObservable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(186); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ConnectableObservable", function() { return _internal_observable_ConnectableObservable__WEBPACK_IMPORTED_MODULE_1__["ConnectableObservable"]; }); - -/* harmony import */ var _internal_operators_groupBy__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(191); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GroupedObservable", function() { return _internal_operators_groupBy__WEBPACK_IMPORTED_MODULE_2__["GroupedObservable"]; }); - -/* harmony import */ var _internal_symbol_observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(183); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "observable", function() { return _internal_symbol_observable__WEBPACK_IMPORTED_MODULE_3__["observable"]; }); - -/* harmony import */ var _internal_Subject__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(187); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subject", function() { return _internal_Subject__WEBPACK_IMPORTED_MODULE_4__["Subject"]; }); - -/* harmony import */ var _internal_BehaviorSubject__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(192); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BehaviorSubject", function() { return _internal_BehaviorSubject__WEBPACK_IMPORTED_MODULE_5__["BehaviorSubject"]; }); - -/* harmony import */ var _internal_ReplaySubject__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(193); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReplaySubject", function() { return _internal_ReplaySubject__WEBPACK_IMPORTED_MODULE_6__["ReplaySubject"]; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OuterSubscriber", function() { return OuterSubscriber; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -/* harmony import */ var _internal_AsyncSubject__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(210); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AsyncSubject", function() { return _internal_AsyncSubject__WEBPACK_IMPORTED_MODULE_7__["AsyncSubject"]; }); -/* harmony import */ var _internal_scheduler_asap__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(211); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "asapScheduler", function() { return _internal_scheduler_asap__WEBPACK_IMPORTED_MODULE_8__["asap"]; }); +var OuterSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](OuterSubscriber, _super); + function OuterSubscriber() { + return _super !== null && _super.apply(this, arguments) || this; + } + OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.destination.next(innerValue); + }; + OuterSubscriber.prototype.notifyError = function (error, innerSub) { + this.destination.error(error); + }; + OuterSubscriber.prototype.notifyComplete = function (innerSub) { + this.destination.complete(); + }; + return OuterSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -/* harmony import */ var _internal_scheduler_async__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(215); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "asyncScheduler", function() { return _internal_scheduler_async__WEBPACK_IMPORTED_MODULE_9__["async"]; }); +//# sourceMappingURL=OuterSubscriber.js.map -/* harmony import */ var _internal_scheduler_queue__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(194); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "queueScheduler", function() { return _internal_scheduler_queue__WEBPACK_IMPORTED_MODULE_10__["queue"]; }); -/* harmony import */ var _internal_scheduler_animationFrame__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(216); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "animationFrameScheduler", function() { return _internal_scheduler_animationFrame__WEBPACK_IMPORTED_MODULE_11__["animationFrame"]; }); +/***/ }), +/* 201 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -/* harmony import */ var _internal_scheduler_VirtualTimeScheduler__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(219); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VirtualTimeScheduler", function() { return _internal_scheduler_VirtualTimeScheduler__WEBPACK_IMPORTED_MODULE_12__["VirtualTimeScheduler"]; }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeToResult", function() { return subscribeToResult; }); +/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(202); +/* harmony import */ var _subscribeTo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(203); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(141); +/** PURE_IMPORTS_START _InnerSubscriber,_subscribeTo,_Observable PURE_IMPORTS_END */ -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VirtualAction", function() { return _internal_scheduler_VirtualTimeScheduler__WEBPACK_IMPORTED_MODULE_12__["VirtualAction"]; }); -/* harmony import */ var _internal_Scheduler__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(200); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Scheduler", function() { return _internal_Scheduler__WEBPACK_IMPORTED_MODULE_13__["Scheduler"]; }); -/* harmony import */ var _internal_Subscription__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(177); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subscription", function() { return _internal_Subscription__WEBPACK_IMPORTED_MODULE_14__["Subscription"]; }); +function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, destination) { + if (destination === void 0) { + destination = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_0__["InnerSubscriber"](outerSubscriber, outerValue, outerIndex); + } + if (destination.closed) { + return undefined; + } + if (result instanceof _Observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]) { + return result.subscribe(destination); + } + return Object(_subscribeTo__WEBPACK_IMPORTED_MODULE_1__["subscribeTo"])(result)(destination); +} +//# sourceMappingURL=subscribeToResult.js.map -/* harmony import */ var _internal_Subscriber__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(172); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subscriber", function() { return _internal_Subscriber__WEBPACK_IMPORTED_MODULE_15__["Subscriber"]; }); -/* harmony import */ var _internal_Notification__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(202); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Notification", function() { return _internal_Notification__WEBPACK_IMPORTED_MODULE_16__["Notification"]; }); +/***/ }), +/* 202 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotificationKind", function() { return _internal_Notification__WEBPACK_IMPORTED_MODULE_16__["NotificationKind"]; }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InnerSubscriber", function() { return InnerSubscriber; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -/* harmony import */ var _internal_util_pipe__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(184); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "pipe", function() { return _internal_util_pipe__WEBPACK_IMPORTED_MODULE_17__["pipe"]; }); -/* harmony import */ var _internal_util_noop__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(185); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "noop", function() { return _internal_util_noop__WEBPACK_IMPORTED_MODULE_18__["noop"]; }); +var InnerSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](InnerSubscriber, _super); + function InnerSubscriber(parent, outerValue, outerIndex) { + var _this = _super.call(this) || this; + _this.parent = parent; + _this.outerValue = outerValue; + _this.outerIndex = outerIndex; + _this.index = 0; + return _this; + } + InnerSubscriber.prototype._next = function (value) { + this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this); + }; + InnerSubscriber.prototype._error = function (error) { + this.parent.notifyError(error, this); + this.unsubscribe(); + }; + InnerSubscriber.prototype._complete = function () { + this.parent.notifyComplete(this); + this.unsubscribe(); + }; + return InnerSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -/* harmony import */ var _internal_util_identity__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(220); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "identity", function() { return _internal_util_identity__WEBPACK_IMPORTED_MODULE_19__["identity"]; }); +//# sourceMappingURL=InnerSubscriber.js.map -/* harmony import */ var _internal_util_isObservable__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(221); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isObservable", function() { return _internal_util_isObservable__WEBPACK_IMPORTED_MODULE_20__["isObservable"]; }); -/* harmony import */ var _internal_util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(222); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArgumentOutOfRangeError", function() { return _internal_util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_21__["ArgumentOutOfRangeError"]; }); +/***/ }), +/* 203 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -/* harmony import */ var _internal_util_EmptyError__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(223); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EmptyError", function() { return _internal_util_EmptyError__WEBPACK_IMPORTED_MODULE_22__["EmptyError"]; }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeTo", function() { return subscribeTo; }); +/* harmony import */ var _subscribeToArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(178); +/* harmony import */ var _subscribeToPromise__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(204); +/* harmony import */ var _subscribeToIterable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(205); +/* harmony import */ var _subscribeToObservable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(207); +/* harmony import */ var _isArrayLike__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(208); +/* harmony import */ var _isPromise__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(209); +/* harmony import */ var _isObject__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(150); +/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(206); +/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(154); +/** PURE_IMPORTS_START _subscribeToArray,_subscribeToPromise,_subscribeToIterable,_subscribeToObservable,_isArrayLike,_isPromise,_isObject,_symbol_iterator,_symbol_observable PURE_IMPORTS_END */ -/* harmony import */ var _internal_util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(188); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ObjectUnsubscribedError", function() { return _internal_util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_23__["ObjectUnsubscribedError"]; }); -/* harmony import */ var _internal_util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(180); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UnsubscriptionError", function() { return _internal_util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_24__["UnsubscriptionError"]; }); -/* harmony import */ var _internal_util_TimeoutError__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(224); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TimeoutError", function() { return _internal_util_TimeoutError__WEBPACK_IMPORTED_MODULE_25__["TimeoutError"]; }); -/* harmony import */ var _internal_observable_bindCallback__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(225); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bindCallback", function() { return _internal_observable_bindCallback__WEBPACK_IMPORTED_MODULE_26__["bindCallback"]; }); -/* harmony import */ var _internal_observable_bindNodeCallback__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(227); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bindNodeCallback", function() { return _internal_observable_bindNodeCallback__WEBPACK_IMPORTED_MODULE_27__["bindNodeCallback"]; }); -/* harmony import */ var _internal_observable_combineLatest__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(228); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "combineLatest", function() { return _internal_observable_combineLatest__WEBPACK_IMPORTED_MODULE_28__["combineLatest"]; }); -/* harmony import */ var _internal_observable_concat__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(239); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "concat", function() { return _internal_observable_concat__WEBPACK_IMPORTED_MODULE_29__["concat"]; }); -/* harmony import */ var _internal_observable_defer__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(250); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defer", function() { return _internal_observable_defer__WEBPACK_IMPORTED_MODULE_30__["defer"]; }); -/* harmony import */ var _internal_observable_empty__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(203); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "empty", function() { return _internal_observable_empty__WEBPACK_IMPORTED_MODULE_31__["empty"]; }); - -/* harmony import */ var _internal_observable_forkJoin__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(251); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "forkJoin", function() { return _internal_observable_forkJoin__WEBPACK_IMPORTED_MODULE_32__["forkJoin"]; }); - -/* harmony import */ var _internal_observable_from__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(243); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "from", function() { return _internal_observable_from__WEBPACK_IMPORTED_MODULE_33__["from"]; }); - -/* harmony import */ var _internal_observable_fromEvent__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(252); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fromEvent", function() { return _internal_observable_fromEvent__WEBPACK_IMPORTED_MODULE_34__["fromEvent"]; }); - -/* harmony import */ var _internal_observable_fromEventPattern__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(253); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fromEventPattern", function() { return _internal_observable_fromEventPattern__WEBPACK_IMPORTED_MODULE_35__["fromEventPattern"]; }); - -/* harmony import */ var _internal_observable_generate__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(254); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "generate", function() { return _internal_observable_generate__WEBPACK_IMPORTED_MODULE_36__["generate"]; }); - -/* harmony import */ var _internal_observable_iif__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(255); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "iif", function() { return _internal_observable_iif__WEBPACK_IMPORTED_MODULE_37__["iif"]; }); - -/* harmony import */ var _internal_observable_interval__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(256); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "interval", function() { return _internal_observable_interval__WEBPACK_IMPORTED_MODULE_38__["interval"]; }); - -/* harmony import */ var _internal_observable_merge__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(258); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "merge", function() { return _internal_observable_merge__WEBPACK_IMPORTED_MODULE_39__["merge"]; }); - -/* harmony import */ var _internal_observable_never__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(259); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "never", function() { return _internal_observable_never__WEBPACK_IMPORTED_MODULE_40__["never"]; }); - -/* harmony import */ var _internal_observable_of__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(204); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "of", function() { return _internal_observable_of__WEBPACK_IMPORTED_MODULE_41__["of"]; }); - -/* harmony import */ var _internal_observable_onErrorResumeNext__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(260); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "onErrorResumeNext", function() { return _internal_observable_onErrorResumeNext__WEBPACK_IMPORTED_MODULE_42__["onErrorResumeNext"]; }); - -/* harmony import */ var _internal_observable_pairs__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(261); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "pairs", function() { return _internal_observable_pairs__WEBPACK_IMPORTED_MODULE_43__["pairs"]; }); - -/* harmony import */ var _internal_observable_partition__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(262); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "partition", function() { return _internal_observable_partition__WEBPACK_IMPORTED_MODULE_44__["partition"]; }); +var subscribeTo = function (result) { + if (!!result && typeof result[_symbol_observable__WEBPACK_IMPORTED_MODULE_8__["observable"]] === 'function') { + return Object(_subscribeToObservable__WEBPACK_IMPORTED_MODULE_3__["subscribeToObservable"])(result); + } + else if (Object(_isArrayLike__WEBPACK_IMPORTED_MODULE_4__["isArrayLike"])(result)) { + return Object(_subscribeToArray__WEBPACK_IMPORTED_MODULE_0__["subscribeToArray"])(result); + } + else if (Object(_isPromise__WEBPACK_IMPORTED_MODULE_5__["isPromise"])(result)) { + return Object(_subscribeToPromise__WEBPACK_IMPORTED_MODULE_1__["subscribeToPromise"])(result); + } + else if (!!result && typeof result[_symbol_iterator__WEBPACK_IMPORTED_MODULE_7__["iterator"]] === 'function') { + return Object(_subscribeToIterable__WEBPACK_IMPORTED_MODULE_2__["subscribeToIterable"])(result); + } + else { + var value = Object(_isObject__WEBPACK_IMPORTED_MODULE_6__["isObject"])(result) ? 'an invalid object' : "'" + result + "'"; + var msg = "You provided " + value + " where a stream was expected." + + ' You can provide an Observable, Promise, Array, or Iterable.'; + throw new TypeError(msg); + } +}; +//# sourceMappingURL=subscribeTo.js.map -/* harmony import */ var _internal_observable_race__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(265); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "race", function() { return _internal_observable_race__WEBPACK_IMPORTED_MODULE_45__["race"]; }); -/* harmony import */ var _internal_observable_range__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(266); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "range", function() { return _internal_observable_range__WEBPACK_IMPORTED_MODULE_46__["range"]; }); +/***/ }), +/* 204 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -/* harmony import */ var _internal_observable_throwError__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(209); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "throwError", function() { return _internal_observable_throwError__WEBPACK_IMPORTED_MODULE_47__["throwError"]; }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeToPromise", function() { return subscribeToPromise; }); +/* harmony import */ var _hostReportError__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(147); +/** PURE_IMPORTS_START _hostReportError PURE_IMPORTS_END */ -/* harmony import */ var _internal_observable_timer__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(267); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "timer", function() { return _internal_observable_timer__WEBPACK_IMPORTED_MODULE_48__["timer"]; }); +var subscribeToPromise = function (promise) { + return function (subscriber) { + promise.then(function (value) { + if (!subscriber.closed) { + subscriber.next(value); + subscriber.complete(); + } + }, function (err) { return subscriber.error(err); }) + .then(null, _hostReportError__WEBPACK_IMPORTED_MODULE_0__["hostReportError"]); + return subscriber; + }; +}; +//# sourceMappingURL=subscribeToPromise.js.map -/* harmony import */ var _internal_observable_using__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(268); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "using", function() { return _internal_observable_using__WEBPACK_IMPORTED_MODULE_49__["using"]; }); -/* harmony import */ var _internal_observable_zip__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(269); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "zip", function() { return _internal_observable_zip__WEBPACK_IMPORTED_MODULE_50__["zip"]; }); +/***/ }), +/* 205 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -/* harmony import */ var _internal_scheduled_scheduled__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(244); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "scheduled", function() { return _internal_scheduled_scheduled__WEBPACK_IMPORTED_MODULE_51__["scheduled"]; }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeToIterable", function() { return subscribeToIterable; }); +/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(206); +/** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */ -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EMPTY", function() { return _internal_observable_empty__WEBPACK_IMPORTED_MODULE_31__["EMPTY"]; }); +var subscribeToIterable = function (iterable) { + return function (subscriber) { + var iterator = iterable[_symbol_iterator__WEBPACK_IMPORTED_MODULE_0__["iterator"]](); + do { + var item = iterator.next(); + if (item.done) { + subscriber.complete(); + break; + } + subscriber.next(item.value); + if (subscriber.closed) { + break; + } + } while (true); + if (typeof iterator.return === 'function') { + subscriber.add(function () { + if (iterator.return) { + iterator.return(); + } + }); + } + return subscriber; + }; +}; +//# sourceMappingURL=subscribeToIterable.js.map -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NEVER", function() { return _internal_observable_never__WEBPACK_IMPORTED_MODULE_40__["NEVER"]; }); -/* harmony import */ var _internal_config__WEBPACK_IMPORTED_MODULE_52__ = __webpack_require__(175); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "config", function() { return _internal_config__WEBPACK_IMPORTED_MODULE_52__["config"]; }); +/***/ }), +/* 206 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getSymbolIterator", function() { return getSymbolIterator; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "iterator", function() { return iterator; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "$$iterator", function() { return $$iterator; }); /** PURE_IMPORTS_START PURE_IMPORTS_END */ +function getSymbolIterator() { + if (typeof Symbol !== 'function' || !Symbol.iterator) { + return '@@iterator'; + } + return Symbol.iterator; +} +var iterator = /*@__PURE__*/ getSymbolIterator(); +var $$iterator = iterator; +//# sourceMappingURL=iterator.js.map +/***/ }), +/* 207 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeToObservable", function() { return subscribeToObservable; }); +/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(154); +/** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */ +var subscribeToObservable = function (obj) { + return function (subscriber) { + var obs = obj[_symbol_observable__WEBPACK_IMPORTED_MODULE_0__["observable"]](); + if (typeof obs.subscribe !== 'function') { + throw new TypeError('Provided object does not correctly implement Symbol.observable'); + } + else { + return obs.subscribe(subscriber); + } + }; +}; +//# sourceMappingURL=subscribeToObservable.js.map +/***/ }), +/* 208 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isArrayLike", function() { return isArrayLike; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; }); +//# sourceMappingURL=isArrayLike.js.map +/***/ }), +/* 209 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPromise", function() { return isPromise; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function isPromise(value) { + return !!value && typeof value.subscribe !== 'function' && typeof value.then === 'function'; +} +//# sourceMappingURL=isPromise.js.map +/***/ }), +/* 210 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat", function() { return concat; }); +/* harmony import */ var _of__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(175); +/* harmony import */ var _operators_concatAll__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(211); +/** PURE_IMPORTS_START _of,_operators_concatAll PURE_IMPORTS_END */ +function concat() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; + } + return Object(_operators_concatAll__WEBPACK_IMPORTED_MODULE_1__["concatAll"])()(_of__WEBPACK_IMPORTED_MODULE_0__["of"].apply(void 0, observables)); +} +//# sourceMappingURL=concat.js.map +/***/ }), +/* 211 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concatAll", function() { return concatAll; }); +/* harmony import */ var _mergeAll__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(212); +/** PURE_IMPORTS_START _mergeAll PURE_IMPORTS_END */ +function concatAll() { + return Object(_mergeAll__WEBPACK_IMPORTED_MODULE_0__["mergeAll"])(1); +} +//# sourceMappingURL=concatAll.js.map +/***/ }), +/* 212 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeAll", function() { return mergeAll; }); +/* harmony import */ var _mergeMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(213); +/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(191); +/** PURE_IMPORTS_START _mergeMap,_util_identity PURE_IMPORTS_END */ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//# sourceMappingURL=index.js.map +function mergeAll(concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + return Object(_mergeMap__WEBPACK_IMPORTED_MODULE_0__["mergeMap"])(_util_identity__WEBPACK_IMPORTED_MODULE_1__["identity"], concurrent); +} +//# sourceMappingURL=mergeAll.js.map /***/ }), -/* 170 */ +/* 213 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Observable", function() { return Observable; }); -/* harmony import */ var _util_canReportError__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(171); -/* harmony import */ var _util_toSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(182); -/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(183); -/* harmony import */ var _util_pipe__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(184); -/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(175); -/** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeMap", function() { return mergeMap; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MergeMapOperator", function() { return MergeMapOperator; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MergeMapSubscriber", function() { return MergeMapSubscriber; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(201); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(200); +/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(202); +/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(197); +/* harmony import */ var _observable_from__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(214); +/** PURE_IMPORTS_START tslib,_util_subscribeToResult,_OuterSubscriber,_InnerSubscriber,_map,_observable_from PURE_IMPORTS_END */ -var Observable = /*@__PURE__*/ (function () { - function Observable(subscribe) { - this._isScalar = false; - if (subscribe) { - this._subscribe = subscribe; + +function mergeMap(project, resultSelector, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + if (typeof resultSelector === 'function') { + return function (source) { return source.pipe(mergeMap(function (a, i) { return Object(_observable_from__WEBPACK_IMPORTED_MODULE_5__["from"])(project(a, i)).pipe(Object(_map__WEBPACK_IMPORTED_MODULE_4__["map"])(function (b, ii) { return resultSelector(a, b, i, ii); })); }, concurrent)); }; + } + else if (typeof resultSelector === 'number') { + concurrent = resultSelector; + } + return function (source) { return source.lift(new MergeMapOperator(project, concurrent)); }; +} +var MergeMapOperator = /*@__PURE__*/ (function () { + function MergeMapOperator(project, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; } + this.project = project; + this.concurrent = concurrent; } - Observable.prototype.lift = function (operator) { - var observable = new Observable(); - observable.source = this; - observable.operator = operator; - return observable; + MergeMapOperator.prototype.call = function (observer, source) { + return source.subscribe(new MergeMapSubscriber(observer, this.project, this.concurrent)); }; - Observable.prototype.subscribe = function (observerOrNext, error, complete) { - var operator = this.operator; - var sink = Object(_util_toSubscriber__WEBPACK_IMPORTED_MODULE_1__["toSubscriber"])(observerOrNext, error, complete); - if (operator) { - sink.add(operator.call(sink, this.source)); + return MergeMapOperator; +}()); + +var MergeMapSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MergeMapSubscriber, _super); + function MergeMapSubscriber(destination, project, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; } - else { - sink.add(this.source || (_config__WEBPACK_IMPORTED_MODULE_4__["config"].useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ? - this._subscribe(sink) : - this._trySubscribe(sink)); + var _this = _super.call(this, destination) || this; + _this.project = project; + _this.concurrent = concurrent; + _this.hasCompleted = false; + _this.buffer = []; + _this.active = 0; + _this.index = 0; + return _this; + } + MergeMapSubscriber.prototype._next = function (value) { + if (this.active < this.concurrent) { + this._tryNext(value); } - if (_config__WEBPACK_IMPORTED_MODULE_4__["config"].useDeprecatedSynchronousErrorHandling) { - if (sink.syncErrorThrowable) { - sink.syncErrorThrowable = false; - if (sink.syncErrorThrown) { - throw sink.syncErrorValue; - } - } + else { + this.buffer.push(value); } - return sink; }; - Observable.prototype._trySubscribe = function (sink) { + MergeMapSubscriber.prototype._tryNext = function (value) { + var result; + var index = this.index++; try { - return this._subscribe(sink); + result = this.project(value, index); } catch (err) { - if (_config__WEBPACK_IMPORTED_MODULE_4__["config"].useDeprecatedSynchronousErrorHandling) { - sink.syncErrorThrown = true; - sink.syncErrorValue = err; - } - if (Object(_util_canReportError__WEBPACK_IMPORTED_MODULE_0__["canReportError"])(sink)) { - sink.error(err); - } - else { - console.warn(err); - } + this.destination.error(err); + return; } + this.active++; + this._innerSub(result, value, index); }; - Observable.prototype.forEach = function (next, promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function (resolve, reject) { - var subscription; - subscription = _this.subscribe(function (value) { - try { - next(value); - } - catch (err) { - reject(err); - if (subscription) { - subscription.unsubscribe(); - } - } - }, reject, resolve); - }); + MergeMapSubscriber.prototype._innerSub = function (ish, value, index) { + var innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_3__["InnerSubscriber"](this, undefined, undefined); + var destination = this.destination; + destination.add(innerSubscriber); + Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__["subscribeToResult"])(this, ish, value, index, innerSubscriber); }; - Observable.prototype._subscribe = function (subscriber) { - var source = this.source; - return source && source.subscribe(subscriber); + MergeMapSubscriber.prototype._complete = function () { + this.hasCompleted = true; + if (this.active === 0 && this.buffer.length === 0) { + this.destination.complete(); + } + this.unsubscribe(); }; - Observable.prototype[_symbol_observable__WEBPACK_IMPORTED_MODULE_2__["observable"]] = function () { - return this; + MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.destination.next(innerValue); }; - Observable.prototype.pipe = function () { - var operations = []; - for (var _i = 0; _i < arguments.length; _i++) { - operations[_i] = arguments[_i]; + MergeMapSubscriber.prototype.notifyComplete = function (innerSub) { + var buffer = this.buffer; + this.remove(innerSub); + this.active--; + if (buffer.length > 0) { + this._next(buffer.shift()); } - if (operations.length === 0) { - return this; + else if (this.active === 0 && this.hasCompleted) { + this.destination.complete(); } - return Object(_util_pipe__WEBPACK_IMPORTED_MODULE_3__["pipeFromArray"])(operations)(this); - }; - Observable.prototype.toPromise = function (promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function (resolve, reject) { - var value; - _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); }); - }); - }; - Observable.create = function (subscribe) { - return new Observable(subscribe); }; - return Observable; -}()); + return MergeMapSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"])); -function getPromiseCtor(promiseCtor) { - if (!promiseCtor) { - promiseCtor = _config__WEBPACK_IMPORTED_MODULE_4__["config"].Promise || Promise; +//# sourceMappingURL=mergeMap.js.map + + +/***/ }), +/* 214 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "from", function() { return from; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _util_subscribeTo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(203); +/* harmony import */ var _scheduled_scheduled__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(215); +/** PURE_IMPORTS_START _Observable,_util_subscribeTo,_scheduled_scheduled PURE_IMPORTS_END */ + + + +function from(input, scheduler) { + if (!scheduler) { + if (input instanceof _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]) { + return input; + } + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](Object(_util_subscribeTo__WEBPACK_IMPORTED_MODULE_1__["subscribeTo"])(input)); } - if (!promiseCtor) { - throw new Error('no Promise impl found'); + else { + return Object(_scheduled_scheduled__WEBPACK_IMPORTED_MODULE_2__["scheduled"])(input, scheduler); } - return promiseCtor; } -//# sourceMappingURL=Observable.js.map +//# sourceMappingURL=from.js.map /***/ }), -/* 171 */ +/* 215 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canReportError", function() { return canReportError; }); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(172); -/** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scheduled", function() { return scheduled; }); +/* harmony import */ var _scheduleObservable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(216); +/* harmony import */ var _schedulePromise__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(217); +/* harmony import */ var _scheduleArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(179); +/* harmony import */ var _scheduleIterable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(218); +/* harmony import */ var _util_isInteropObservable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(219); +/* harmony import */ var _util_isPromise__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(209); +/* harmony import */ var _util_isArrayLike__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(208); +/* harmony import */ var _util_isIterable__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(220); +/** PURE_IMPORTS_START _scheduleObservable,_schedulePromise,_scheduleArray,_scheduleIterable,_util_isInteropObservable,_util_isPromise,_util_isArrayLike,_util_isIterable PURE_IMPORTS_END */ -function canReportError(observer) { - while (observer) { - var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped; - if (closed_1 || isStopped) { - return false; + + + + + + + +function scheduled(input, scheduler) { + if (input != null) { + if (Object(_util_isInteropObservable__WEBPACK_IMPORTED_MODULE_4__["isInteropObservable"])(input)) { + return Object(_scheduleObservable__WEBPACK_IMPORTED_MODULE_0__["scheduleObservable"])(input, scheduler); } - else if (destination && destination instanceof _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"]) { - observer = destination; + else if (Object(_util_isPromise__WEBPACK_IMPORTED_MODULE_5__["isPromise"])(input)) { + return Object(_schedulePromise__WEBPACK_IMPORTED_MODULE_1__["schedulePromise"])(input, scheduler); } - else { - observer = null; + else if (Object(_util_isArrayLike__WEBPACK_IMPORTED_MODULE_6__["isArrayLike"])(input)) { + return Object(_scheduleArray__WEBPACK_IMPORTED_MODULE_2__["scheduleArray"])(input, scheduler); + } + else if (Object(_util_isIterable__WEBPACK_IMPORTED_MODULE_7__["isIterable"])(input) || typeof input === 'string') { + return Object(_scheduleIterable__WEBPACK_IMPORTED_MODULE_3__["scheduleIterable"])(input, scheduler); } } - return true; + throw new TypeError((input !== null && typeof input || input) + ' is not observable'); } -//# sourceMappingURL=canReportError.js.map +//# sourceMappingURL=scheduled.js.map /***/ }), -/* 172 */ +/* 216 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Subscriber", function() { return Subscriber; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SafeSubscriber", function() { return SafeSubscriber; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(173); -/* harmony import */ var _Observer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(174); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(177); -/* harmony import */ var _internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(181); -/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(175); -/* harmony import */ var _util_hostReportError__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(176); -/** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scheduleObservable", function() { return scheduleObservable; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(148); +/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(154); +/** PURE_IMPORTS_START _Observable,_Subscription,_symbol_observable PURE_IMPORTS_END */ +function scheduleObservable(input, scheduler) { + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { + var sub = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"](); + sub.add(scheduler.schedule(function () { + var observable = input[_symbol_observable__WEBPACK_IMPORTED_MODULE_2__["observable"]](); + sub.add(observable.subscribe({ + next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); }, + error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); }, + complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); }, + })); + })); + return sub; + }); +} +//# sourceMappingURL=scheduleObservable.js.map +/***/ }), +/* 217 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "schedulePromise", function() { return schedulePromise; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(148); +/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ -var Subscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Subscriber, _super); - function Subscriber(destinationOrNext, error, complete) { - var _this = _super.call(this) || this; - _this.syncErrorValue = null; - _this.syncErrorThrown = false; - _this.syncErrorThrowable = false; - _this.isStopped = false; - switch (arguments.length) { - case 0: - _this.destination = _Observer__WEBPACK_IMPORTED_MODULE_2__["empty"]; - break; - case 1: - if (!destinationOrNext) { - _this.destination = _Observer__WEBPACK_IMPORTED_MODULE_2__["empty"]; - break; - } - if (typeof destinationOrNext === 'object') { - if (destinationOrNext instanceof Subscriber) { - _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable; - _this.destination = destinationOrNext; - destinationOrNext.add(_this); - } - else { - _this.syncErrorThrowable = true; - _this.destination = new SafeSubscriber(_this, destinationOrNext); - } - break; - } - default: - _this.syncErrorThrowable = true; - _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete); - break; - } - return _this; - } - Subscriber.prototype[_internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_4__["rxSubscriber"]] = function () { return this; }; - Subscriber.create = function (next, error, complete) { - var subscriber = new Subscriber(next, error, complete); - subscriber.syncErrorThrowable = false; - return subscriber; - }; - Subscriber.prototype.next = function (value) { - if (!this.isStopped) { - this._next(value); - } - }; - Subscriber.prototype.error = function (err) { - if (!this.isStopped) { - this.isStopped = true; - this._error(err); - } - }; - Subscriber.prototype.complete = function () { - if (!this.isStopped) { - this.isStopped = true; - this._complete(); - } - }; - Subscriber.prototype.unsubscribe = function () { - if (this.closed) { - return; - } - this.isStopped = true; - _super.prototype.unsubscribe.call(this); - }; - Subscriber.prototype._next = function (value) { - this.destination.next(value); - }; - Subscriber.prototype._error = function (err) { - this.destination.error(err); - this.unsubscribe(); - }; - Subscriber.prototype._complete = function () { - this.destination.complete(); - this.unsubscribe(); - }; - Subscriber.prototype._unsubscribeAndRecycle = function () { - var _parentOrParents = this._parentOrParents; - this._parentOrParents = null; - this.unsubscribe(); - this.closed = false; - this.isStopped = false; - this._parentOrParents = _parentOrParents; - return this; - }; - return Subscriber; -}(_Subscription__WEBPACK_IMPORTED_MODULE_3__["Subscription"])); -var SafeSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SafeSubscriber, _super); - function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) { - var _this = _super.call(this) || this; - _this._parentSubscriber = _parentSubscriber; - var next; - var context = _this; - if (Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_1__["isFunction"])(observerOrNext)) { - next = observerOrNext; - } - else if (observerOrNext) { - next = observerOrNext.next; - error = observerOrNext.error; - complete = observerOrNext.complete; - if (observerOrNext !== _Observer__WEBPACK_IMPORTED_MODULE_2__["empty"]) { - context = Object.create(observerOrNext); - if (Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_1__["isFunction"])(context.unsubscribe)) { - _this.add(context.unsubscribe.bind(context)); - } - context.unsubscribe = _this.unsubscribe.bind(_this); - } - } - _this._context = context; - _this._next = next; - _this._error = error; - _this._complete = complete; - return _this; +function schedulePromise(input, scheduler) { + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { + var sub = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"](); + sub.add(scheduler.schedule(function () { + return input.then(function (value) { + sub.add(scheduler.schedule(function () { + subscriber.next(value); + sub.add(scheduler.schedule(function () { return subscriber.complete(); })); + })); + }, function (err) { + sub.add(scheduler.schedule(function () { return subscriber.error(err); })); + }); + })); + return sub; + }); +} +//# sourceMappingURL=schedulePromise.js.map + + +/***/ }), +/* 218 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scheduleIterable", function() { return scheduleIterable; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(148); +/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(206); +/** PURE_IMPORTS_START _Observable,_Subscription,_symbol_iterator PURE_IMPORTS_END */ + + + +function scheduleIterable(input, scheduler) { + if (!input) { + throw new Error('Iterable cannot be null'); } - SafeSubscriber.prototype.next = function (value) { - if (!this.isStopped && this._next) { - var _parentSubscriber = this._parentSubscriber; - if (!_config__WEBPACK_IMPORTED_MODULE_5__["config"].useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(this._next, value); - } - else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) { - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.error = function (err) { - if (!this.isStopped) { - var _parentSubscriber = this._parentSubscriber; - var useDeprecatedSynchronousErrorHandling = _config__WEBPACK_IMPORTED_MODULE_5__["config"].useDeprecatedSynchronousErrorHandling; - if (this._error) { - if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(this._error, err); - this.unsubscribe(); - } - else { - this.__tryOrSetError(_parentSubscriber, this._error, err); - this.unsubscribe(); - } + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { + var sub = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"](); + var iterator; + sub.add(function () { + if (iterator && typeof iterator.return === 'function') { + iterator.return(); } - else if (!_parentSubscriber.syncErrorThrowable) { - this.unsubscribe(); - if (useDeprecatedSynchronousErrorHandling) { - throw err; + }); + sub.add(scheduler.schedule(function () { + iterator = input[_symbol_iterator__WEBPACK_IMPORTED_MODULE_2__["iterator"]](); + sub.add(scheduler.schedule(function () { + if (subscriber.closed) { + return; } - Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_6__["hostReportError"])(err); - } - else { - if (useDeprecatedSynchronousErrorHandling) { - _parentSubscriber.syncErrorValue = err; - _parentSubscriber.syncErrorThrown = true; + var value; + var done; + try { + var result = iterator.next(); + value = result.value; + done = result.done; } - else { - Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_6__["hostReportError"])(err); + catch (err) { + subscriber.error(err); + return; } - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.complete = function () { - var _this = this; - if (!this.isStopped) { - var _parentSubscriber = this._parentSubscriber; - if (this._complete) { - var wrappedComplete = function () { return _this._complete.call(_this._context); }; - if (!_config__WEBPACK_IMPORTED_MODULE_5__["config"].useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(wrappedComplete); - this.unsubscribe(); + if (done) { + subscriber.complete(); } else { - this.__tryOrSetError(_parentSubscriber, wrappedComplete); - this.unsubscribe(); + subscriber.next(value); + this.schedule(); } - } - else { - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) { - try { - fn.call(this._context, value); - } - catch (err) { - this.unsubscribe(); - if (_config__WEBPACK_IMPORTED_MODULE_5__["config"].useDeprecatedSynchronousErrorHandling) { - throw err; - } - else { - Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_6__["hostReportError"])(err); - } - } - }; - SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) { - if (!_config__WEBPACK_IMPORTED_MODULE_5__["config"].useDeprecatedSynchronousErrorHandling) { - throw new Error('bad call'); - } - try { - fn.call(this._context, value); - } - catch (err) { - if (_config__WEBPACK_IMPORTED_MODULE_5__["config"].useDeprecatedSynchronousErrorHandling) { - parent.syncErrorValue = err; - parent.syncErrorThrown = true; - return true; - } - else { - Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_6__["hostReportError"])(err); - return true; - } - } - return false; - }; - SafeSubscriber.prototype._unsubscribe = function () { - var _parentSubscriber = this._parentSubscriber; - this._context = null; - this._parentSubscriber = null; - _parentSubscriber.unsubscribe(); - }; - return SafeSubscriber; -}(Subscriber)); + })); + })); + return sub; + }); +} +//# sourceMappingURL=scheduleIterable.js.map -//# sourceMappingURL=Subscriber.js.map + +/***/ }), +/* 219 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isInteropObservable", function() { return isInteropObservable; }); +/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(154); +/** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */ + +function isInteropObservable(input) { + return input && typeof input[_symbol_observable__WEBPACK_IMPORTED_MODULE_0__["observable"]] === 'function'; +} +//# sourceMappingURL=isInteropObservable.js.map /***/ }), -/* 173 */ +/* 220 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFunction", function() { return isFunction; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function isFunction(x) { - return typeof x === 'function'; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isIterable", function() { return isIterable; }); +/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(206); +/** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */ + +function isIterable(input) { + return input && typeof input[_symbol_iterator__WEBPACK_IMPORTED_MODULE_0__["iterator"]] === 'function'; } -//# sourceMappingURL=isFunction.js.map +//# sourceMappingURL=isIterable.js.map /***/ }), -/* 174 */ +/* 221 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "empty", function() { return empty; }); -/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(175); -/* harmony import */ var _util_hostReportError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(176); -/** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defer", function() { return defer; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(214); +/* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(174); +/** PURE_IMPORTS_START _Observable,_from,_empty PURE_IMPORTS_END */ -var empty = { - closed: true, - next: function (value) { }, - error: function (err) { - if (_config__WEBPACK_IMPORTED_MODULE_0__["config"].useDeprecatedSynchronousErrorHandling) { - throw err; + +function defer(observableFactory) { + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { + var input; + try { + input = observableFactory(); } - else { - Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_1__["hostReportError"])(err); + catch (err) { + subscriber.error(err); + return undefined; } - }, - complete: function () { } -}; -//# sourceMappingURL=Observer.js.map + var source = input ? Object(_from__WEBPACK_IMPORTED_MODULE_1__["from"])(input) : Object(_empty__WEBPACK_IMPORTED_MODULE_2__["empty"])(); + return source.subscribe(subscriber); + }); +} +//# sourceMappingURL=defer.js.map /***/ }), -/* 175 */ +/* 222 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "config", function() { return config; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var _enable_super_gross_mode_that_will_cause_bad_things = false; -var config = { - Promise: undefined, - set useDeprecatedSynchronousErrorHandling(value) { - if (value) { - var error = /*@__PURE__*/ new Error(); - /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "forkJoin", function() { return forkJoin; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(149); +/* harmony import */ var _operators_map__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(197); +/* harmony import */ var _util_isObject__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(150); +/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(214); +/** PURE_IMPORTS_START _Observable,_util_isArray,_operators_map,_util_isObject,_from PURE_IMPORTS_END */ + + + + + +function forkJoin() { + var sources = []; + for (var _i = 0; _i < arguments.length; _i++) { + sources[_i] = arguments[_i]; + } + if (sources.length === 1) { + var first_1 = sources[0]; + if (Object(_util_isArray__WEBPACK_IMPORTED_MODULE_1__["isArray"])(first_1)) { + return forkJoinInternal(first_1, null); } - else if (_enable_super_gross_mode_that_will_cause_bad_things) { - /*@__PURE__*/ console.log('RxJS: Back to a better error behavior. Thank you. <3'); + if (Object(_util_isObject__WEBPACK_IMPORTED_MODULE_3__["isObject"])(first_1) && Object.getPrototypeOf(first_1) === Object.prototype) { + var keys = Object.keys(first_1); + return forkJoinInternal(keys.map(function (key) { return first_1[key]; }), keys); } - _enable_super_gross_mode_that_will_cause_bad_things = value; - }, - get useDeprecatedSynchronousErrorHandling() { - return _enable_super_gross_mode_that_will_cause_bad_things; - }, -}; -//# sourceMappingURL=config.js.map + } + if (typeof sources[sources.length - 1] === 'function') { + var resultSelector_1 = sources.pop(); + sources = (sources.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_1__["isArray"])(sources[0])) ? sources[0] : sources; + return forkJoinInternal(sources, null).pipe(Object(_operators_map__WEBPACK_IMPORTED_MODULE_2__["map"])(function (args) { return resultSelector_1.apply(void 0, args); })); + } + return forkJoinInternal(sources, null); +} +function forkJoinInternal(sources, keys) { + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { + var len = sources.length; + if (len === 0) { + subscriber.complete(); + return; + } + var values = new Array(len); + var completed = 0; + var emitted = 0; + var _loop_1 = function (i) { + var source = Object(_from__WEBPACK_IMPORTED_MODULE_4__["from"])(sources[i]); + var hasValue = false; + subscriber.add(source.subscribe({ + next: function (value) { + if (!hasValue) { + hasValue = true; + emitted++; + } + values[i] = value; + }, + error: function (err) { return subscriber.error(err); }, + complete: function () { + completed++; + if (completed === len || !hasValue) { + if (emitted === len) { + subscriber.next(keys ? + keys.reduce(function (result, key, i) { return (result[key] = values[i], result); }, {}) : + values); + } + subscriber.complete(); + } + } + })); + }; + for (var i = 0; i < len; i++) { + _loop_1(i); + } + }); +} +//# sourceMappingURL=forkJoin.js.map /***/ }), -/* 176 */ +/* 223 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hostReportError", function() { return hostReportError; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function hostReportError(err) { - setTimeout(function () { throw err; }, 0); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromEvent", function() { return fromEvent; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(149); +/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(144); +/* harmony import */ var _operators_map__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(197); +/** PURE_IMPORTS_START _Observable,_util_isArray,_util_isFunction,_operators_map PURE_IMPORTS_END */ + + + + +var toString = /*@__PURE__*/ (function () { return Object.prototype.toString; })(); +function fromEvent(target, eventName, options, resultSelector) { + if (Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_2__["isFunction"])(options)) { + resultSelector = options; + options = undefined; + } + if (resultSelector) { + return fromEvent(target, eventName, options).pipe(Object(_operators_map__WEBPACK_IMPORTED_MODULE_3__["map"])(function (args) { return Object(_util_isArray__WEBPACK_IMPORTED_MODULE_1__["isArray"])(args) ? resultSelector.apply(void 0, args) : resultSelector(args); })); + } + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { + function handler(e) { + if (arguments.length > 1) { + subscriber.next(Array.prototype.slice.call(arguments)); + } + else { + subscriber.next(e); + } + } + setupSubscription(target, eventName, handler, subscriber, options); + }); } -//# sourceMappingURL=hostReportError.js.map +function setupSubscription(sourceObj, eventName, handler, subscriber, options) { + var unsubscribe; + if (isEventTarget(sourceObj)) { + var source_1 = sourceObj; + sourceObj.addEventListener(eventName, handler, options); + unsubscribe = function () { return source_1.removeEventListener(eventName, handler, options); }; + } + else if (isJQueryStyleEventEmitter(sourceObj)) { + var source_2 = sourceObj; + sourceObj.on(eventName, handler); + unsubscribe = function () { return source_2.off(eventName, handler); }; + } + else if (isNodeStyleEventEmitter(sourceObj)) { + var source_3 = sourceObj; + sourceObj.addListener(eventName, handler); + unsubscribe = function () { return source_3.removeListener(eventName, handler); }; + } + else if (sourceObj && sourceObj.length) { + for (var i = 0, len = sourceObj.length; i < len; i++) { + setupSubscription(sourceObj[i], eventName, handler, subscriber, options); + } + } + else { + throw new TypeError('Invalid event target'); + } + subscriber.add(unsubscribe); +} +function isNodeStyleEventEmitter(sourceObj) { + return sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function'; +} +function isJQueryStyleEventEmitter(sourceObj) { + return sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function'; +} +function isEventTarget(sourceObj) { + return sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function'; +} +//# sourceMappingURL=fromEvent.js.map /***/ }), -/* 177 */ +/* 224 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Subscription", function() { return Subscription; }); -/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(178); -/* harmony import */ var _util_isObject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(179); -/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(173); -/* harmony import */ var _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(180); -/** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromEventPattern", function() { return fromEventPattern; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(149); +/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(144); +/* harmony import */ var _operators_map__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(197); +/** PURE_IMPORTS_START _Observable,_util_isArray,_util_isFunction,_operators_map PURE_IMPORTS_END */ -var Subscription = /*@__PURE__*/ (function () { - function Subscription(unsubscribe) { - this.closed = false; - this._parentOrParents = null; - this._subscriptions = null; - if (unsubscribe) { - this._unsubscribe = unsubscribe; - } +function fromEventPattern(addHandler, removeHandler, resultSelector) { + if (resultSelector) { + return fromEventPattern(addHandler, removeHandler).pipe(Object(_operators_map__WEBPACK_IMPORTED_MODULE_3__["map"])(function (args) { return Object(_util_isArray__WEBPACK_IMPORTED_MODULE_1__["isArray"])(args) ? resultSelector.apply(void 0, args) : resultSelector(args); })); } - Subscription.prototype.unsubscribe = function () { - var errors; - if (this.closed) { - return; + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { + var handler = function () { + var e = []; + for (var _i = 0; _i < arguments.length; _i++) { + e[_i] = arguments[_i]; + } + return subscriber.next(e.length === 1 ? e[0] : e); + }; + var retValue; + try { + retValue = addHandler(handler); } - var _a = this, _parentOrParents = _a._parentOrParents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; - this.closed = true; - this._parentOrParents = null; - this._subscriptions = null; - if (_parentOrParents instanceof Subscription) { - _parentOrParents.remove(this); - } - else if (_parentOrParents !== null) { - for (var index = 0; index < _parentOrParents.length; ++index) { - var parent_1 = _parentOrParents[index]; - parent_1.remove(this); - } - } - if (Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_2__["isFunction"])(_unsubscribe)) { - try { - _unsubscribe.call(this); - } - catch (e) { - errors = e instanceof _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__["UnsubscriptionError"] ? flattenUnsubscriptionErrors(e.errors) : [e]; - } - } - if (Object(_util_isArray__WEBPACK_IMPORTED_MODULE_0__["isArray"])(_subscriptions)) { - var index = -1; - var len = _subscriptions.length; - while (++index < len) { - var sub = _subscriptions[index]; - if (Object(_util_isObject__WEBPACK_IMPORTED_MODULE_1__["isObject"])(sub)) { - try { - sub.unsubscribe(); - } - catch (e) { - errors = errors || []; - if (e instanceof _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__["UnsubscriptionError"]) { - errors = errors.concat(flattenUnsubscriptionErrors(e.errors)); - } - else { - errors.push(e); - } - } - } - } + catch (err) { + subscriber.error(err); + return undefined; } - if (errors) { - throw new _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__["UnsubscriptionError"](errors); + if (!Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_2__["isFunction"])(removeHandler)) { + return undefined; } - }; - Subscription.prototype.add = function (teardown) { - var subscription = teardown; - if (!teardown) { - return Subscription.EMPTY; + return function () { return removeHandler(handler, retValue); }; + }); +} +//# sourceMappingURL=fromEventPattern.js.map + + +/***/ }), +/* 225 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "generate", function() { return generate; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(191); +/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(176); +/** PURE_IMPORTS_START _Observable,_util_identity,_util_isScheduler PURE_IMPORTS_END */ + + + +function generate(initialStateOrOptions, condition, iterate, resultSelectorOrObservable, scheduler) { + var resultSelector; + var initialState; + if (arguments.length == 1) { + var options = initialStateOrOptions; + initialState = options.initialState; + condition = options.condition; + iterate = options.iterate; + resultSelector = options.resultSelector || _util_identity__WEBPACK_IMPORTED_MODULE_1__["identity"]; + scheduler = options.scheduler; + } + else if (resultSelectorOrObservable === undefined || Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_2__["isScheduler"])(resultSelectorOrObservable)) { + initialState = initialStateOrOptions; + resultSelector = _util_identity__WEBPACK_IMPORTED_MODULE_1__["identity"]; + scheduler = resultSelectorOrObservable; + } + else { + initialState = initialStateOrOptions; + resultSelector = resultSelectorOrObservable; + } + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { + var state = initialState; + if (scheduler) { + return scheduler.schedule(dispatch, 0, { + subscriber: subscriber, + iterate: iterate, + condition: condition, + resultSelector: resultSelector, + state: state + }); } - switch (typeof teardown) { - case 'function': - subscription = new Subscription(teardown); - case 'object': - if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') { - return subscription; + do { + if (condition) { + var conditionResult = void 0; + try { + conditionResult = condition(state); } - else if (this.closed) { - subscription.unsubscribe(); - return subscription; + catch (err) { + subscriber.error(err); + return undefined; } - else if (!(subscription instanceof Subscription)) { - var tmp = subscription; - subscription = new Subscription(); - subscription._subscriptions = [tmp]; + if (!conditionResult) { + subscriber.complete(); + break; } + } + var value = void 0; + try { + value = resultSelector(state); + } + catch (err) { + subscriber.error(err); + return undefined; + } + subscriber.next(value); + if (subscriber.closed) { break; - default: { - throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); } - } - var _parentOrParents = subscription._parentOrParents; - if (_parentOrParents === null) { - subscription._parentOrParents = this; - } - else if (_parentOrParents instanceof Subscription) { - if (_parentOrParents === this) { - return subscription; + try { + state = iterate(state); } - subscription._parentOrParents = [_parentOrParents, this]; + catch (err) { + subscriber.error(err); + return undefined; + } + } while (true); + return undefined; + }); +} +function dispatch(state) { + var subscriber = state.subscriber, condition = state.condition; + if (subscriber.closed) { + return undefined; + } + if (state.needIterate) { + try { + state.state = state.iterate(state.state); } - else if (_parentOrParents.indexOf(this) === -1) { - _parentOrParents.push(this); + catch (err) { + subscriber.error(err); + return undefined; } - else { - return subscription; + } + else { + state.needIterate = true; + } + if (condition) { + var conditionResult = void 0; + try { + conditionResult = condition(state.state); } - var subscriptions = this._subscriptions; - if (subscriptions === null) { - this._subscriptions = [subscription]; + catch (err) { + subscriber.error(err); + return undefined; } - else { - subscriptions.push(subscription); + if (!conditionResult) { + subscriber.complete(); + return undefined; } - return subscription; - }; - Subscription.prototype.remove = function (subscription) { - var subscriptions = this._subscriptions; - if (subscriptions) { - var subscriptionIndex = subscriptions.indexOf(subscription); - if (subscriptionIndex !== -1) { - subscriptions.splice(subscriptionIndex, 1); - } + if (subscriber.closed) { + return undefined; } - }; - Subscription.EMPTY = (function (empty) { - empty.closed = true; - return empty; - }(new Subscription())); - return Subscription; -}()); - -function flattenUnsubscriptionErrors(errors) { - return errors.reduce(function (errs, err) { return errs.concat((err instanceof _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__["UnsubscriptionError"]) ? err.errors : err); }, []); + } + var value; + try { + value = state.resultSelector(state.state); + } + catch (err) { + subscriber.error(err); + return undefined; + } + if (subscriber.closed) { + return undefined; + } + subscriber.next(value); + if (subscriber.closed) { + return undefined; + } + return this.schedule(state); } -//# sourceMappingURL=Subscription.js.map +//# sourceMappingURL=generate.js.map /***/ }), -/* 178 */ +/* 226 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isArray", function() { return isArray; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var isArray = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })(); -//# sourceMappingURL=isArray.js.map - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "iif", function() { return iif; }); +/* harmony import */ var _defer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(221); +/* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(174); +/** PURE_IMPORTS_START _defer,_empty PURE_IMPORTS_END */ -/***/ }), -/* 179 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isObject", function() { return isObject; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function isObject(x) { - return x !== null && typeof x === 'object'; +function iif(condition, trueResult, falseResult) { + if (trueResult === void 0) { + trueResult = _empty__WEBPACK_IMPORTED_MODULE_1__["EMPTY"]; + } + if (falseResult === void 0) { + falseResult = _empty__WEBPACK_IMPORTED_MODULE_1__["EMPTY"]; + } + return Object(_defer__WEBPACK_IMPORTED_MODULE_0__["defer"])(function () { return condition() ? trueResult : falseResult; }); } -//# sourceMappingURL=isObject.js.map +//# sourceMappingURL=iif.js.map /***/ }), -/* 180 */ +/* 227 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UnsubscriptionError", function() { return UnsubscriptionError; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var UnsubscriptionErrorImpl = /*@__PURE__*/ (function () { - function UnsubscriptionErrorImpl(errors) { - Error.call(this); - this.message = errors ? - errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ') : ''; - this.name = 'UnsubscriptionError'; - this.errors = errors; - return this; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "interval", function() { return interval; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(186); +/* harmony import */ var _util_isNumeric__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(228); +/** PURE_IMPORTS_START _Observable,_scheduler_async,_util_isNumeric PURE_IMPORTS_END */ + + + +function interval(period, scheduler) { + if (period === void 0) { + period = 0; } - UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); - return UnsubscriptionErrorImpl; -})(); -var UnsubscriptionError = UnsubscriptionErrorImpl; -//# sourceMappingURL=UnsubscriptionError.js.map + if (scheduler === void 0) { + scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__["async"]; + } + if (!Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_2__["isNumeric"])(period) || period < 0) { + period = 0; + } + if (!scheduler || typeof scheduler.schedule !== 'function') { + scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__["async"]; + } + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { + subscriber.add(scheduler.schedule(dispatch, period, { subscriber: subscriber, counter: 0, period: period })); + return subscriber; + }); +} +function dispatch(state) { + var subscriber = state.subscriber, counter = state.counter, period = state.period; + subscriber.next(counter); + this.schedule({ subscriber: subscriber, counter: counter + 1, period: period }, period); +} +//# sourceMappingURL=interval.js.map /***/ }), -/* 181 */ +/* 228 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rxSubscriber", function() { return rxSubscriber; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "$$rxSubscriber", function() { return $$rxSubscriber; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var rxSubscriber = /*@__PURE__*/ (function () { - return typeof Symbol === 'function' - ? /*@__PURE__*/ Symbol('rxSubscriber') - : '@@rxSubscriber_' + /*@__PURE__*/ Math.random(); -})(); -var $$rxSubscriber = rxSubscriber; -//# sourceMappingURL=rxSubscriber.js.map +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNumeric", function() { return isNumeric; }); +/* harmony import */ var _isArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); +/** PURE_IMPORTS_START _isArray PURE_IMPORTS_END */ + +function isNumeric(val) { + return !Object(_isArray__WEBPACK_IMPORTED_MODULE_0__["isArray"])(val) && (val - parseFloat(val) + 1) >= 0; +} +//# sourceMappingURL=isNumeric.js.map /***/ }), -/* 182 */ +/* 229 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toSubscriber", function() { return toSubscriber; }); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(172); -/* harmony import */ var _symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(181); -/* harmony import */ var _Observer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(174); -/** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "merge", function() { return merge; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(176); +/* harmony import */ var _operators_mergeAll__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(212); +/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(177); +/** PURE_IMPORTS_START _Observable,_util_isScheduler,_operators_mergeAll,_fromArray PURE_IMPORTS_END */ -function toSubscriber(nextOrObserver, error, complete) { - if (nextOrObserver) { - if (nextOrObserver instanceof _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"]) { - return nextOrObserver; - } - if (nextOrObserver[_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_1__["rxSubscriber"]]) { - return nextOrObserver[_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_1__["rxSubscriber"]](); + +function merge() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; + } + var concurrent = Number.POSITIVE_INFINITY; + var scheduler = null; + var last = observables[observables.length - 1]; + if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_1__["isScheduler"])(last)) { + scheduler = observables.pop(); + if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') { + concurrent = observables.pop(); } } - if (!nextOrObserver && !error && !complete) { - return new _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"](_Observer__WEBPACK_IMPORTED_MODULE_2__["empty"]); + else if (typeof last === 'number') { + concurrent = observables.pop(); } - return new _Subscriber__WEBPACK_IMPORTED_MODULE_0__["Subscriber"](nextOrObserver, error, complete); + if (scheduler === null && observables.length === 1 && observables[0] instanceof _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]) { + return observables[0]; + } + return Object(_operators_mergeAll__WEBPACK_IMPORTED_MODULE_2__["mergeAll"])(concurrent)(Object(_fromArray__WEBPACK_IMPORTED_MODULE_3__["fromArray"])(observables, scheduler)); } -//# sourceMappingURL=toSubscriber.js.map +//# sourceMappingURL=merge.js.map /***/ }), -/* 183 */ +/* 230 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "observable", function() { return observable; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })(); -//# sourceMappingURL=observable.js.map +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NEVER", function() { return NEVER; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "never", function() { return never; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _util_noop__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(156); +/** PURE_IMPORTS_START _Observable,_util_noop PURE_IMPORTS_END */ + + +var NEVER = /*@__PURE__*/ new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](_util_noop__WEBPACK_IMPORTED_MODULE_1__["noop"]); +function never() { + return NEVER; +} +//# sourceMappingURL=never.js.map /***/ }), -/* 184 */ +/* 231 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pipe", function() { return pipe; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pipeFromArray", function() { return pipeFromArray; }); -/* harmony import */ var _noop__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(185); -/** PURE_IMPORTS_START _noop PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onErrorResumeNext", function() { return onErrorResumeNext; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(214); +/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(149); +/* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(174); +/** PURE_IMPORTS_START _Observable,_from,_util_isArray,_empty PURE_IMPORTS_END */ -function pipe() { - var fns = []; + + + +function onErrorResumeNext() { + var sources = []; for (var _i = 0; _i < arguments.length; _i++) { - fns[_i] = arguments[_i]; + sources[_i] = arguments[_i]; } - return pipeFromArray(fns); -} -function pipeFromArray(fns) { - if (!fns) { - return _noop__WEBPACK_IMPORTED_MODULE_0__["noop"]; + if (sources.length === 0) { + return _empty__WEBPACK_IMPORTED_MODULE_3__["EMPTY"]; } - if (fns.length === 1) { - return fns[0]; + var first = sources[0], remainder = sources.slice(1); + if (sources.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_2__["isArray"])(first)) { + return onErrorResumeNext.apply(void 0, first); } - return function piped(input) { - return fns.reduce(function (prev, fn) { return fn(prev); }, input); - }; + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { + var subNext = function () { return subscriber.add(onErrorResumeNext.apply(void 0, remainder).subscribe(subscriber)); }; + return Object(_from__WEBPACK_IMPORTED_MODULE_1__["from"])(first).subscribe({ + next: function (value) { subscriber.next(value); }, + error: subNext, + complete: subNext, + }); + }); } -//# sourceMappingURL=pipe.js.map +//# sourceMappingURL=onErrorResumeNext.js.map /***/ }), -/* 185 */ +/* 232 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "noop", function() { return noop; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function noop() { } -//# sourceMappingURL=noop.js.map +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pairs", function() { return pairs; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dispatch", function() { return dispatch; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(148); +/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ + + +function pairs(obj, scheduler) { + if (!scheduler) { + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { + var keys = Object.keys(obj); + for (var i = 0; i < keys.length && !subscriber.closed; i++) { + var key = keys[i]; + if (obj.hasOwnProperty(key)) { + subscriber.next([key, obj[key]]); + } + } + subscriber.complete(); + }); + } + else { + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { + var keys = Object.keys(obj); + var subscription = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"](); + subscription.add(scheduler.schedule(dispatch, 0, { keys: keys, index: 0, subscriber: subscriber, subscription: subscription, obj: obj })); + return subscription; + }); + } +} +function dispatch(state) { + var keys = state.keys, index = state.index, subscriber = state.subscriber, subscription = state.subscription, obj = state.obj; + if (!subscriber.closed) { + if (index < keys.length) { + var key = keys[index]; + subscriber.next([key, obj[key]]); + subscription.add(this.schedule({ keys: keys, index: index + 1, subscriber: subscriber, subscription: subscription, obj: obj })); + } + else { + subscriber.complete(); + } + } +} +//# sourceMappingURL=pairs.js.map /***/ }), -/* 186 */ +/* 233 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ConnectableObservable", function() { return ConnectableObservable; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "connectableObservableDescriptor", function() { return connectableObservableDescriptor; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(187); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(170); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(172); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(177); -/* harmony import */ var _operators_refCount__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(190); -/** PURE_IMPORTS_START tslib,_Subject,_Observable,_Subscriber,_Subscription,_operators_refCount PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "partition", function() { return partition; }); +/* harmony import */ var _util_not__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(234); +/* harmony import */ var _util_subscribeTo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(203); +/* harmony import */ var _operators_filter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(235); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(141); +/** PURE_IMPORTS_START _util_not,_util_subscribeTo,_operators_filter,_Observable PURE_IMPORTS_END */ +function partition(source, predicate, thisArg) { + return [ + Object(_operators_filter__WEBPACK_IMPORTED_MODULE_2__["filter"])(predicate, thisArg)(new _Observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](Object(_util_subscribeTo__WEBPACK_IMPORTED_MODULE_1__["subscribeTo"])(source))), + Object(_operators_filter__WEBPACK_IMPORTED_MODULE_2__["filter"])(Object(_util_not__WEBPACK_IMPORTED_MODULE_0__["not"])(predicate, thisArg))(new _Observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](Object(_util_subscribeTo__WEBPACK_IMPORTED_MODULE_1__["subscribeTo"])(source))) + ]; +} +//# sourceMappingURL=partition.js.map -var ConnectableObservable = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ConnectableObservable, _super); - function ConnectableObservable(source, subjectFactory) { - var _this = _super.call(this) || this; - _this.source = source; - _this.subjectFactory = subjectFactory; - _this._refCount = 0; - _this._isComplete = false; - return _this; +/***/ }), +/* 234 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "not", function() { return not; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function not(pred, thisArg) { + function notPred() { + return !(notPred.pred.apply(notPred.thisArg, arguments)); } - ConnectableObservable.prototype._subscribe = function (subscriber) { - return this.getSubject().subscribe(subscriber); - }; - ConnectableObservable.prototype.getSubject = function () { - var subject = this._subject; - if (!subject || subject.isStopped) { - this._subject = this.subjectFactory(); - } - return this._subject; - }; - ConnectableObservable.prototype.connect = function () { - var connection = this._connection; - if (!connection) { - this._isComplete = false; - connection = this._connection = new _Subscription__WEBPACK_IMPORTED_MODULE_4__["Subscription"](); - connection.add(this.source - .subscribe(new ConnectableSubscriber(this.getSubject(), this))); - if (connection.closed) { - this._connection = null; - connection = _Subscription__WEBPACK_IMPORTED_MODULE_4__["Subscription"].EMPTY; - } - } - return connection; - }; - ConnectableObservable.prototype.refCount = function () { - return Object(_operators_refCount__WEBPACK_IMPORTED_MODULE_5__["refCount"])()(this); - }; - return ConnectableObservable; -}(_Observable__WEBPACK_IMPORTED_MODULE_2__["Observable"])); + notPred.pred = pred; + notPred.thisArg = thisArg; + return notPred; +} +//# sourceMappingURL=not.js.map -var connectableObservableDescriptor = /*@__PURE__*/ (function () { - var connectableProto = ConnectableObservable.prototype; - return { - operator: { value: null }, - _refCount: { value: 0, writable: true }, - _subject: { value: null, writable: true }, - _connection: { value: null, writable: true }, - _subscribe: { value: connectableProto._subscribe }, - _isComplete: { value: connectableProto._isComplete, writable: true }, - getSubject: { value: connectableProto.getSubject }, - connect: { value: connectableProto.connect }, - refCount: { value: connectableProto.refCount } - }; -})(); -var ConnectableSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ConnectableSubscriber, _super); - function ConnectableSubscriber(destination, connectable) { - var _this = _super.call(this, destination) || this; - _this.connectable = connectable; - return _this; - } - ConnectableSubscriber.prototype._error = function (err) { - this._unsubscribe(); - _super.prototype._error.call(this, err); - }; - ConnectableSubscriber.prototype._complete = function () { - this.connectable._isComplete = true; - this._unsubscribe(); - _super.prototype._complete.call(this); - }; - ConnectableSubscriber.prototype._unsubscribe = function () { - var connectable = this.connectable; - if (connectable) { - this.connectable = null; - var connection = connectable._connection; - connectable._refCount = 0; - connectable._subject = null; - connectable._connection = null; - if (connection) { - connection.unsubscribe(); - } - } + +/***/ }), +/* 235 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "filter", function() { return filter; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ + + +function filter(predicate, thisArg) { + return function filterOperatorFunction(source) { + return source.lift(new FilterOperator(predicate, thisArg)); }; - return ConnectableSubscriber; -}(_Subject__WEBPACK_IMPORTED_MODULE_1__["SubjectSubscriber"])); -var RefCountOperator = /*@__PURE__*/ (function () { - function RefCountOperator(connectable) { - this.connectable = connectable; +} +var FilterOperator = /*@__PURE__*/ (function () { + function FilterOperator(predicate, thisArg) { + this.predicate = predicate; + this.thisArg = thisArg; } - RefCountOperator.prototype.call = function (subscriber, source) { - var connectable = this.connectable; - connectable._refCount++; - var refCounter = new RefCountSubscriber(subscriber, connectable); - var subscription = source.subscribe(refCounter); - if (!refCounter.closed) { - refCounter.connection = connectable.connect(); - } - return subscription; + FilterOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg)); }; - return RefCountOperator; + return FilterOperator; }()); -var RefCountSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RefCountSubscriber, _super); - function RefCountSubscriber(destination, connectable) { +var FilterSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FilterSubscriber, _super); + function FilterSubscriber(destination, predicate, thisArg) { var _this = _super.call(this, destination) || this; - _this.connectable = connectable; + _this.predicate = predicate; + _this.thisArg = thisArg; + _this.count = 0; return _this; } - RefCountSubscriber.prototype._unsubscribe = function () { - var connectable = this.connectable; - if (!connectable) { - this.connection = null; - return; - } - this.connectable = null; - var refCount = connectable._refCount; - if (refCount <= 0) { - this.connection = null; - return; + FilterSubscriber.prototype._next = function (value) { + var result; + try { + result = this.predicate.call(this.thisArg, value, this.count++); } - connectable._refCount = refCount - 1; - if (refCount > 1) { - this.connection = null; + catch (err) { + this.destination.error(err); return; } - var connection = this.connection; - var sharedConnection = connectable._connection; - this.connection = null; - if (sharedConnection && (!connection || sharedConnection === connection)) { - sharedConnection.unsubscribe(); + if (result) { + this.destination.next(value); } }; - return RefCountSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_3__["Subscriber"])); -//# sourceMappingURL=ConnectableObservable.js.map + return FilterSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=filter.js.map /***/ }), -/* 187 */ +/* 236 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubjectSubscriber", function() { return SubjectSubscriber; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Subject", function() { return Subject; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnonymousSubject", function() { return AnonymousSubject; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(170); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(172); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(177); -/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(188); -/* harmony import */ var _SubjectSubscription__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(189); -/* harmony import */ var _internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(181); -/** PURE_IMPORTS_START tslib,_Observable,_Subscriber,_Subscription,_util_ObjectUnsubscribedError,_SubjectSubscription,_internal_symbol_rxSubscriber PURE_IMPORTS_END */ - - - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "race", function() { return race; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RaceOperator", function() { return RaceOperator; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RaceSubscriber", function() { return RaceSubscriber; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(149); +/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(177); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_util_isArray,_fromArray,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -var SubjectSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SubjectSubscriber, _super); - function SubjectSubscriber(destination) { - var _this = _super.call(this, destination) || this; - _this.destination = destination; - return _this; - } - return SubjectSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_2__["Subscriber"])); -var Subject = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Subject, _super); - function Subject() { - var _this = _super.call(this) || this; - _this.observers = []; - _this.closed = false; - _this.isStopped = false; - _this.hasError = false; - _this.thrownError = null; - return _this; +function race() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; } - Subject.prototype[_internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_6__["rxSubscriber"]] = function () { - return new SubjectSubscriber(this); - }; - Subject.prototype.lift = function (operator) { - var subject = new AnonymousSubject(this, this); - subject.operator = operator; - return subject; - }; - Subject.prototype.next = function (value) { - if (this.closed) { - throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__["ObjectUnsubscribedError"](); - } - if (!this.isStopped) { - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].next(value); - } - } - }; - Subject.prototype.error = function (err) { - if (this.closed) { - throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__["ObjectUnsubscribedError"](); - } - this.hasError = true; - this.thrownError = err; - this.isStopped = true; - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].error(err); - } - this.observers.length = 0; - }; - Subject.prototype.complete = function () { - if (this.closed) { - throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__["ObjectUnsubscribedError"](); - } - this.isStopped = true; - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].complete(); - } - this.observers.length = 0; - }; - Subject.prototype.unsubscribe = function () { - this.isStopped = true; - this.closed = true; - this.observers = null; - }; - Subject.prototype._trySubscribe = function (subscriber) { - if (this.closed) { - throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__["ObjectUnsubscribedError"](); - } - else { - return _super.prototype._trySubscribe.call(this, subscriber); - } - }; - Subject.prototype._subscribe = function (subscriber) { - if (this.closed) { - throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__["ObjectUnsubscribedError"](); - } - else if (this.hasError) { - subscriber.error(this.thrownError); - return _Subscription__WEBPACK_IMPORTED_MODULE_3__["Subscription"].EMPTY; - } - else if (this.isStopped) { - subscriber.complete(); - return _Subscription__WEBPACK_IMPORTED_MODULE_3__["Subscription"].EMPTY; + if (observables.length === 1) { + if (Object(_util_isArray__WEBPACK_IMPORTED_MODULE_1__["isArray"])(observables[0])) { + observables = observables[0]; } else { - this.observers.push(subscriber); - return new _SubjectSubscription__WEBPACK_IMPORTED_MODULE_5__["SubjectSubscription"](this, subscriber); + return observables[0]; } + } + return Object(_fromArray__WEBPACK_IMPORTED_MODULE_2__["fromArray"])(observables, undefined).lift(new RaceOperator()); +} +var RaceOperator = /*@__PURE__*/ (function () { + function RaceOperator() { + } + RaceOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new RaceSubscriber(subscriber)); }; - Subject.prototype.asObservable = function () { - var observable = new _Observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); - observable.source = this; - return observable; - }; - Subject.create = function (destination, source) { - return new AnonymousSubject(destination, source); - }; - return Subject; -}(_Observable__WEBPACK_IMPORTED_MODULE_1__["Observable"])); + return RaceOperator; +}()); -var AnonymousSubject = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AnonymousSubject, _super); - function AnonymousSubject(destination, source) { - var _this = _super.call(this) || this; - _this.destination = destination; - _this.source = source; +var RaceSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RaceSubscriber, _super); + function RaceSubscriber(destination) { + var _this = _super.call(this, destination) || this; + _this.hasFirst = false; + _this.observables = []; + _this.subscriptions = []; return _this; } - AnonymousSubject.prototype.next = function (value) { - var destination = this.destination; - if (destination && destination.next) { - destination.next(value); - } - }; - AnonymousSubject.prototype.error = function (err) { - var destination = this.destination; - if (destination && destination.error) { - this.destination.error(err); - } + RaceSubscriber.prototype._next = function (observable) { + this.observables.push(observable); }; - AnonymousSubject.prototype.complete = function () { - var destination = this.destination; - if (destination && destination.complete) { + RaceSubscriber.prototype._complete = function () { + var observables = this.observables; + var len = observables.length; + if (len === 0) { this.destination.complete(); } - }; - AnonymousSubject.prototype._subscribe = function (subscriber) { - var source = this.source; - if (source) { - return this.source.subscribe(subscriber); - } else { - return _Subscription__WEBPACK_IMPORTED_MODULE_3__["Subscription"].EMPTY; + for (var i = 0; i < len && !this.hasFirst; i++) { + var observable = observables[i]; + var subscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__["subscribeToResult"])(this, observable, observable, i); + if (this.subscriptions) { + this.subscriptions.push(subscription); + } + this.add(subscription); + } + this.observables = null; } }; - return AnonymousSubject; -}(Subject)); + RaceSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + if (!this.hasFirst) { + this.hasFirst = true; + for (var i = 0; i < this.subscriptions.length; i++) { + if (i !== outerIndex) { + var subscription = this.subscriptions[i]; + subscription.unsubscribe(); + this.remove(subscription); + } + } + this.subscriptions = null; + } + this.destination.next(innerValue); + }; + return RaceSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__["OuterSubscriber"])); -//# sourceMappingURL=Subject.js.map +//# sourceMappingURL=race.js.map /***/ }), -/* 188 */ +/* 237 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ObjectUnsubscribedError", function() { return ObjectUnsubscribedError; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var ObjectUnsubscribedErrorImpl = /*@__PURE__*/ (function () { - function ObjectUnsubscribedErrorImpl() { - Error.call(this); - this.message = 'object unsubscribed'; - this.name = 'ObjectUnsubscribedError'; - return this; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "range", function() { return range; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dispatch", function() { return dispatch; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ + +function range(start, count, scheduler) { + if (start === void 0) { + start = 0; } - ObjectUnsubscribedErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); - return ObjectUnsubscribedErrorImpl; -})(); -var ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl; -//# sourceMappingURL=ObjectUnsubscribedError.js.map + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { + if (count === undefined) { + count = start; + start = 0; + } + var index = 0; + var current = start; + if (scheduler) { + return scheduler.schedule(dispatch, 0, { + index: index, count: count, start: start, subscriber: subscriber + }); + } + else { + do { + if (index++ >= count) { + subscriber.complete(); + break; + } + subscriber.next(current++); + if (subscriber.closed) { + break; + } + } while (true); + } + return undefined; + }); +} +function dispatch(state) { + var start = state.start, index = state.index, count = state.count, subscriber = state.subscriber; + if (index >= count) { + subscriber.complete(); + return; + } + subscriber.next(start); + if (subscriber.closed) { + return; + } + state.index = index + 1; + state.start = start + 1; + this.schedule(state); +} +//# sourceMappingURL=range.js.map /***/ }), -/* 189 */ +/* 238 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubjectSubscription", function() { return SubjectSubscription; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(177); -/** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timer", function() { return timer; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(186); +/* harmony import */ var _util_isNumeric__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(228); +/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(176); +/** PURE_IMPORTS_START _Observable,_scheduler_async,_util_isNumeric,_util_isScheduler PURE_IMPORTS_END */ -var SubjectSubscription = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SubjectSubscription, _super); - function SubjectSubscription(subject, subscriber) { - var _this = _super.call(this) || this; - _this.subject = subject; - _this.subscriber = subscriber; - _this.closed = false; - return _this; - } - SubjectSubscription.prototype.unsubscribe = function () { - if (this.closed) { - return; - } - this.closed = true; - var subject = this.subject; - var observers = subject.observers; - this.subject = null; - if (!observers || observers.length === 0 || subject.isStopped || subject.closed) { - return; - } - var subscriberIndex = observers.indexOf(this.subscriber); - if (subscriberIndex !== -1) { - observers.splice(subscriberIndex, 1); - } - }; - return SubjectSubscription; -}(_Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"])); -//# sourceMappingURL=SubjectSubscription.js.map + +function timer(dueTime, periodOrScheduler, scheduler) { + if (dueTime === void 0) { + dueTime = 0; + } + var period = -1; + if (Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_2__["isNumeric"])(periodOrScheduler)) { + period = Number(periodOrScheduler) < 1 && 1 || Number(periodOrScheduler); + } + else if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_3__["isScheduler"])(periodOrScheduler)) { + scheduler = periodOrScheduler; + } + if (!Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_3__["isScheduler"])(scheduler)) { + scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__["async"]; + } + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { + var due = Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_2__["isNumeric"])(dueTime) + ? dueTime + : (+dueTime - scheduler.now()); + return scheduler.schedule(dispatch, due, { + index: 0, period: period, subscriber: subscriber + }); + }); +} +function dispatch(state) { + var index = state.index, period = state.period, subscriber = state.subscriber; + subscriber.next(index); + if (subscriber.closed) { + return; + } + else if (period === -1) { + return subscriber.complete(); + } + state.index = index + 1; + this.schedule(state, period); +} +//# sourceMappingURL=timer.js.map /***/ }), -/* 190 */ +/* 239 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "refCount", function() { return refCount; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "using", function() { return using; }); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(141); +/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(214); +/* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(174); +/** PURE_IMPORTS_START _Observable,_from,_empty PURE_IMPORTS_END */ -function refCount() { - return function refCountOperatorFunction(source) { - return source.lift(new RefCountOperator(source)); - }; -} -var RefCountOperator = /*@__PURE__*/ (function () { - function RefCountOperator(connectable) { - this.connectable = connectable; - } - RefCountOperator.prototype.call = function (subscriber, source) { - var connectable = this.connectable; - connectable._refCount++; - var refCounter = new RefCountSubscriber(subscriber, connectable); - var subscription = source.subscribe(refCounter); - if (!refCounter.closed) { - refCounter.connection = connectable.connect(); + +function using(resourceFactory, observableFactory) { + return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { + var resource; + try { + resource = resourceFactory(); } - return subscription; - }; - return RefCountOperator; -}()); -var RefCountSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RefCountSubscriber, _super); - function RefCountSubscriber(destination, connectable) { - var _this = _super.call(this, destination) || this; - _this.connectable = connectable; - return _this; - } - RefCountSubscriber.prototype._unsubscribe = function () { - var connectable = this.connectable; - if (!connectable) { - this.connection = null; - return; - } - this.connectable = null; - var refCount = connectable._refCount; - if (refCount <= 0) { - this.connection = null; - return; + catch (err) { + subscriber.error(err); + return undefined; } - connectable._refCount = refCount - 1; - if (refCount > 1) { - this.connection = null; - return; + var result; + try { + result = observableFactory(resource); } - var connection = this.connection; - var sharedConnection = connectable._connection; - this.connection = null; - if (sharedConnection && (!connection || sharedConnection === connection)) { - sharedConnection.unsubscribe(); + catch (err) { + subscriber.error(err); + return undefined; } - }; - return RefCountSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=refCount.js.map + var source = result ? Object(_from__WEBPACK_IMPORTED_MODULE_1__["from"])(result) : _empty__WEBPACK_IMPORTED_MODULE_2__["EMPTY"]; + var subscription = source.subscribe(subscriber); + return function () { + subscription.unsubscribe(); + if (resource) { + resource.unsubscribe(); + } + }; + }); +} +//# sourceMappingURL=using.js.map /***/ }), -/* 191 */ +/* 240 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "groupBy", function() { return groupBy; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GroupedObservable", function() { return GroupedObservable; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(177); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(170); -/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(187); -/** PURE_IMPORTS_START tslib,_Subscriber,_Subscription,_Observable,_Subject PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "zip", function() { return zip; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ZipOperator", function() { return ZipOperator; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ZipSubscriber", function() { return ZipSubscriber; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(177); +/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(149); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(143); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(201); +/* harmony import */ var _internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(206); +/** PURE_IMPORTS_START tslib,_fromArray,_util_isArray,_Subscriber,_OuterSubscriber,_util_subscribeToResult,_.._internal_symbol_iterator PURE_IMPORTS_END */ -function groupBy(keySelector, elementSelector, durationSelector, subjectSelector) { - return function (source) { - return source.lift(new GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector)); - }; + + +function zip() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; + } + var resultSelector = observables[observables.length - 1]; + if (typeof resultSelector === 'function') { + observables.pop(); + } + return Object(_fromArray__WEBPACK_IMPORTED_MODULE_1__["fromArray"])(observables, undefined).lift(new ZipOperator(resultSelector)); } -var GroupByOperator = /*@__PURE__*/ (function () { - function GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector) { - this.keySelector = keySelector; - this.elementSelector = elementSelector; - this.durationSelector = durationSelector; - this.subjectSelector = subjectSelector; +var ZipOperator = /*@__PURE__*/ (function () { + function ZipOperator(resultSelector) { + this.resultSelector = resultSelector; } - GroupByOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new GroupBySubscriber(subscriber, this.keySelector, this.elementSelector, this.durationSelector, this.subjectSelector)); + ZipOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ZipSubscriber(subscriber, this.resultSelector)); }; - return GroupByOperator; + return ZipOperator; }()); -var GroupBySubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GroupBySubscriber, _super); - function GroupBySubscriber(destination, keySelector, elementSelector, durationSelector, subjectSelector) { + +var ZipSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ZipSubscriber, _super); + function ZipSubscriber(destination, resultSelector, values) { + if (values === void 0) { + values = Object.create(null); + } var _this = _super.call(this, destination) || this; - _this.keySelector = keySelector; - _this.elementSelector = elementSelector; - _this.durationSelector = durationSelector; - _this.subjectSelector = subjectSelector; - _this.groups = null; - _this.attemptedToUnsubscribe = false; - _this.count = 0; + _this.iterators = []; + _this.active = 0; + _this.resultSelector = (typeof resultSelector === 'function') ? resultSelector : null; + _this.values = values; return _this; } - GroupBySubscriber.prototype._next = function (value) { - var key; - try { - key = this.keySelector(value); + ZipSubscriber.prototype._next = function (value) { + var iterators = this.iterators; + if (Object(_util_isArray__WEBPACK_IMPORTED_MODULE_2__["isArray"])(value)) { + iterators.push(new StaticArrayIterator(value)); } - catch (err) { - this.error(err); - return; + else if (typeof value[_internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_6__["iterator"]] === 'function') { + iterators.push(new StaticIterator(value[_internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_6__["iterator"]]())); + } + else { + iterators.push(new ZipBufferIterator(this.destination, this, value)); } - this._group(value, key); }; - GroupBySubscriber.prototype._group = function (value, key) { - var groups = this.groups; - if (!groups) { - groups = this.groups = new Map(); + ZipSubscriber.prototype._complete = function () { + var iterators = this.iterators; + var len = iterators.length; + this.unsubscribe(); + if (len === 0) { + this.destination.complete(); + return; } - var group = groups.get(key); - var element; - if (this.elementSelector) { - try { - element = this.elementSelector(value); + this.active = len; + for (var i = 0; i < len; i++) { + var iterator = iterators[i]; + if (iterator.stillUnsubscribed) { + var destination = this.destination; + destination.add(iterator.subscribe(iterator, i)); } - catch (err) { - this.error(err); + else { + this.active--; } } - else { - element = value; + }; + ZipSubscriber.prototype.notifyInactive = function () { + this.active--; + if (this.active === 0) { + this.destination.complete(); } - if (!group) { - group = (this.subjectSelector ? this.subjectSelector() : new _Subject__WEBPACK_IMPORTED_MODULE_4__["Subject"]()); - groups.set(key, group); - var groupedObservable = new GroupedObservable(key, group, this); - this.destination.next(groupedObservable); - if (this.durationSelector) { - var duration = void 0; - try { - duration = this.durationSelector(new GroupedObservable(key, group)); - } - catch (err) { - this.error(err); - return; - } - this.add(duration.subscribe(new GroupDurationSubscriber(key, group, this))); + }; + ZipSubscriber.prototype.checkIterators = function () { + var iterators = this.iterators; + var len = iterators.length; + var destination = this.destination; + for (var i = 0; i < len; i++) { + var iterator = iterators[i]; + if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) { + return; } } - if (!group.closed) { - group.next(element); + var shouldComplete = false; + var args = []; + for (var i = 0; i < len; i++) { + var iterator = iterators[i]; + var result = iterator.next(); + if (iterator.hasCompleted()) { + shouldComplete = true; + } + if (result.done) { + destination.complete(); + return; + } + args.push(result.value); } - }; - GroupBySubscriber.prototype._error = function (err) { - var groups = this.groups; - if (groups) { - groups.forEach(function (group, key) { - group.error(err); - }); - groups.clear(); + if (this.resultSelector) { + this._tryresultSelector(args); } - this.destination.error(err); - }; - GroupBySubscriber.prototype._complete = function () { - var groups = this.groups; - if (groups) { - groups.forEach(function (group, key) { - group.complete(); - }); - groups.clear(); + else { + destination.next(args); + } + if (shouldComplete) { + destination.complete(); } - this.destination.complete(); - }; - GroupBySubscriber.prototype.removeGroup = function (key) { - this.groups.delete(key); }; - GroupBySubscriber.prototype.unsubscribe = function () { - if (!this.closed) { - this.attemptedToUnsubscribe = true; - if (this.count === 0) { - _super.prototype.unsubscribe.call(this); - } + ZipSubscriber.prototype._tryresultSelector = function (args) { + var result; + try { + result = this.resultSelector.apply(this, args); + } + catch (err) { + this.destination.error(err); + return; } + this.destination.next(result); }; - return GroupBySubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -var GroupDurationSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GroupDurationSubscriber, _super); - function GroupDurationSubscriber(key, group, parent) { - var _this = _super.call(this, group) || this; - _this.key = key; - _this.group = group; - _this.parent = parent; - return _this; + return ZipSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_3__["Subscriber"])); + +var StaticIterator = /*@__PURE__*/ (function () { + function StaticIterator(iterator) { + this.iterator = iterator; + this.nextResult = iterator.next(); } - GroupDurationSubscriber.prototype._next = function (value) { - this.complete(); + StaticIterator.prototype.hasValue = function () { + return true; }; - GroupDurationSubscriber.prototype._unsubscribe = function () { - var _a = this, parent = _a.parent, key = _a.key; - this.key = this.parent = null; - if (parent) { - parent.removeGroup(key); - } + StaticIterator.prototype.next = function () { + var result = this.nextResult; + this.nextResult = this.iterator.next(); + return result; }; - return GroupDurationSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -var GroupedObservable = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GroupedObservable, _super); - function GroupedObservable(key, groupSubject, refCountSubscription) { - var _this = _super.call(this) || this; - _this.key = key; - _this.groupSubject = groupSubject; - _this.refCountSubscription = refCountSubscription; - return _this; + StaticIterator.prototype.hasCompleted = function () { + var nextResult = this.nextResult; + return nextResult && nextResult.done; + }; + return StaticIterator; +}()); +var StaticArrayIterator = /*@__PURE__*/ (function () { + function StaticArrayIterator(array) { + this.array = array; + this.index = 0; + this.length = 0; + this.length = array.length; } - GroupedObservable.prototype._subscribe = function (subscriber) { - var subscription = new _Subscription__WEBPACK_IMPORTED_MODULE_2__["Subscription"](); - var _a = this, refCountSubscription = _a.refCountSubscription, groupSubject = _a.groupSubject; - if (refCountSubscription && !refCountSubscription.closed) { - subscription.add(new InnerRefCountSubscription(refCountSubscription)); - } - subscription.add(groupSubject.subscribe(subscriber)); - return subscription; + StaticArrayIterator.prototype[_internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_6__["iterator"]] = function () { + return this; }; - return GroupedObservable; -}(_Observable__WEBPACK_IMPORTED_MODULE_3__["Observable"])); - -var InnerRefCountSubscription = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](InnerRefCountSubscription, _super); - function InnerRefCountSubscription(parent) { - var _this = _super.call(this) || this; + StaticArrayIterator.prototype.next = function (value) { + var i = this.index++; + var array = this.array; + return i < this.length ? { value: array[i], done: false } : { value: null, done: true }; + }; + StaticArrayIterator.prototype.hasValue = function () { + return this.array.length > this.index; + }; + StaticArrayIterator.prototype.hasCompleted = function () { + return this.array.length === this.index; + }; + return StaticArrayIterator; +}()); +var ZipBufferIterator = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ZipBufferIterator, _super); + function ZipBufferIterator(destination, parent, observable) { + var _this = _super.call(this, destination) || this; _this.parent = parent; - parent.count++; + _this.observable = observable; + _this.stillUnsubscribed = true; + _this.buffer = []; + _this.isComplete = false; return _this; } - InnerRefCountSubscription.prototype.unsubscribe = function () { - var parent = this.parent; - if (!parent.closed && !this.closed) { - _super.prototype.unsubscribe.call(this); - parent.count -= 1; - if (parent.count === 0 && parent.attemptedToUnsubscribe) { - parent.unsubscribe(); - } + ZipBufferIterator.prototype[_internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_6__["iterator"]] = function () { + return this; + }; + ZipBufferIterator.prototype.next = function () { + var buffer = this.buffer; + if (buffer.length === 0 && this.isComplete) { + return { value: null, done: true }; + } + else { + return { value: buffer.shift(), done: false }; } }; - return InnerRefCountSubscription; -}(_Subscription__WEBPACK_IMPORTED_MODULE_2__["Subscription"])); -//# sourceMappingURL=groupBy.js.map + ZipBufferIterator.prototype.hasValue = function () { + return this.buffer.length > 0; + }; + ZipBufferIterator.prototype.hasCompleted = function () { + return this.buffer.length === 0 && this.isComplete; + }; + ZipBufferIterator.prototype.notifyComplete = function () { + if (this.buffer.length > 0) { + this.isComplete = true; + this.parent.notifyInactive(); + } + else { + this.destination.complete(); + } + }; + ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.buffer.push(innerValue); + this.parent.checkIterators(); + }; + ZipBufferIterator.prototype.subscribe = function (value, index) { + return Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_5__["subscribeToResult"])(this, this.observable, this, index); + }; + return ZipBufferIterator; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_4__["OuterSubscriber"])); +//# sourceMappingURL=zip.js.map /***/ }), -/* 192 */ +/* 241 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BehaviorSubject", function() { return BehaviorSubject; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(187); -/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(188); -/** PURE_IMPORTS_START tslib,_Subject,_util_ObjectUnsubscribedError PURE_IMPORTS_END */ +/* harmony import */ var _internal_operators_audit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(242); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "audit", function() { return _internal_operators_audit__WEBPACK_IMPORTED_MODULE_0__["audit"]; }); +/* harmony import */ var _internal_operators_auditTime__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(243); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "auditTime", function() { return _internal_operators_auditTime__WEBPACK_IMPORTED_MODULE_1__["auditTime"]; }); +/* harmony import */ var _internal_operators_buffer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(244); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "buffer", function() { return _internal_operators_buffer__WEBPACK_IMPORTED_MODULE_2__["buffer"]; }); -var BehaviorSubject = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BehaviorSubject, _super); - function BehaviorSubject(_value) { - var _this = _super.call(this) || this; - _this._value = _value; - return _this; - } - Object.defineProperty(BehaviorSubject.prototype, "value", { - get: function () { - return this.getValue(); - }, - enumerable: true, - configurable: true - }); - BehaviorSubject.prototype._subscribe = function (subscriber) { - var subscription = _super.prototype._subscribe.call(this, subscriber); - if (subscription && !subscription.closed) { - subscriber.next(this._value); - } - return subscription; - }; - BehaviorSubject.prototype.getValue = function () { - if (this.hasError) { - throw this.thrownError; - } - else if (this.closed) { - throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_2__["ObjectUnsubscribedError"](); - } - else { - return this._value; - } - }; - BehaviorSubject.prototype.next = function (value) { - _super.prototype.next.call(this, this._value = value); - }; - return BehaviorSubject; -}(_Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"])); +/* harmony import */ var _internal_operators_bufferCount__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(245); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bufferCount", function() { return _internal_operators_bufferCount__WEBPACK_IMPORTED_MODULE_3__["bufferCount"]; }); -//# sourceMappingURL=BehaviorSubject.js.map +/* harmony import */ var _internal_operators_bufferTime__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(246); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bufferTime", function() { return _internal_operators_bufferTime__WEBPACK_IMPORTED_MODULE_4__["bufferTime"]; }); +/* harmony import */ var _internal_operators_bufferToggle__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(247); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bufferToggle", function() { return _internal_operators_bufferToggle__WEBPACK_IMPORTED_MODULE_5__["bufferToggle"]; }); -/***/ }), -/* 193 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony import */ var _internal_operators_bufferWhen__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(248); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bufferWhen", function() { return _internal_operators_bufferWhen__WEBPACK_IMPORTED_MODULE_6__["bufferWhen"]; }); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReplaySubject", function() { return ReplaySubject; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(187); -/* harmony import */ var _scheduler_queue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(194); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(177); -/* harmony import */ var _operators_observeOn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(201); -/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(188); -/* harmony import */ var _SubjectSubscription__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(189); -/** PURE_IMPORTS_START tslib,_Subject,_scheduler_queue,_Subscription,_operators_observeOn,_util_ObjectUnsubscribedError,_SubjectSubscription PURE_IMPORTS_END */ +/* harmony import */ var _internal_operators_catchError__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(249); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "catchError", function() { return _internal_operators_catchError__WEBPACK_IMPORTED_MODULE_7__["catchError"]; }); +/* harmony import */ var _internal_operators_combineAll__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(250); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "combineAll", function() { return _internal_operators_combineAll__WEBPACK_IMPORTED_MODULE_8__["combineAll"]; }); +/* harmony import */ var _internal_operators_combineLatest__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(251); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "combineLatest", function() { return _internal_operators_combineLatest__WEBPACK_IMPORTED_MODULE_9__["combineLatest"]; }); +/* harmony import */ var _internal_operators_concat__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(252); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "concat", function() { return _internal_operators_concat__WEBPACK_IMPORTED_MODULE_10__["concat"]; }); +/* harmony import */ var _internal_operators_concatAll__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(211); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "concatAll", function() { return _internal_operators_concatAll__WEBPACK_IMPORTED_MODULE_11__["concatAll"]; }); +/* harmony import */ var _internal_operators_concatMap__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(253); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "concatMap", function() { return _internal_operators_concatMap__WEBPACK_IMPORTED_MODULE_12__["concatMap"]; }); +/* harmony import */ var _internal_operators_concatMapTo__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(254); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "concatMapTo", function() { return _internal_operators_concatMapTo__WEBPACK_IMPORTED_MODULE_13__["concatMapTo"]; }); -var ReplaySubject = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ReplaySubject, _super); - function ReplaySubject(bufferSize, windowTime, scheduler) { - if (bufferSize === void 0) { - bufferSize = Number.POSITIVE_INFINITY; - } - if (windowTime === void 0) { - windowTime = Number.POSITIVE_INFINITY; - } - var _this = _super.call(this) || this; - _this.scheduler = scheduler; - _this._events = []; - _this._infiniteTimeWindow = false; - _this._bufferSize = bufferSize < 1 ? 1 : bufferSize; - _this._windowTime = windowTime < 1 ? 1 : windowTime; - if (windowTime === Number.POSITIVE_INFINITY) { - _this._infiniteTimeWindow = true; - _this.next = _this.nextInfiniteTimeWindow; - } - else { - _this.next = _this.nextTimeWindow; - } - return _this; - } - ReplaySubject.prototype.nextInfiniteTimeWindow = function (value) { - var _events = this._events; - _events.push(value); - if (_events.length > this._bufferSize) { - _events.shift(); - } - _super.prototype.next.call(this, value); - }; - ReplaySubject.prototype.nextTimeWindow = function (value) { - this._events.push(new ReplayEvent(this._getNow(), value)); - this._trimBufferThenGetEvents(); - _super.prototype.next.call(this, value); - }; - ReplaySubject.prototype._subscribe = function (subscriber) { - var _infiniteTimeWindow = this._infiniteTimeWindow; - var _events = _infiniteTimeWindow ? this._events : this._trimBufferThenGetEvents(); - var scheduler = this.scheduler; - var len = _events.length; - var subscription; - if (this.closed) { - throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_5__["ObjectUnsubscribedError"](); - } - else if (this.isStopped || this.hasError) { - subscription = _Subscription__WEBPACK_IMPORTED_MODULE_3__["Subscription"].EMPTY; - } - else { - this.observers.push(subscriber); - subscription = new _SubjectSubscription__WEBPACK_IMPORTED_MODULE_6__["SubjectSubscription"](this, subscriber); - } - if (scheduler) { - subscriber.add(subscriber = new _operators_observeOn__WEBPACK_IMPORTED_MODULE_4__["ObserveOnSubscriber"](subscriber, scheduler)); - } - if (_infiniteTimeWindow) { - for (var i = 0; i < len && !subscriber.closed; i++) { - subscriber.next(_events[i]); - } - } - else { - for (var i = 0; i < len && !subscriber.closed; i++) { - subscriber.next(_events[i].value); - } - } - if (this.hasError) { - subscriber.error(this.thrownError); - } - else if (this.isStopped) { - subscriber.complete(); - } - return subscription; - }; - ReplaySubject.prototype._getNow = function () { - return (this.scheduler || _scheduler_queue__WEBPACK_IMPORTED_MODULE_2__["queue"]).now(); - }; - ReplaySubject.prototype._trimBufferThenGetEvents = function () { - var now = this._getNow(); - var _bufferSize = this._bufferSize; - var _windowTime = this._windowTime; - var _events = this._events; - var eventsCount = _events.length; - var spliceCount = 0; - while (spliceCount < eventsCount) { - if ((now - _events[spliceCount].time) < _windowTime) { - break; - } - spliceCount++; - } - if (eventsCount > _bufferSize) { - spliceCount = Math.max(spliceCount, eventsCount - _bufferSize); - } - if (spliceCount > 0) { - _events.splice(0, spliceCount); - } - return _events; - }; - return ReplaySubject; -}(_Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"])); +/* harmony import */ var _internal_operators_count__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(255); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "count", function() { return _internal_operators_count__WEBPACK_IMPORTED_MODULE_14__["count"]; }); -var ReplayEvent = /*@__PURE__*/ (function () { - function ReplayEvent(time, value) { - this.time = time; - this.value = value; - } - return ReplayEvent; -}()); -//# sourceMappingURL=ReplaySubject.js.map +/* harmony import */ var _internal_operators_debounce__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(256); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "debounce", function() { return _internal_operators_debounce__WEBPACK_IMPORTED_MODULE_15__["debounce"]; }); +/* harmony import */ var _internal_operators_debounceTime__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(257); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "debounceTime", function() { return _internal_operators_debounceTime__WEBPACK_IMPORTED_MODULE_16__["debounceTime"]; }); -/***/ }), -/* 194 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony import */ var _internal_operators_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(258); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultIfEmpty", function() { return _internal_operators_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_17__["defaultIfEmpty"]; }); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "queue", function() { return queue; }); -/* harmony import */ var _QueueAction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(195); -/* harmony import */ var _QueueScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(198); -/** PURE_IMPORTS_START _QueueAction,_QueueScheduler PURE_IMPORTS_END */ +/* harmony import */ var _internal_operators_delay__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(259); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "delay", function() { return _internal_operators_delay__WEBPACK_IMPORTED_MODULE_18__["delay"]; }); +/* harmony import */ var _internal_operators_delayWhen__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(261); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "delayWhen", function() { return _internal_operators_delayWhen__WEBPACK_IMPORTED_MODULE_19__["delayWhen"]; }); -var queue = /*@__PURE__*/ new _QueueScheduler__WEBPACK_IMPORTED_MODULE_1__["QueueScheduler"](_QueueAction__WEBPACK_IMPORTED_MODULE_0__["QueueAction"]); -//# sourceMappingURL=queue.js.map +/* harmony import */ var _internal_operators_dematerialize__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(262); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "dematerialize", function() { return _internal_operators_dematerialize__WEBPACK_IMPORTED_MODULE_20__["dematerialize"]; }); +/* harmony import */ var _internal_operators_distinct__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(263); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "distinct", function() { return _internal_operators_distinct__WEBPACK_IMPORTED_MODULE_21__["distinct"]; }); -/***/ }), -/* 195 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony import */ var _internal_operators_distinctUntilChanged__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(264); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "distinctUntilChanged", function() { return _internal_operators_distinctUntilChanged__WEBPACK_IMPORTED_MODULE_22__["distinctUntilChanged"]; }); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QueueAction", function() { return QueueAction; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(196); -/** PURE_IMPORTS_START tslib,_AsyncAction PURE_IMPORTS_END */ +/* harmony import */ var _internal_operators_distinctUntilKeyChanged__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(265); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "distinctUntilKeyChanged", function() { return _internal_operators_distinctUntilKeyChanged__WEBPACK_IMPORTED_MODULE_23__["distinctUntilKeyChanged"]; }); +/* harmony import */ var _internal_operators_elementAt__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(266); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "elementAt", function() { return _internal_operators_elementAt__WEBPACK_IMPORTED_MODULE_24__["elementAt"]; }); -var QueueAction = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](QueueAction, _super); - function QueueAction(scheduler, work) { - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - return _this; - } - QueueAction.prototype.schedule = function (state, delay) { - if (delay === void 0) { - delay = 0; - } - if (delay > 0) { - return _super.prototype.schedule.call(this, state, delay); - } - this.delay = delay; - this.state = state; - this.scheduler.flush(this); - return this; - }; - QueueAction.prototype.execute = function (state, delay) { - return (delay > 0 || this.closed) ? - _super.prototype.execute.call(this, state, delay) : - this._execute(state, delay); - }; - QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) { - return _super.prototype.requestAsyncId.call(this, scheduler, id, delay); - } - return scheduler.flush(this); - }; - return QueueAction; -}(_AsyncAction__WEBPACK_IMPORTED_MODULE_1__["AsyncAction"])); +/* harmony import */ var _internal_operators_endWith__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(269); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "endWith", function() { return _internal_operators_endWith__WEBPACK_IMPORTED_MODULE_25__["endWith"]; }); -//# sourceMappingURL=QueueAction.js.map +/* harmony import */ var _internal_operators_every__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(270); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "every", function() { return _internal_operators_every__WEBPACK_IMPORTED_MODULE_26__["every"]; }); +/* harmony import */ var _internal_operators_exhaust__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(271); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "exhaust", function() { return _internal_operators_exhaust__WEBPACK_IMPORTED_MODULE_27__["exhaust"]; }); -/***/ }), -/* 196 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony import */ var _internal_operators_exhaustMap__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(272); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "exhaustMap", function() { return _internal_operators_exhaustMap__WEBPACK_IMPORTED_MODULE_28__["exhaustMap"]; }); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AsyncAction", function() { return AsyncAction; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Action__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(197); -/** PURE_IMPORTS_START tslib,_Action PURE_IMPORTS_END */ +/* harmony import */ var _internal_operators_expand__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(273); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "expand", function() { return _internal_operators_expand__WEBPACK_IMPORTED_MODULE_29__["expand"]; }); +/* harmony import */ var _internal_operators_filter__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(235); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "filter", function() { return _internal_operators_filter__WEBPACK_IMPORTED_MODULE_30__["filter"]; }); -var AsyncAction = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AsyncAction, _super); - function AsyncAction(scheduler, work) { - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - _this.pending = false; - return _this; - } - AsyncAction.prototype.schedule = function (state, delay) { - if (delay === void 0) { - delay = 0; - } - if (this.closed) { - return this; - } - this.state = state; - var id = this.id; - var scheduler = this.scheduler; - if (id != null) { - this.id = this.recycleAsyncId(scheduler, id, delay); - } - this.pending = true; - this.delay = delay; - this.id = this.id || this.requestAsyncId(scheduler, this.id, delay); - return this; - }; - AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - return setInterval(scheduler.flush.bind(scheduler, this), delay); - }; - AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - if (delay !== null && this.delay === delay && this.pending === false) { - return id; - } - clearInterval(id); - return undefined; - }; - AsyncAction.prototype.execute = function (state, delay) { - if (this.closed) { - return new Error('executing a cancelled action'); - } - this.pending = false; - var error = this._execute(state, delay); - if (error) { - return error; - } - else if (this.pending === false && this.id != null) { - this.id = this.recycleAsyncId(this.scheduler, this.id, null); - } - }; - AsyncAction.prototype._execute = function (state, delay) { - var errored = false; - var errorValue = undefined; - try { - this.work(state); - } - catch (e) { - errored = true; - errorValue = !!e && e || new Error(e); - } - if (errored) { - this.unsubscribe(); - return errorValue; - } - }; - AsyncAction.prototype._unsubscribe = function () { - var id = this.id; - var scheduler = this.scheduler; - var actions = scheduler.actions; - var index = actions.indexOf(this); - this.work = null; - this.state = null; - this.pending = false; - this.scheduler = null; - if (index !== -1) { - actions.splice(index, 1); - } - if (id != null) { - this.id = this.recycleAsyncId(scheduler, id, null); - } - this.delay = null; - }; - return AsyncAction; -}(_Action__WEBPACK_IMPORTED_MODULE_1__["Action"])); +/* harmony import */ var _internal_operators_finalize__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(274); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "finalize", function() { return _internal_operators_finalize__WEBPACK_IMPORTED_MODULE_31__["finalize"]; }); -//# sourceMappingURL=AsyncAction.js.map +/* harmony import */ var _internal_operators_find__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(275); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "find", function() { return _internal_operators_find__WEBPACK_IMPORTED_MODULE_32__["find"]; }); +/* harmony import */ var _internal_operators_findIndex__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(276); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "findIndex", function() { return _internal_operators_findIndex__WEBPACK_IMPORTED_MODULE_33__["findIndex"]; }); -/***/ }), -/* 197 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony import */ var _internal_operators_first__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(277); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "first", function() { return _internal_operators_first__WEBPACK_IMPORTED_MODULE_34__["first"]; }); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Action", function() { return Action; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(177); -/** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */ +/* harmony import */ var _internal_operators_groupBy__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(162); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "groupBy", function() { return _internal_operators_groupBy__WEBPACK_IMPORTED_MODULE_35__["groupBy"]; }); +/* harmony import */ var _internal_operators_ignoreElements__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(278); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ignoreElements", function() { return _internal_operators_ignoreElements__WEBPACK_IMPORTED_MODULE_36__["ignoreElements"]; }); -var Action = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Action, _super); - function Action(scheduler, work) { - return _super.call(this) || this; - } - Action.prototype.schedule = function (state, delay) { - if (delay === void 0) { - delay = 0; - } - return this; - }; - return Action; -}(_Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"])); +/* harmony import */ var _internal_operators_isEmpty__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(279); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isEmpty", function() { return _internal_operators_isEmpty__WEBPACK_IMPORTED_MODULE_37__["isEmpty"]; }); -//# sourceMappingURL=Action.js.map +/* harmony import */ var _internal_operators_last__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(280); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "last", function() { return _internal_operators_last__WEBPACK_IMPORTED_MODULE_38__["last"]; }); +/* harmony import */ var _internal_operators_map__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(197); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "map", function() { return _internal_operators_map__WEBPACK_IMPORTED_MODULE_39__["map"]; }); -/***/ }), -/* 198 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony import */ var _internal_operators_mapTo__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(282); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mapTo", function() { return _internal_operators_mapTo__WEBPACK_IMPORTED_MODULE_40__["mapTo"]; }); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QueueScheduler", function() { return QueueScheduler; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(199); -/** PURE_IMPORTS_START tslib,_AsyncScheduler PURE_IMPORTS_END */ +/* harmony import */ var _internal_operators_materialize__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(283); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "materialize", function() { return _internal_operators_materialize__WEBPACK_IMPORTED_MODULE_41__["materialize"]; }); +/* harmony import */ var _internal_operators_max__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(284); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "max", function() { return _internal_operators_max__WEBPACK_IMPORTED_MODULE_42__["max"]; }); -var QueueScheduler = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](QueueScheduler, _super); - function QueueScheduler() { - return _super !== null && _super.apply(this, arguments) || this; - } - return QueueScheduler; -}(_AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__["AsyncScheduler"])); +/* harmony import */ var _internal_operators_merge__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(287); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "merge", function() { return _internal_operators_merge__WEBPACK_IMPORTED_MODULE_43__["merge"]; }); -//# sourceMappingURL=QueueScheduler.js.map +/* harmony import */ var _internal_operators_mergeAll__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(212); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mergeAll", function() { return _internal_operators_mergeAll__WEBPACK_IMPORTED_MODULE_44__["mergeAll"]; }); +/* harmony import */ var _internal_operators_mergeMap__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(213); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mergeMap", function() { return _internal_operators_mergeMap__WEBPACK_IMPORTED_MODULE_45__["mergeMap"]; }); -/***/ }), -/* 199 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "flatMap", function() { return _internal_operators_mergeMap__WEBPACK_IMPORTED_MODULE_45__["mergeMap"]; }); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AsyncScheduler", function() { return AsyncScheduler; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Scheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(200); -/** PURE_IMPORTS_START tslib,_Scheduler PURE_IMPORTS_END */ +/* harmony import */ var _internal_operators_mergeMapTo__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(288); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mergeMapTo", function() { return _internal_operators_mergeMapTo__WEBPACK_IMPORTED_MODULE_46__["mergeMapTo"]; }); +/* harmony import */ var _internal_operators_mergeScan__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(289); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mergeScan", function() { return _internal_operators_mergeScan__WEBPACK_IMPORTED_MODULE_47__["mergeScan"]; }); -var AsyncScheduler = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AsyncScheduler, _super); - function AsyncScheduler(SchedulerAction, now) { - if (now === void 0) { - now = _Scheduler__WEBPACK_IMPORTED_MODULE_1__["Scheduler"].now; - } - var _this = _super.call(this, SchedulerAction, function () { - if (AsyncScheduler.delegate && AsyncScheduler.delegate !== _this) { - return AsyncScheduler.delegate.now(); - } - else { - return now(); - } - }) || this; - _this.actions = []; - _this.active = false; - _this.scheduled = undefined; - return _this; - } - AsyncScheduler.prototype.schedule = function (work, delay, state) { - if (delay === void 0) { - delay = 0; - } - if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) { - return AsyncScheduler.delegate.schedule(work, delay, state); - } - else { - return _super.prototype.schedule.call(this, work, delay, state); - } - }; - AsyncScheduler.prototype.flush = function (action) { - var actions = this.actions; - if (this.active) { - actions.push(action); - return; - } - var error; - this.active = true; - do { - if (error = action.execute(action.state, action.delay)) { - break; - } - } while (action = actions.shift()); - this.active = false; - if (error) { - while (action = actions.shift()) { - action.unsubscribe(); - } - throw error; - } - }; - return AsyncScheduler; -}(_Scheduler__WEBPACK_IMPORTED_MODULE_1__["Scheduler"])); +/* harmony import */ var _internal_operators_min__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(290); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "min", function() { return _internal_operators_min__WEBPACK_IMPORTED_MODULE_48__["min"]; }); -//# sourceMappingURL=AsyncScheduler.js.map +/* harmony import */ var _internal_operators_multicast__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(291); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "multicast", function() { return _internal_operators_multicast__WEBPACK_IMPORTED_MODULE_49__["multicast"]; }); +/* harmony import */ var _internal_operators_observeOn__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(172); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "observeOn", function() { return _internal_operators_observeOn__WEBPACK_IMPORTED_MODULE_50__["observeOn"]; }); -/***/ }), -/* 200 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony import */ var _internal_operators_onErrorResumeNext__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(292); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "onErrorResumeNext", function() { return _internal_operators_onErrorResumeNext__WEBPACK_IMPORTED_MODULE_51__["onErrorResumeNext"]; }); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Scheduler", function() { return Scheduler; }); -var Scheduler = /*@__PURE__*/ (function () { - function Scheduler(SchedulerAction, now) { - if (now === void 0) { - now = Scheduler.now; - } - this.SchedulerAction = SchedulerAction; - this.now = now; - } - Scheduler.prototype.schedule = function (work, delay, state) { - if (delay === void 0) { - delay = 0; - } - return new this.SchedulerAction(this, work).schedule(state, delay); - }; - Scheduler.now = function () { return Date.now(); }; - return Scheduler; -}()); +/* harmony import */ var _internal_operators_pairwise__WEBPACK_IMPORTED_MODULE_52__ = __webpack_require__(293); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "pairwise", function() { return _internal_operators_pairwise__WEBPACK_IMPORTED_MODULE_52__["pairwise"]; }); -//# sourceMappingURL=Scheduler.js.map +/* harmony import */ var _internal_operators_partition__WEBPACK_IMPORTED_MODULE_53__ = __webpack_require__(294); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "partition", function() { return _internal_operators_partition__WEBPACK_IMPORTED_MODULE_53__["partition"]; }); +/* harmony import */ var _internal_operators_pluck__WEBPACK_IMPORTED_MODULE_54__ = __webpack_require__(295); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "pluck", function() { return _internal_operators_pluck__WEBPACK_IMPORTED_MODULE_54__["pluck"]; }); -/***/ }), -/* 201 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony import */ var _internal_operators_publish__WEBPACK_IMPORTED_MODULE_55__ = __webpack_require__(296); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "publish", function() { return _internal_operators_publish__WEBPACK_IMPORTED_MODULE_55__["publish"]; }); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "observeOn", function() { return observeOn; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ObserveOnOperator", function() { return ObserveOnOperator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ObserveOnSubscriber", function() { return ObserveOnSubscriber; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ObserveOnMessage", function() { return ObserveOnMessage; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/* harmony import */ var _Notification__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(202); -/** PURE_IMPORTS_START tslib,_Subscriber,_Notification PURE_IMPORTS_END */ +/* harmony import */ var _internal_operators_publishBehavior__WEBPACK_IMPORTED_MODULE_56__ = __webpack_require__(297); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "publishBehavior", function() { return _internal_operators_publishBehavior__WEBPACK_IMPORTED_MODULE_56__["publishBehavior"]; }); +/* harmony import */ var _internal_operators_publishLast__WEBPACK_IMPORTED_MODULE_57__ = __webpack_require__(298); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "publishLast", function() { return _internal_operators_publishLast__WEBPACK_IMPORTED_MODULE_57__["publishLast"]; }); +/* harmony import */ var _internal_operators_publishReplay__WEBPACK_IMPORTED_MODULE_58__ = __webpack_require__(299); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "publishReplay", function() { return _internal_operators_publishReplay__WEBPACK_IMPORTED_MODULE_58__["publishReplay"]; }); -function observeOn(scheduler, delay) { - if (delay === void 0) { - delay = 0; - } - return function observeOnOperatorFunction(source) { - return source.lift(new ObserveOnOperator(scheduler, delay)); - }; -} -var ObserveOnOperator = /*@__PURE__*/ (function () { - function ObserveOnOperator(scheduler, delay) { - if (delay === void 0) { - delay = 0; - } - this.scheduler = scheduler; - this.delay = delay; - } - ObserveOnOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay)); - }; - return ObserveOnOperator; -}()); +/* harmony import */ var _internal_operators_race__WEBPACK_IMPORTED_MODULE_59__ = __webpack_require__(300); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "race", function() { return _internal_operators_race__WEBPACK_IMPORTED_MODULE_59__["race"]; }); -var ObserveOnSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ObserveOnSubscriber, _super); - function ObserveOnSubscriber(destination, scheduler, delay) { - if (delay === void 0) { - delay = 0; - } - var _this = _super.call(this, destination) || this; - _this.scheduler = scheduler; - _this.delay = delay; - return _this; - } - ObserveOnSubscriber.dispatch = function (arg) { - var notification = arg.notification, destination = arg.destination; - notification.observe(destination); - this.unsubscribe(); - }; - ObserveOnSubscriber.prototype.scheduleMessage = function (notification) { - var destination = this.destination; - destination.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination))); - }; - ObserveOnSubscriber.prototype._next = function (value) { - this.scheduleMessage(_Notification__WEBPACK_IMPORTED_MODULE_2__["Notification"].createNext(value)); - }; - ObserveOnSubscriber.prototype._error = function (err) { - this.scheduleMessage(_Notification__WEBPACK_IMPORTED_MODULE_2__["Notification"].createError(err)); - this.unsubscribe(); - }; - ObserveOnSubscriber.prototype._complete = function () { - this.scheduleMessage(_Notification__WEBPACK_IMPORTED_MODULE_2__["Notification"].createComplete()); - this.unsubscribe(); - }; - return ObserveOnSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +/* harmony import */ var _internal_operators_reduce__WEBPACK_IMPORTED_MODULE_60__ = __webpack_require__(285); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "reduce", function() { return _internal_operators_reduce__WEBPACK_IMPORTED_MODULE_60__["reduce"]; }); -var ObserveOnMessage = /*@__PURE__*/ (function () { - function ObserveOnMessage(notification, destination) { - this.notification = notification; - this.destination = destination; - } - return ObserveOnMessage; -}()); +/* harmony import */ var _internal_operators_repeat__WEBPACK_IMPORTED_MODULE_61__ = __webpack_require__(301); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "repeat", function() { return _internal_operators_repeat__WEBPACK_IMPORTED_MODULE_61__["repeat"]; }); -//# sourceMappingURL=observeOn.js.map +/* harmony import */ var _internal_operators_repeatWhen__WEBPACK_IMPORTED_MODULE_62__ = __webpack_require__(302); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "repeatWhen", function() { return _internal_operators_repeatWhen__WEBPACK_IMPORTED_MODULE_62__["repeatWhen"]; }); +/* harmony import */ var _internal_operators_retry__WEBPACK_IMPORTED_MODULE_63__ = __webpack_require__(303); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "retry", function() { return _internal_operators_retry__WEBPACK_IMPORTED_MODULE_63__["retry"]; }); -/***/ }), -/* 202 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony import */ var _internal_operators_retryWhen__WEBPACK_IMPORTED_MODULE_64__ = __webpack_require__(304); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "retryWhen", function() { return _internal_operators_retryWhen__WEBPACK_IMPORTED_MODULE_64__["retryWhen"]; }); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NotificationKind", function() { return NotificationKind; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Notification", function() { return Notification; }); -/* harmony import */ var _observable_empty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(203); -/* harmony import */ var _observable_of__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(204); -/* harmony import */ var _observable_throwError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(209); -/** PURE_IMPORTS_START _observable_empty,_observable_of,_observable_throwError PURE_IMPORTS_END */ +/* harmony import */ var _internal_operators_refCount__WEBPACK_IMPORTED_MODULE_65__ = __webpack_require__(161); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "refCount", function() { return _internal_operators_refCount__WEBPACK_IMPORTED_MODULE_65__["refCount"]; }); +/* harmony import */ var _internal_operators_sample__WEBPACK_IMPORTED_MODULE_66__ = __webpack_require__(305); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sample", function() { return _internal_operators_sample__WEBPACK_IMPORTED_MODULE_66__["sample"]; }); +/* harmony import */ var _internal_operators_sampleTime__WEBPACK_IMPORTED_MODULE_67__ = __webpack_require__(306); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sampleTime", function() { return _internal_operators_sampleTime__WEBPACK_IMPORTED_MODULE_67__["sampleTime"]; }); -var NotificationKind; -/*@__PURE__*/ (function (NotificationKind) { - NotificationKind["NEXT"] = "N"; - NotificationKind["ERROR"] = "E"; - NotificationKind["COMPLETE"] = "C"; -})(NotificationKind || (NotificationKind = {})); -var Notification = /*@__PURE__*/ (function () { - function Notification(kind, value, error) { - this.kind = kind; - this.value = value; - this.error = error; - this.hasValue = kind === 'N'; - } - Notification.prototype.observe = function (observer) { - switch (this.kind) { - case 'N': - return observer.next && observer.next(this.value); - case 'E': - return observer.error && observer.error(this.error); - case 'C': - return observer.complete && observer.complete(); - } - }; - Notification.prototype.do = function (next, error, complete) { - var kind = this.kind; - switch (kind) { - case 'N': - return next && next(this.value); - case 'E': - return error && error(this.error); - case 'C': - return complete && complete(); - } - }; - Notification.prototype.accept = function (nextOrObserver, error, complete) { - if (nextOrObserver && typeof nextOrObserver.next === 'function') { - return this.observe(nextOrObserver); - } - else { - return this.do(nextOrObserver, error, complete); - } - }; - Notification.prototype.toObservable = function () { - var kind = this.kind; - switch (kind) { - case 'N': - return Object(_observable_of__WEBPACK_IMPORTED_MODULE_1__["of"])(this.value); - case 'E': - return Object(_observable_throwError__WEBPACK_IMPORTED_MODULE_2__["throwError"])(this.error); - case 'C': - return Object(_observable_empty__WEBPACK_IMPORTED_MODULE_0__["empty"])(); - } - throw new Error('unexpected notification kind value'); - }; - Notification.createNext = function (value) { - if (typeof value !== 'undefined') { - return new Notification('N', value); - } - return Notification.undefinedValueNotification; - }; - Notification.createError = function (err) { - return new Notification('E', undefined, err); - }; - Notification.createComplete = function () { - return Notification.completeNotification; - }; - Notification.completeNotification = new Notification('C'); - Notification.undefinedValueNotification = new Notification('N', undefined); - return Notification; -}()); +/* harmony import */ var _internal_operators_scan__WEBPACK_IMPORTED_MODULE_68__ = __webpack_require__(286); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "scan", function() { return _internal_operators_scan__WEBPACK_IMPORTED_MODULE_68__["scan"]; }); -//# sourceMappingURL=Notification.js.map +/* harmony import */ var _internal_operators_sequenceEqual__WEBPACK_IMPORTED_MODULE_69__ = __webpack_require__(307); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sequenceEqual", function() { return _internal_operators_sequenceEqual__WEBPACK_IMPORTED_MODULE_69__["sequenceEqual"]; }); +/* harmony import */ var _internal_operators_share__WEBPACK_IMPORTED_MODULE_70__ = __webpack_require__(308); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "share", function() { return _internal_operators_share__WEBPACK_IMPORTED_MODULE_70__["share"]; }); -/***/ }), -/* 203 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony import */ var _internal_operators_shareReplay__WEBPACK_IMPORTED_MODULE_71__ = __webpack_require__(309); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "shareReplay", function() { return _internal_operators_shareReplay__WEBPACK_IMPORTED_MODULE_71__["shareReplay"]; }); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EMPTY", function() { return EMPTY; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "empty", function() { return empty; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ +/* harmony import */ var _internal_operators_single__WEBPACK_IMPORTED_MODULE_72__ = __webpack_require__(310); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "single", function() { return _internal_operators_single__WEBPACK_IMPORTED_MODULE_72__["single"]; }); -var EMPTY = /*@__PURE__*/ new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { return subscriber.complete(); }); -function empty(scheduler) { - return scheduler ? emptyScheduled(scheduler) : EMPTY; -} -function emptyScheduled(scheduler) { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { return scheduler.schedule(function () { return subscriber.complete(); }); }); -} -//# sourceMappingURL=empty.js.map +/* harmony import */ var _internal_operators_skip__WEBPACK_IMPORTED_MODULE_73__ = __webpack_require__(311); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "skip", function() { return _internal_operators_skip__WEBPACK_IMPORTED_MODULE_73__["skip"]; }); +/* harmony import */ var _internal_operators_skipLast__WEBPACK_IMPORTED_MODULE_74__ = __webpack_require__(312); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "skipLast", function() { return _internal_operators_skipLast__WEBPACK_IMPORTED_MODULE_74__["skipLast"]; }); -/***/ }), -/* 204 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony import */ var _internal_operators_skipUntil__WEBPACK_IMPORTED_MODULE_75__ = __webpack_require__(313); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "skipUntil", function() { return _internal_operators_skipUntil__WEBPACK_IMPORTED_MODULE_75__["skipUntil"]; }); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "of", function() { return of; }); -/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(205); -/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(206); -/* harmony import */ var _scheduled_scheduleArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(208); -/** PURE_IMPORTS_START _util_isScheduler,_fromArray,_scheduled_scheduleArray PURE_IMPORTS_END */ +/* harmony import */ var _internal_operators_skipWhile__WEBPACK_IMPORTED_MODULE_76__ = __webpack_require__(314); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "skipWhile", function() { return _internal_operators_skipWhile__WEBPACK_IMPORTED_MODULE_76__["skipWhile"]; }); +/* harmony import */ var _internal_operators_startWith__WEBPACK_IMPORTED_MODULE_77__ = __webpack_require__(315); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "startWith", function() { return _internal_operators_startWith__WEBPACK_IMPORTED_MODULE_77__["startWith"]; }); +/* harmony import */ var _internal_operators_subscribeOn__WEBPACK_IMPORTED_MODULE_78__ = __webpack_require__(316); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "subscribeOn", function() { return _internal_operators_subscribeOn__WEBPACK_IMPORTED_MODULE_78__["subscribeOn"]; }); -function of() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var scheduler = args[args.length - 1]; - if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_0__["isScheduler"])(scheduler)) { - args.pop(); - return Object(_scheduled_scheduleArray__WEBPACK_IMPORTED_MODULE_2__["scheduleArray"])(args, scheduler); - } - else { - return Object(_fromArray__WEBPACK_IMPORTED_MODULE_1__["fromArray"])(args); - } -} -//# sourceMappingURL=of.js.map +/* harmony import */ var _internal_operators_switchAll__WEBPACK_IMPORTED_MODULE_79__ = __webpack_require__(318); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "switchAll", function() { return _internal_operators_switchAll__WEBPACK_IMPORTED_MODULE_79__["switchAll"]; }); +/* harmony import */ var _internal_operators_switchMap__WEBPACK_IMPORTED_MODULE_80__ = __webpack_require__(319); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "switchMap", function() { return _internal_operators_switchMap__WEBPACK_IMPORTED_MODULE_80__["switchMap"]; }); -/***/ }), -/* 205 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony import */ var _internal_operators_switchMapTo__WEBPACK_IMPORTED_MODULE_81__ = __webpack_require__(320); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "switchMapTo", function() { return _internal_operators_switchMapTo__WEBPACK_IMPORTED_MODULE_81__["switchMapTo"]; }); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isScheduler", function() { return isScheduler; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function isScheduler(value) { - return value && typeof value.schedule === 'function'; -} -//# sourceMappingURL=isScheduler.js.map +/* harmony import */ var _internal_operators_take__WEBPACK_IMPORTED_MODULE_82__ = __webpack_require__(268); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "take", function() { return _internal_operators_take__WEBPACK_IMPORTED_MODULE_82__["take"]; }); +/* harmony import */ var _internal_operators_takeLast__WEBPACK_IMPORTED_MODULE_83__ = __webpack_require__(281); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "takeLast", function() { return _internal_operators_takeLast__WEBPACK_IMPORTED_MODULE_83__["takeLast"]; }); -/***/ }), -/* 206 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony import */ var _internal_operators_takeUntil__WEBPACK_IMPORTED_MODULE_84__ = __webpack_require__(321); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "takeUntil", function() { return _internal_operators_takeUntil__WEBPACK_IMPORTED_MODULE_84__["takeUntil"]; }); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromArray", function() { return fromArray; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _util_subscribeToArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(207); -/* harmony import */ var _scheduled_scheduleArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(208); -/** PURE_IMPORTS_START _Observable,_util_subscribeToArray,_scheduled_scheduleArray PURE_IMPORTS_END */ +/* harmony import */ var _internal_operators_takeWhile__WEBPACK_IMPORTED_MODULE_85__ = __webpack_require__(322); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "takeWhile", function() { return _internal_operators_takeWhile__WEBPACK_IMPORTED_MODULE_85__["takeWhile"]; }); +/* harmony import */ var _internal_operators_tap__WEBPACK_IMPORTED_MODULE_86__ = __webpack_require__(323); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "tap", function() { return _internal_operators_tap__WEBPACK_IMPORTED_MODULE_86__["tap"]; }); +/* harmony import */ var _internal_operators_throttle__WEBPACK_IMPORTED_MODULE_87__ = __webpack_require__(324); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "throttle", function() { return _internal_operators_throttle__WEBPACK_IMPORTED_MODULE_87__["throttle"]; }); -function fromArray(input, scheduler) { - if (!scheduler) { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](Object(_util_subscribeToArray__WEBPACK_IMPORTED_MODULE_1__["subscribeToArray"])(input)); - } - else { - return Object(_scheduled_scheduleArray__WEBPACK_IMPORTED_MODULE_2__["scheduleArray"])(input, scheduler); - } -} -//# sourceMappingURL=fromArray.js.map +/* harmony import */ var _internal_operators_throttleTime__WEBPACK_IMPORTED_MODULE_88__ = __webpack_require__(325); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "throttleTime", function() { return _internal_operators_throttleTime__WEBPACK_IMPORTED_MODULE_88__["throttleTime"]; }); +/* harmony import */ var _internal_operators_throwIfEmpty__WEBPACK_IMPORTED_MODULE_89__ = __webpack_require__(267); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "throwIfEmpty", function() { return _internal_operators_throwIfEmpty__WEBPACK_IMPORTED_MODULE_89__["throwIfEmpty"]; }); -/***/ }), -/* 207 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony import */ var _internal_operators_timeInterval__WEBPACK_IMPORTED_MODULE_90__ = __webpack_require__(326); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "timeInterval", function() { return _internal_operators_timeInterval__WEBPACK_IMPORTED_MODULE_90__["timeInterval"]; }); + +/* harmony import */ var _internal_operators_timeout__WEBPACK_IMPORTED_MODULE_91__ = __webpack_require__(327); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "timeout", function() { return _internal_operators_timeout__WEBPACK_IMPORTED_MODULE_91__["timeout"]; }); + +/* harmony import */ var _internal_operators_timeoutWith__WEBPACK_IMPORTED_MODULE_92__ = __webpack_require__(328); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "timeoutWith", function() { return _internal_operators_timeoutWith__WEBPACK_IMPORTED_MODULE_92__["timeoutWith"]; }); + +/* harmony import */ var _internal_operators_timestamp__WEBPACK_IMPORTED_MODULE_93__ = __webpack_require__(329); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "timestamp", function() { return _internal_operators_timestamp__WEBPACK_IMPORTED_MODULE_93__["timestamp"]; }); + +/* harmony import */ var _internal_operators_toArray__WEBPACK_IMPORTED_MODULE_94__ = __webpack_require__(330); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toArray", function() { return _internal_operators_toArray__WEBPACK_IMPORTED_MODULE_94__["toArray"]; }); + +/* harmony import */ var _internal_operators_window__WEBPACK_IMPORTED_MODULE_95__ = __webpack_require__(331); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "window", function() { return _internal_operators_window__WEBPACK_IMPORTED_MODULE_95__["window"]; }); + +/* harmony import */ var _internal_operators_windowCount__WEBPACK_IMPORTED_MODULE_96__ = __webpack_require__(332); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "windowCount", function() { return _internal_operators_windowCount__WEBPACK_IMPORTED_MODULE_96__["windowCount"]; }); + +/* harmony import */ var _internal_operators_windowTime__WEBPACK_IMPORTED_MODULE_97__ = __webpack_require__(333); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "windowTime", function() { return _internal_operators_windowTime__WEBPACK_IMPORTED_MODULE_97__["windowTime"]; }); + +/* harmony import */ var _internal_operators_windowToggle__WEBPACK_IMPORTED_MODULE_98__ = __webpack_require__(334); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "windowToggle", function() { return _internal_operators_windowToggle__WEBPACK_IMPORTED_MODULE_98__["windowToggle"]; }); + +/* harmony import */ var _internal_operators_windowWhen__WEBPACK_IMPORTED_MODULE_99__ = __webpack_require__(335); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "windowWhen", function() { return _internal_operators_windowWhen__WEBPACK_IMPORTED_MODULE_99__["windowWhen"]; }); + +/* harmony import */ var _internal_operators_withLatestFrom__WEBPACK_IMPORTED_MODULE_100__ = __webpack_require__(336); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "withLatestFrom", function() { return _internal_operators_withLatestFrom__WEBPACK_IMPORTED_MODULE_100__["withLatestFrom"]; }); + +/* harmony import */ var _internal_operators_zip__WEBPACK_IMPORTED_MODULE_101__ = __webpack_require__(337); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "zip", function() { return _internal_operators_zip__WEBPACK_IMPORTED_MODULE_101__["zip"]; }); + +/* harmony import */ var _internal_operators_zipAll__WEBPACK_IMPORTED_MODULE_102__ = __webpack_require__(338); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "zipAll", function() { return _internal_operators_zipAll__WEBPACK_IMPORTED_MODULE_102__["zipAll"]; }); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeToArray", function() { return subscribeToArray; }); /** PURE_IMPORTS_START PURE_IMPORTS_END */ -var subscribeToArray = function (array) { - return function (subscriber) { - for (var i = 0, len = array.length; i < len && !subscriber.closed; i++) { - subscriber.next(array[i]); - } - subscriber.complete(); - }; -}; -//# sourceMappingURL=subscribeToArray.js.map -/***/ }), -/* 208 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scheduleArray", function() { return scheduleArray; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(177); -/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ -function scheduleArray(input, scheduler) { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { - var sub = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"](); - var i = 0; - sub.add(scheduler.schedule(function () { - if (i === input.length) { - subscriber.complete(); - return; - } - subscriber.next(input[i++]); - if (!subscriber.closed) { - sub.add(this.schedule()); - } - })); - return sub; - }); -} -//# sourceMappingURL=scheduleArray.js.map -/***/ }), -/* 209 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "throwError", function() { return throwError; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ -function throwError(error, scheduler) { - if (!scheduler) { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { return subscriber.error(error); }); - } - else { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { return scheduler.schedule(dispatch, 0, { error: error, subscriber: subscriber }); }); - } -} -function dispatch(_a) { - var error = _a.error, subscriber = _a.subscriber; - subscriber.error(error); -} -//# sourceMappingURL=throwError.js.map -/***/ }), -/* 210 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AsyncSubject", function() { return AsyncSubject; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(187); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(177); -/** PURE_IMPORTS_START tslib,_Subject,_Subscription PURE_IMPORTS_END */ -var AsyncSubject = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AsyncSubject, _super); - function AsyncSubject() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.value = null; - _this.hasNext = false; - _this.hasCompleted = false; - return _this; - } - AsyncSubject.prototype._subscribe = function (subscriber) { - if (this.hasError) { - subscriber.error(this.thrownError); - return _Subscription__WEBPACK_IMPORTED_MODULE_2__["Subscription"].EMPTY; - } - else if (this.hasCompleted && this.hasNext) { - subscriber.next(this.value); - subscriber.complete(); - return _Subscription__WEBPACK_IMPORTED_MODULE_2__["Subscription"].EMPTY; - } - return _super.prototype._subscribe.call(this, subscriber); - }; - AsyncSubject.prototype.next = function (value) { - if (!this.hasCompleted) { - this.value = value; - this.hasNext = true; - } - }; - AsyncSubject.prototype.error = function (error) { - if (!this.hasCompleted) { - _super.prototype.error.call(this, error); - } - }; - AsyncSubject.prototype.complete = function () { - this.hasCompleted = true; - if (this.hasNext) { - _super.prototype.next.call(this, this.value); - } - _super.prototype.complete.call(this); - }; - return AsyncSubject; -}(_Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"])); -//# sourceMappingURL=AsyncSubject.js.map -/***/ }), -/* 211 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "asap", function() { return asap; }); -/* harmony import */ var _AsapAction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(212); -/* harmony import */ var _AsapScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(214); -/** PURE_IMPORTS_START _AsapAction,_AsapScheduler PURE_IMPORTS_END */ -var asap = /*@__PURE__*/ new _AsapScheduler__WEBPACK_IMPORTED_MODULE_1__["AsapScheduler"](_AsapAction__WEBPACK_IMPORTED_MODULE_0__["AsapAction"]); -//# sourceMappingURL=asap.js.map -/***/ }), -/* 212 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AsapAction", function() { return AsapAction; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _util_Immediate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(213); -/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(196); -/** PURE_IMPORTS_START tslib,_util_Immediate,_AsyncAction PURE_IMPORTS_END */ -var AsapAction = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AsapAction, _super); - function AsapAction(scheduler, work) { - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - return _this; - } - AsapAction.prototype.requestAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - if (delay !== null && delay > 0) { - return _super.prototype.requestAsyncId.call(this, scheduler, id, delay); - } - scheduler.actions.push(this); - return scheduler.scheduled || (scheduler.scheduled = _util_Immediate__WEBPACK_IMPORTED_MODULE_1__["Immediate"].setImmediate(scheduler.flush.bind(scheduler, null))); - }; - AsapAction.prototype.recycleAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) { - return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay); - } - if (scheduler.actions.length === 0) { - _util_Immediate__WEBPACK_IMPORTED_MODULE_1__["Immediate"].clearImmediate(id); - scheduler.scheduled = undefined; - } - return undefined; - }; - return AsapAction; -}(_AsyncAction__WEBPACK_IMPORTED_MODULE_2__["AsyncAction"])); -//# sourceMappingURL=AsapAction.js.map -/***/ }), -/* 213 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Immediate", function() { return Immediate; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var nextHandle = 1; -var tasksByHandle = {}; -function runIfPresent(handle) { - var cb = tasksByHandle[handle]; - if (cb) { - cb(); - } -} -var Immediate = { - setImmediate: function (cb) { - var handle = nextHandle++; - tasksByHandle[handle] = cb; - Promise.resolve().then(function () { return runIfPresent(handle); }); - return handle; - }, - clearImmediate: function (handle) { - delete tasksByHandle[handle]; - }, -}; -//# sourceMappingURL=Immediate.js.map -/***/ }), -/* 214 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AsapScheduler", function() { return AsapScheduler; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(199); -/** PURE_IMPORTS_START tslib,_AsyncScheduler PURE_IMPORTS_END */ -var AsapScheduler = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AsapScheduler, _super); - function AsapScheduler() { - return _super !== null && _super.apply(this, arguments) || this; - } - AsapScheduler.prototype.flush = function (action) { - this.active = true; - this.scheduled = undefined; - var actions = this.actions; - var error; - var index = -1; - var count = actions.length; - action = action || actions.shift(); - do { - if (error = action.execute(action.state, action.delay)) { - break; - } - } while (++index < count && (action = actions.shift())); - this.active = false; - if (error) { - while (++index < count && (action = actions.shift())) { - action.unsubscribe(); - } - throw error; - } - }; - return AsapScheduler; -}(_AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__["AsyncScheduler"])); -//# sourceMappingURL=AsapScheduler.js.map -/***/ }), -/* 215 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "async", function() { return async; }); -/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(196); -/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(199); -/** PURE_IMPORTS_START _AsyncAction,_AsyncScheduler PURE_IMPORTS_END */ -var async = /*@__PURE__*/ new _AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__["AsyncScheduler"](_AsyncAction__WEBPACK_IMPORTED_MODULE_0__["AsyncAction"]); -//# sourceMappingURL=async.js.map -/***/ }), -/* 216 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "animationFrame", function() { return animationFrame; }); -/* harmony import */ var _AnimationFrameAction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(217); -/* harmony import */ var _AnimationFrameScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(218); -/** PURE_IMPORTS_START _AnimationFrameAction,_AnimationFrameScheduler PURE_IMPORTS_END */ -var animationFrame = /*@__PURE__*/ new _AnimationFrameScheduler__WEBPACK_IMPORTED_MODULE_1__["AnimationFrameScheduler"](_AnimationFrameAction__WEBPACK_IMPORTED_MODULE_0__["AnimationFrameAction"]); -//# sourceMappingURL=animationFrame.js.map -/***/ }), -/* 217 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationFrameAction", function() { return AnimationFrameAction; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(196); -/** PURE_IMPORTS_START tslib,_AsyncAction PURE_IMPORTS_END */ -var AnimationFrameAction = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AnimationFrameAction, _super); - function AnimationFrameAction(scheduler, work) { - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - return _this; - } - AnimationFrameAction.prototype.requestAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - if (delay !== null && delay > 0) { - return _super.prototype.requestAsyncId.call(this, scheduler, id, delay); - } - scheduler.actions.push(this); - return scheduler.scheduled || (scheduler.scheduled = requestAnimationFrame(function () { return scheduler.flush(null); })); - }; - AnimationFrameAction.prototype.recycleAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) { - return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay); - } - if (scheduler.actions.length === 0) { - cancelAnimationFrame(id); - scheduler.scheduled = undefined; - } - return undefined; - }; - return AnimationFrameAction; -}(_AsyncAction__WEBPACK_IMPORTED_MODULE_1__["AsyncAction"])); -//# sourceMappingURL=AnimationFrameAction.js.map -/***/ }), -/* 218 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationFrameScheduler", function() { return AnimationFrameScheduler; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(199); -/** PURE_IMPORTS_START tslib,_AsyncScheduler PURE_IMPORTS_END */ -var AnimationFrameScheduler = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AnimationFrameScheduler, _super); - function AnimationFrameScheduler() { - return _super !== null && _super.apply(this, arguments) || this; - } - AnimationFrameScheduler.prototype.flush = function (action) { - this.active = true; - this.scheduled = undefined; - var actions = this.actions; - var error; - var index = -1; - var count = actions.length; - action = action || actions.shift(); - do { - if (error = action.execute(action.state, action.delay)) { - break; - } - } while (++index < count && (action = actions.shift())); - this.active = false; - if (error) { - while (++index < count && (action = actions.shift())) { - action.unsubscribe(); - } - throw error; - } - }; - return AnimationFrameScheduler; -}(_AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__["AsyncScheduler"])); -//# sourceMappingURL=AnimationFrameScheduler.js.map + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +//# sourceMappingURL=index.js.map /***/ }), -/* 219 */ +/* 242 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VirtualTimeScheduler", function() { return VirtualTimeScheduler; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VirtualAction", function() { return VirtualAction; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(196); -/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(199); -/** PURE_IMPORTS_START tslib,_AsyncAction,_AsyncScheduler PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "audit", function() { return audit; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -var VirtualTimeScheduler = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VirtualTimeScheduler, _super); - function VirtualTimeScheduler(SchedulerAction, maxFrames) { - if (SchedulerAction === void 0) { - SchedulerAction = VirtualAction; - } - if (maxFrames === void 0) { - maxFrames = Number.POSITIVE_INFINITY; - } - var _this = _super.call(this, SchedulerAction, function () { return _this.frame; }) || this; - _this.maxFrames = maxFrames; - _this.frame = 0; - _this.index = -1; - return _this; +function audit(durationSelector) { + return function auditOperatorFunction(source) { + return source.lift(new AuditOperator(durationSelector)); + }; +} +var AuditOperator = /*@__PURE__*/ (function () { + function AuditOperator(durationSelector) { + this.durationSelector = durationSelector; } - VirtualTimeScheduler.prototype.flush = function () { - var _a = this, actions = _a.actions, maxFrames = _a.maxFrames; - var error, action; - while ((action = actions[0]) && action.delay <= maxFrames) { - actions.shift(); - this.frame = action.delay; - if (error = action.execute(action.state, action.delay)) { - break; - } - } - if (error) { - while (action = actions.shift()) { - action.unsubscribe(); - } - throw error; - } + AuditOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new AuditSubscriber(subscriber, this.durationSelector)); }; - VirtualTimeScheduler.frameTimeFactor = 10; - return VirtualTimeScheduler; -}(_AsyncScheduler__WEBPACK_IMPORTED_MODULE_2__["AsyncScheduler"])); - -var VirtualAction = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VirtualAction, _super); - function VirtualAction(scheduler, work, index) { - if (index === void 0) { - index = scheduler.index += 1; - } - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - _this.index = index; - _this.active = true; - _this.index = scheduler.index = index; + return AuditOperator; +}()); +var AuditSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AuditSubscriber, _super); + function AuditSubscriber(destination, durationSelector) { + var _this = _super.call(this, destination) || this; + _this.durationSelector = durationSelector; + _this.hasValue = false; return _this; } - VirtualAction.prototype.schedule = function (state, delay) { - if (delay === void 0) { - delay = 0; - } - if (!this.id) { - return _super.prototype.schedule.call(this, state, delay); - } - this.active = false; - var action = new VirtualAction(this.scheduler, this.work); - this.add(action); - return action.schedule(state, delay); - }; - VirtualAction.prototype.requestAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - this.delay = scheduler.frame + delay; - var actions = scheduler.actions; - actions.push(this); - actions.sort(VirtualAction.sortActions); - return true; - }; - VirtualAction.prototype.recycleAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - return undefined; - }; - VirtualAction.prototype._execute = function (state, delay) { - if (this.active === true) { - return _super.prototype._execute.call(this, state, delay); - } - }; - VirtualAction.sortActions = function (a, b) { - if (a.delay === b.delay) { - if (a.index === b.index) { - return 0; + AuditSubscriber.prototype._next = function (value) { + this.value = value; + this.hasValue = true; + if (!this.throttled) { + var duration = void 0; + try { + var durationSelector = this.durationSelector; + duration = durationSelector(value); } - else if (a.index > b.index) { - return 1; + catch (err) { + return this.destination.error(err); + } + var innerSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, duration); + if (!innerSubscription || innerSubscription.closed) { + this.clearThrottle(); } else { - return -1; + this.add(this.throttled = innerSubscription); } } - else if (a.delay > b.delay) { - return 1; + }; + AuditSubscriber.prototype.clearThrottle = function () { + var _a = this, value = _a.value, hasValue = _a.hasValue, throttled = _a.throttled; + if (throttled) { + this.remove(throttled); + this.throttled = null; + throttled.unsubscribe(); } - else { - return -1; + if (hasValue) { + this.value = null; + this.hasValue = false; + this.destination.next(value); } }; - return VirtualAction; -}(_AsyncAction__WEBPACK_IMPORTED_MODULE_1__["AsyncAction"])); - -//# sourceMappingURL=VirtualTimeScheduler.js.map + AuditSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex) { + this.clearThrottle(); + }; + AuditSubscriber.prototype.notifyComplete = function () { + this.clearThrottle(); + }; + return AuditSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); +//# sourceMappingURL=audit.js.map /***/ }), -/* 220 */ +/* 243 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "identity", function() { return identity; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function identity(x) { - return x; -} -//# sourceMappingURL=identity.js.map - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "auditTime", function() { return auditTime; }); +/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(186); +/* harmony import */ var _audit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(242); +/* harmony import */ var _observable_timer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(238); +/** PURE_IMPORTS_START _scheduler_async,_audit,_observable_timer PURE_IMPORTS_END */ -/***/ }), -/* 221 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isObservable", function() { return isObservable; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ -function isObservable(obj) { - return !!obj && (obj instanceof _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"] || (typeof obj.lift === 'function' && typeof obj.subscribe === 'function')); +function auditTime(duration, scheduler) { + if (scheduler === void 0) { + scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_0__["async"]; + } + return Object(_audit__WEBPACK_IMPORTED_MODULE_1__["audit"])(function () { return Object(_observable_timer__WEBPACK_IMPORTED_MODULE_2__["timer"])(duration, scheduler); }); } -//# sourceMappingURL=isObservable.js.map +//# sourceMappingURL=auditTime.js.map /***/ }), -/* 222 */ +/* 244 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArgumentOutOfRangeError", function() { return ArgumentOutOfRangeError; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var ArgumentOutOfRangeErrorImpl = /*@__PURE__*/ (function () { - function ArgumentOutOfRangeErrorImpl() { - Error.call(this); - this.message = 'argument out of range'; - this.name = 'ArgumentOutOfRangeError'; - return this; - } - ArgumentOutOfRangeErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); - return ArgumentOutOfRangeErrorImpl; -})(); -var ArgumentOutOfRangeError = ArgumentOutOfRangeErrorImpl; -//# sourceMappingURL=ArgumentOutOfRangeError.js.map +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buffer", function() { return buffer; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -/***/ }), -/* 223 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EmptyError", function() { return EmptyError; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var EmptyErrorImpl = /*@__PURE__*/ (function () { - function EmptyErrorImpl() { - Error.call(this); - this.message = 'no elements in sequence'; - this.name = 'EmptyError'; - return this; +function buffer(closingNotifier) { + return function bufferOperatorFunction(source) { + return source.lift(new BufferOperator(closingNotifier)); + }; +} +var BufferOperator = /*@__PURE__*/ (function () { + function BufferOperator(closingNotifier) { + this.closingNotifier = closingNotifier; } - EmptyErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); - return EmptyErrorImpl; -})(); -var EmptyError = EmptyErrorImpl; -//# sourceMappingURL=EmptyError.js.map - - -/***/ }), -/* 224 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimeoutError", function() { return TimeoutError; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var TimeoutErrorImpl = /*@__PURE__*/ (function () { - function TimeoutErrorImpl() { - Error.call(this); - this.message = 'Timeout has occurred'; - this.name = 'TimeoutError'; - return this; + BufferOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier)); + }; + return BufferOperator; +}()); +var BufferSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BufferSubscriber, _super); + function BufferSubscriber(destination, closingNotifier) { + var _this = _super.call(this, destination) || this; + _this.buffer = []; + _this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(_this, closingNotifier)); + return _this; } - TimeoutErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); - return TimeoutErrorImpl; -})(); -var TimeoutError = TimeoutErrorImpl; -//# sourceMappingURL=TimeoutError.js.map + BufferSubscriber.prototype._next = function (value) { + this.buffer.push(value); + }; + BufferSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + var buffer = this.buffer; + this.buffer = []; + this.destination.next(buffer); + }; + return BufferSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); +//# sourceMappingURL=buffer.js.map /***/ }), -/* 225 */ +/* 245 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bindCallback", function() { return bindCallback; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(210); -/* harmony import */ var _operators_map__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(226); -/* harmony import */ var _util_canReportError__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(171); -/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(178); -/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(205); -/** PURE_IMPORTS_START _Observable,_AsyncSubject,_operators_map,_util_canReportError,_util_isArray,_util_isScheduler PURE_IMPORTS_END */ - - - - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bufferCount", function() { return bufferCount; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function bindCallback(callbackFunc, resultSelector, scheduler) { - if (resultSelector) { - if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_5__["isScheduler"])(resultSelector)) { - scheduler = resultSelector; - } - else { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return bindCallback(callbackFunc, scheduler).apply(void 0, args).pipe(Object(_operators_map__WEBPACK_IMPORTED_MODULE_2__["map"])(function (args) { return Object(_util_isArray__WEBPACK_IMPORTED_MODULE_4__["isArray"])(args) ? resultSelector.apply(void 0, args) : resultSelector(args); })); - }; - } +function bufferCount(bufferSize, startBufferEvery) { + if (startBufferEvery === void 0) { + startBufferEvery = null; } - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var context = this; - var subject; - var params = { - context: context, - subject: subject, - callbackFunc: callbackFunc, - scheduler: scheduler, - }; - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { - if (!scheduler) { - if (!subject) { - subject = new _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__["AsyncSubject"](); - var handler = function () { - var innerArgs = []; - for (var _i = 0; _i < arguments.length; _i++) { - innerArgs[_i] = arguments[_i]; - } - subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs); - subject.complete(); - }; - try { - callbackFunc.apply(context, args.concat([handler])); - } - catch (err) { - if (Object(_util_canReportError__WEBPACK_IMPORTED_MODULE_3__["canReportError"])(subject)) { - subject.error(err); - } - else { - console.warn(err); - } - } - } - return subject.subscribe(subscriber); - } - else { - var state = { - args: args, subscriber: subscriber, params: params, - }; - return scheduler.schedule(dispatch, 0, state); - } - }); + return function bufferCountOperatorFunction(source) { + return source.lift(new BufferCountOperator(bufferSize, startBufferEvery)); }; } -function dispatch(state) { - var _this = this; - var self = this; - var args = state.args, subscriber = state.subscriber, params = state.params; - var callbackFunc = params.callbackFunc, context = params.context, scheduler = params.scheduler; - var subject = params.subject; - if (!subject) { - subject = params.subject = new _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__["AsyncSubject"](); - var handler = function () { - var innerArgs = []; - for (var _i = 0; _i < arguments.length; _i++) { - innerArgs[_i] = arguments[_i]; - } - var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs; - _this.add(scheduler.schedule(dispatchNext, 0, { value: value, subject: subject })); - }; - try { - callbackFunc.apply(context, args.concat([handler])); +var BufferCountOperator = /*@__PURE__*/ (function () { + function BufferCountOperator(bufferSize, startBufferEvery) { + this.bufferSize = bufferSize; + this.startBufferEvery = startBufferEvery; + if (!startBufferEvery || bufferSize === startBufferEvery) { + this.subscriberClass = BufferCountSubscriber; } - catch (err) { - subject.error(err); + else { + this.subscriberClass = BufferSkipCountSubscriber; } } - this.add(subject.subscribe(subscriber)); -} -function dispatchNext(state) { - var value = state.value, subject = state.subject; - subject.next(value); - subject.complete(); -} -function dispatchError(state) { - var err = state.err, subject = state.subject; - subject.error(err); -} -//# sourceMappingURL=bindCallback.js.map - - -/***/ }), -/* 226 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "map", function() { return map; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MapOperator", function() { return MapOperator; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ - - -function map(project, thisArg) { - return function mapOperation(source) { - if (typeof project !== 'function') { - throw new TypeError('argument is not a function. Are you looking for `mapTo()`?'); - } - return source.lift(new MapOperator(project, thisArg)); + BufferCountOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery)); }; -} -var MapOperator = /*@__PURE__*/ (function () { - function MapOperator(project, thisArg) { - this.project = project; - this.thisArg = thisArg; + return BufferCountOperator; +}()); +var BufferCountSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BufferCountSubscriber, _super); + function BufferCountSubscriber(destination, bufferSize) { + var _this = _super.call(this, destination) || this; + _this.bufferSize = bufferSize; + _this.buffer = []; + return _this; } - MapOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg)); + BufferCountSubscriber.prototype._next = function (value) { + var buffer = this.buffer; + buffer.push(value); + if (buffer.length == this.bufferSize) { + this.destination.next(buffer); + this.buffer = []; + } }; - return MapOperator; -}()); - -var MapSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MapSubscriber, _super); - function MapSubscriber(destination, project, thisArg) { + BufferCountSubscriber.prototype._complete = function () { + var buffer = this.buffer; + if (buffer.length > 0) { + this.destination.next(buffer); + } + _super.prototype._complete.call(this); + }; + return BufferCountSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +var BufferSkipCountSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BufferSkipCountSubscriber, _super); + function BufferSkipCountSubscriber(destination, bufferSize, startBufferEvery) { var _this = _super.call(this, destination) || this; - _this.project = project; + _this.bufferSize = bufferSize; + _this.startBufferEvery = startBufferEvery; + _this.buffers = []; _this.count = 0; - _this.thisArg = thisArg || _this; return _this; } - MapSubscriber.prototype._next = function (value) { - var result; - try { - result = this.project.call(this.thisArg, value, this.count++); + BufferSkipCountSubscriber.prototype._next = function (value) { + var _a = this, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers, count = _a.count; + this.count++; + if (count % startBufferEvery === 0) { + buffers.push([]); } - catch (err) { - this.destination.error(err); - return; + for (var i = buffers.length; i--;) { + var buffer = buffers[i]; + buffer.push(value); + if (buffer.length === bufferSize) { + buffers.splice(i, 1); + this.destination.next(buffer); + } } - this.destination.next(result); }; - return MapSubscriber; + BufferSkipCountSubscriber.prototype._complete = function () { + var _a = this, buffers = _a.buffers, destination = _a.destination; + while (buffers.length > 0) { + var buffer = buffers.shift(); + if (buffer.length > 0) { + destination.next(buffer); + } + } + _super.prototype._complete.call(this); + }; + return BufferSkipCountSubscriber; }(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=map.js.map +//# sourceMappingURL=bufferCount.js.map /***/ }), -/* 227 */ +/* 246 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bindNodeCallback", function() { return bindNodeCallback; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(210); -/* harmony import */ var _operators_map__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(226); -/* harmony import */ var _util_canReportError__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(171); -/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(205); -/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(178); -/** PURE_IMPORTS_START _Observable,_AsyncSubject,_operators_map,_util_canReportError,_util_isScheduler,_util_isArray PURE_IMPORTS_END */ - - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bufferTime", function() { return bufferTime; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(186); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(143); +/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(176); +/** PURE_IMPORTS_START tslib,_scheduler_async,_Subscriber,_util_isScheduler PURE_IMPORTS_END */ -function bindNodeCallback(callbackFunc, resultSelector, scheduler) { - if (resultSelector) { - if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_4__["isScheduler"])(resultSelector)) { - scheduler = resultSelector; - } - else { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return bindNodeCallback(callbackFunc, scheduler).apply(void 0, args).pipe(Object(_operators_map__WEBPACK_IMPORTED_MODULE_2__["map"])(function (args) { return Object(_util_isArray__WEBPACK_IMPORTED_MODULE_5__["isArray"])(args) ? resultSelector.apply(void 0, args) : resultSelector(args); })); - }; - } +function bufferTime(bufferTimeSpan) { + var length = arguments.length; + var scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__["async"]; + if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_3__["isScheduler"])(arguments[arguments.length - 1])) { + scheduler = arguments[arguments.length - 1]; + length--; } - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var params = { - subject: undefined, - args: args, - callbackFunc: callbackFunc, - scheduler: scheduler, - context: this, - }; - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { - var context = params.context; - var subject = params.subject; - if (!scheduler) { - if (!subject) { - subject = params.subject = new _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__["AsyncSubject"](); - var handler = function () { - var innerArgs = []; - for (var _i = 0; _i < arguments.length; _i++) { - innerArgs[_i] = arguments[_i]; - } - var err = innerArgs.shift(); - if (err) { - subject.error(err); - return; - } - subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs); - subject.complete(); - }; - try { - callbackFunc.apply(context, args.concat([handler])); - } - catch (err) { - if (Object(_util_canReportError__WEBPACK_IMPORTED_MODULE_3__["canReportError"])(subject)) { - subject.error(err); - } - else { - console.warn(err); - } - } - } - return subject.subscribe(subscriber); - } - else { - return scheduler.schedule(dispatch, 0, { params: params, subscriber: subscriber, context: context }); - } - }); + var bufferCreationInterval = null; + if (length >= 2) { + bufferCreationInterval = arguments[1]; + } + var maxBufferSize = Number.POSITIVE_INFINITY; + if (length >= 3) { + maxBufferSize = arguments[2]; + } + return function bufferTimeOperatorFunction(source) { + return source.lift(new BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler)); }; } -function dispatch(state) { - var _this = this; - var params = state.params, subscriber = state.subscriber, context = state.context; - var callbackFunc = params.callbackFunc, args = params.args, scheduler = params.scheduler; - var subject = params.subject; - if (!subject) { - subject = params.subject = new _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__["AsyncSubject"](); - var handler = function () { - var innerArgs = []; - for (var _i = 0; _i < arguments.length; _i++) { - innerArgs[_i] = arguments[_i]; - } - var err = innerArgs.shift(); - if (err) { - _this.add(scheduler.schedule(dispatchError, 0, { err: err, subject: subject })); - } - else { - var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs; - _this.add(scheduler.schedule(dispatchNext, 0, { value: value, subject: subject })); +var BufferTimeOperator = /*@__PURE__*/ (function () { + function BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) { + this.bufferTimeSpan = bufferTimeSpan; + this.bufferCreationInterval = bufferCreationInterval; + this.maxBufferSize = maxBufferSize; + this.scheduler = scheduler; + } + BufferTimeOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new BufferTimeSubscriber(subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.maxBufferSize, this.scheduler)); + }; + return BufferTimeOperator; +}()); +var Context = /*@__PURE__*/ (function () { + function Context() { + this.buffer = []; + } + return Context; +}()); +var BufferTimeSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BufferTimeSubscriber, _super); + function BufferTimeSubscriber(destination, bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) { + var _this = _super.call(this, destination) || this; + _this.bufferTimeSpan = bufferTimeSpan; + _this.bufferCreationInterval = bufferCreationInterval; + _this.maxBufferSize = maxBufferSize; + _this.scheduler = scheduler; + _this.contexts = []; + var context = _this.openContext(); + _this.timespanOnly = bufferCreationInterval == null || bufferCreationInterval < 0; + if (_this.timespanOnly) { + var timeSpanOnlyState = { subscriber: _this, context: context, bufferTimeSpan: bufferTimeSpan }; + _this.add(context.closeAction = scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState)); + } + else { + var closeState = { subscriber: _this, context: context }; + var creationState = { bufferTimeSpan: bufferTimeSpan, bufferCreationInterval: bufferCreationInterval, subscriber: _this, scheduler: scheduler }; + _this.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, closeState)); + _this.add(scheduler.schedule(dispatchBufferCreation, bufferCreationInterval, creationState)); + } + return _this; + } + BufferTimeSubscriber.prototype._next = function (value) { + var contexts = this.contexts; + var len = contexts.length; + var filledBufferContext; + for (var i = 0; i < len; i++) { + var context_1 = contexts[i]; + var buffer = context_1.buffer; + buffer.push(value); + if (buffer.length == this.maxBufferSize) { + filledBufferContext = context_1; } - }; - try { - callbackFunc.apply(context, args.concat([handler])); } - catch (err) { - this.add(scheduler.schedule(dispatchError, 0, { err: err, subject: subject })); + if (filledBufferContext) { + this.onBufferFull(filledBufferContext); + } + }; + BufferTimeSubscriber.prototype._error = function (err) { + this.contexts.length = 0; + _super.prototype._error.call(this, err); + }; + BufferTimeSubscriber.prototype._complete = function () { + var _a = this, contexts = _a.contexts, destination = _a.destination; + while (contexts.length > 0) { + var context_2 = contexts.shift(); + destination.next(context_2.buffer); + } + _super.prototype._complete.call(this); + }; + BufferTimeSubscriber.prototype._unsubscribe = function () { + this.contexts = null; + }; + BufferTimeSubscriber.prototype.onBufferFull = function (context) { + this.closeContext(context); + var closeAction = context.closeAction; + closeAction.unsubscribe(); + this.remove(closeAction); + if (!this.closed && this.timespanOnly) { + context = this.openContext(); + var bufferTimeSpan = this.bufferTimeSpan; + var timeSpanOnlyState = { subscriber: this, context: context, bufferTimeSpan: bufferTimeSpan }; + this.add(context.closeAction = this.scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState)); + } + }; + BufferTimeSubscriber.prototype.openContext = function () { + var context = new Context(); + this.contexts.push(context); + return context; + }; + BufferTimeSubscriber.prototype.closeContext = function (context) { + this.destination.next(context.buffer); + var contexts = this.contexts; + var spliceIndex = contexts ? contexts.indexOf(context) : -1; + if (spliceIndex >= 0) { + contexts.splice(contexts.indexOf(context), 1); } + }; + return BufferTimeSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_2__["Subscriber"])); +function dispatchBufferTimeSpanOnly(state) { + var subscriber = state.subscriber; + var prevContext = state.context; + if (prevContext) { + subscriber.closeContext(prevContext); + } + if (!subscriber.closed) { + state.context = subscriber.openContext(); + state.context.closeAction = this.schedule(state, state.bufferTimeSpan); } - this.add(subject.subscribe(subscriber)); } -function dispatchNext(arg) { - var value = arg.value, subject = arg.subject; - subject.next(value); - subject.complete(); +function dispatchBufferCreation(state) { + var bufferCreationInterval = state.bufferCreationInterval, bufferTimeSpan = state.bufferTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler; + var context = subscriber.openContext(); + var action = this; + if (!subscriber.closed) { + subscriber.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, { subscriber: subscriber, context: context })); + action.schedule(state, bufferCreationInterval); + } } -function dispatchError(arg) { - var err = arg.err, subject = arg.subject; - subject.error(err); +function dispatchBufferClose(arg) { + var subscriber = arg.subscriber, context = arg.context; + subscriber.closeContext(context); } -//# sourceMappingURL=bindNodeCallback.js.map +//# sourceMappingURL=bufferTime.js.map /***/ }), -/* 228 */ +/* 247 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "combineLatest", function() { return combineLatest; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CombineLatestOperator", function() { return CombineLatestOperator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CombineLatestSubscriber", function() { return CombineLatestSubscriber; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(205); -/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(178); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(230); -/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(206); -/** PURE_IMPORTS_START tslib,_util_isScheduler,_util_isArray,_OuterSubscriber,_util_subscribeToResult,_fromArray PURE_IMPORTS_END */ - - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bufferToggle", function() { return bufferToggle; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(148); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(201); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(200); +/** PURE_IMPORTS_START tslib,_Subscription,_util_subscribeToResult,_OuterSubscriber PURE_IMPORTS_END */ -var NONE = {}; -function combineLatest() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; - } - var resultSelector = null; - var scheduler = null; - if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_1__["isScheduler"])(observables[observables.length - 1])) { - scheduler = observables.pop(); - } - if (typeof observables[observables.length - 1] === 'function') { - resultSelector = observables.pop(); - } - if (observables.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_2__["isArray"])(observables[0])) { - observables = observables[0]; - } - return Object(_fromArray__WEBPACK_IMPORTED_MODULE_5__["fromArray"])(observables, scheduler).lift(new CombineLatestOperator(resultSelector)); +function bufferToggle(openings, closingSelector) { + return function bufferToggleOperatorFunction(source) { + return source.lift(new BufferToggleOperator(openings, closingSelector)); + }; } -var CombineLatestOperator = /*@__PURE__*/ (function () { - function CombineLatestOperator(resultSelector) { - this.resultSelector = resultSelector; +var BufferToggleOperator = /*@__PURE__*/ (function () { + function BufferToggleOperator(openings, closingSelector) { + this.openings = openings; + this.closingSelector = closingSelector; } - CombineLatestOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new CombineLatestSubscriber(subscriber, this.resultSelector)); + BufferToggleOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new BufferToggleSubscriber(subscriber, this.openings, this.closingSelector)); }; - return CombineLatestOperator; + return BufferToggleOperator; }()); - -var CombineLatestSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CombineLatestSubscriber, _super); - function CombineLatestSubscriber(destination, resultSelector) { +var BufferToggleSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BufferToggleSubscriber, _super); + function BufferToggleSubscriber(destination, openings, closingSelector) { var _this = _super.call(this, destination) || this; - _this.resultSelector = resultSelector; - _this.active = 0; - _this.values = []; - _this.observables = []; + _this.openings = openings; + _this.closingSelector = closingSelector; + _this.contexts = []; + _this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(_this, openings)); return _this; } - CombineLatestSubscriber.prototype._next = function (observable) { - this.values.push(NONE); - this.observables.push(observable); - }; - CombineLatestSubscriber.prototype._complete = function () { - var observables = this.observables; - var len = observables.length; - if (len === 0) { - this.destination.complete(); - } - else { - this.active = len; - this.toRespond = len; - for (var i = 0; i < len; i++) { - var observable = observables[i]; - this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__["subscribeToResult"])(this, observable, observable, i)); - } + BufferToggleSubscriber.prototype._next = function (value) { + var contexts = this.contexts; + var len = contexts.length; + for (var i = 0; i < len; i++) { + contexts[i].buffer.push(value); } }; - CombineLatestSubscriber.prototype.notifyComplete = function (unused) { - if ((this.active -= 1) === 0) { - this.destination.complete(); + BufferToggleSubscriber.prototype._error = function (err) { + var contexts = this.contexts; + while (contexts.length > 0) { + var context_1 = contexts.shift(); + context_1.subscription.unsubscribe(); + context_1.buffer = null; + context_1.subscription = null; } + this.contexts = null; + _super.prototype._error.call(this, err); }; - CombineLatestSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - var values = this.values; - var oldVal = values[outerIndex]; - var toRespond = !this.toRespond - ? 0 - : oldVal === NONE ? --this.toRespond : this.toRespond; - values[outerIndex] = innerValue; - if (toRespond === 0) { - if (this.resultSelector) { - this._tryResultSelector(values); - } - else { - this.destination.next(values.slice()); - } + BufferToggleSubscriber.prototype._complete = function () { + var contexts = this.contexts; + while (contexts.length > 0) { + var context_2 = contexts.shift(); + this.destination.next(context_2.buffer); + context_2.subscription.unsubscribe(); + context_2.buffer = null; + context_2.subscription = null; } + this.contexts = null; + _super.prototype._complete.call(this); }; - CombineLatestSubscriber.prototype._tryResultSelector = function (values) { - var result; + BufferToggleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + outerValue ? this.closeBuffer(outerValue) : this.openBuffer(innerValue); + }; + BufferToggleSubscriber.prototype.notifyComplete = function (innerSub) { + this.closeBuffer(innerSub.context); + }; + BufferToggleSubscriber.prototype.openBuffer = function (value) { try { - result = this.resultSelector.apply(this, values); + var closingSelector = this.closingSelector; + var closingNotifier = closingSelector.call(this, value); + if (closingNotifier) { + this.trySubscribe(closingNotifier); + } } catch (err) { - this.destination.error(err); - return; + this._error(err); } - this.destination.next(result); }; - return CombineLatestSubscriber; + BufferToggleSubscriber.prototype.closeBuffer = function (context) { + var contexts = this.contexts; + if (contexts && context) { + var buffer = context.buffer, subscription = context.subscription; + this.destination.next(buffer); + contexts.splice(contexts.indexOf(context), 1); + this.remove(subscription); + subscription.unsubscribe(); + } + }; + BufferToggleSubscriber.prototype.trySubscribe = function (closingNotifier) { + var contexts = this.contexts; + var buffer = []; + var subscription = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"](); + var context = { buffer: buffer, subscription: subscription }; + contexts.push(context); + var innerSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, closingNotifier, context); + if (!innerSubscription || innerSubscription.closed) { + this.closeBuffer(context); + } + else { + innerSubscription.context = context; + this.add(innerSubscription); + subscription.add(innerSubscription); + } + }; + return BufferToggleSubscriber; }(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__["OuterSubscriber"])); - -//# sourceMappingURL=combineLatest.js.map +//# sourceMappingURL=bufferToggle.js.map /***/ }), -/* 229 */ +/* 248 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OuterSubscriber", function() { return OuterSubscriber; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bufferWhen", function() { return bufferWhen; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(148); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_Subscription,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -var OuterSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](OuterSubscriber, _super); - function OuterSubscriber() { - return _super !== null && _super.apply(this, arguments) || this; + + +function bufferWhen(closingSelector) { + return function (source) { + return source.lift(new BufferWhenOperator(closingSelector)); + }; +} +var BufferWhenOperator = /*@__PURE__*/ (function () { + function BufferWhenOperator(closingSelector) { + this.closingSelector = closingSelector; } - OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.destination.next(innerValue); + BufferWhenOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector)); }; - OuterSubscriber.prototype.notifyError = function (error, innerSub) { - this.destination.error(error); + return BufferWhenOperator; +}()); +var BufferWhenSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BufferWhenSubscriber, _super); + function BufferWhenSubscriber(destination, closingSelector) { + var _this = _super.call(this, destination) || this; + _this.closingSelector = closingSelector; + _this.subscribing = false; + _this.openBuffer(); + return _this; + } + BufferWhenSubscriber.prototype._next = function (value) { + this.buffer.push(value); }; - OuterSubscriber.prototype.notifyComplete = function (innerSub) { - this.destination.complete(); + BufferWhenSubscriber.prototype._complete = function () { + var buffer = this.buffer; + if (buffer) { + this.destination.next(buffer); + } + _super.prototype._complete.call(this); }; - return OuterSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); - -//# sourceMappingURL=OuterSubscriber.js.map + BufferWhenSubscriber.prototype._unsubscribe = function () { + this.buffer = null; + this.subscribing = false; + }; + BufferWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.openBuffer(); + }; + BufferWhenSubscriber.prototype.notifyComplete = function () { + if (this.subscribing) { + this.complete(); + } + else { + this.openBuffer(); + } + }; + BufferWhenSubscriber.prototype.openBuffer = function () { + var closingSubscription = this.closingSubscription; + if (closingSubscription) { + this.remove(closingSubscription); + closingSubscription.unsubscribe(); + } + var buffer = this.buffer; + if (this.buffer) { + this.destination.next(buffer); + } + this.buffer = []; + var closingNotifier; + try { + var closingSelector = this.closingSelector; + closingNotifier = closingSelector(); + } + catch (err) { + return this.error(err); + } + closingSubscription = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"](); + this.closingSubscription = closingSubscription; + this.add(closingSubscription); + this.subscribing = true; + closingSubscription.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(this, closingNotifier)); + this.subscribing = false; + }; + return BufferWhenSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"])); +//# sourceMappingURL=bufferWhen.js.map /***/ }), -/* 230 */ +/* 249 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeToResult", function() { return subscribeToResult; }); -/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(231); -/* harmony import */ var _subscribeTo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(232); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(170); -/** PURE_IMPORTS_START _InnerSubscriber,_subscribeTo,_Observable PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "catchError", function() { return catchError; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(200); +/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(202); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_OuterSubscriber,_InnerSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, destination) { - if (destination === void 0) { - destination = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_0__["InnerSubscriber"](outerSubscriber, outerValue, outerIndex); - } - if (destination.closed) { - return undefined; + +function catchError(selector) { + return function catchErrorOperatorFunction(source) { + var operator = new CatchOperator(selector); + var caught = source.lift(operator); + return (operator.caught = caught); + }; +} +var CatchOperator = /*@__PURE__*/ (function () { + function CatchOperator(selector) { + this.selector = selector; } - if (result instanceof _Observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]) { - return result.subscribe(destination); + CatchOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught)); + }; + return CatchOperator; +}()); +var CatchSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CatchSubscriber, _super); + function CatchSubscriber(destination, selector, caught) { + var _this = _super.call(this, destination) || this; + _this.selector = selector; + _this.caught = caught; + return _this; } - return Object(_subscribeTo__WEBPACK_IMPORTED_MODULE_1__["subscribeTo"])(result)(destination); -} -//# sourceMappingURL=subscribeToResult.js.map + CatchSubscriber.prototype.error = function (err) { + if (!this.isStopped) { + var result = void 0; + try { + result = this.selector(err, this.caught); + } + catch (err2) { + _super.prototype.error.call(this, err2); + return; + } + this._unsubscribeAndRecycle(); + var innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__["InnerSubscriber"](this, undefined, undefined); + this.add(innerSubscriber); + Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(this, result, undefined, undefined, innerSubscriber); + } + }; + return CatchSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); +//# sourceMappingURL=catchError.js.map /***/ }), -/* 231 */ +/* 250 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InnerSubscriber", function() { return InnerSubscriber; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "combineAll", function() { return combineAll; }); +/* harmony import */ var _observable_combineLatest__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(199); +/** PURE_IMPORTS_START _observable_combineLatest PURE_IMPORTS_END */ - -var InnerSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](InnerSubscriber, _super); - function InnerSubscriber(parent, outerValue, outerIndex) { - var _this = _super.call(this) || this; - _this.parent = parent; - _this.outerValue = outerValue; - _this.outerIndex = outerIndex; - _this.index = 0; - return _this; - } - InnerSubscriber.prototype._next = function (value) { - this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this); - }; - InnerSubscriber.prototype._error = function (error) { - this.parent.notifyError(error, this); - this.unsubscribe(); - }; - InnerSubscriber.prototype._complete = function () { - this.parent.notifyComplete(this); - this.unsubscribe(); - }; - return InnerSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); - -//# sourceMappingURL=InnerSubscriber.js.map +function combineAll(project) { + return function (source) { return source.lift(new _observable_combineLatest__WEBPACK_IMPORTED_MODULE_0__["CombineLatestOperator"](project)); }; +} +//# sourceMappingURL=combineAll.js.map /***/ }), -/* 232 */ +/* 251 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeTo", function() { return subscribeTo; }); -/* harmony import */ var _subscribeToArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(207); -/* harmony import */ var _subscribeToPromise__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(233); -/* harmony import */ var _subscribeToIterable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(234); -/* harmony import */ var _subscribeToObservable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(236); -/* harmony import */ var _isArrayLike__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(237); -/* harmony import */ var _isPromise__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(238); -/* harmony import */ var _isObject__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(179); -/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(235); -/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(183); -/** PURE_IMPORTS_START _subscribeToArray,_subscribeToPromise,_subscribeToIterable,_subscribeToObservable,_isArrayLike,_isPromise,_isObject,_symbol_iterator,_symbol_observable PURE_IMPORTS_END */ - - - - - - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "combineLatest", function() { return combineLatest; }); +/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); +/* harmony import */ var _observable_combineLatest__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(199); +/* harmony import */ var _observable_from__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(214); +/** PURE_IMPORTS_START _util_isArray,_observable_combineLatest,_observable_from PURE_IMPORTS_END */ -var subscribeTo = function (result) { - if (!!result && typeof result[_symbol_observable__WEBPACK_IMPORTED_MODULE_8__["observable"]] === 'function') { - return Object(_subscribeToObservable__WEBPACK_IMPORTED_MODULE_3__["subscribeToObservable"])(result); - } - else if (Object(_isArrayLike__WEBPACK_IMPORTED_MODULE_4__["isArrayLike"])(result)) { - return Object(_subscribeToArray__WEBPACK_IMPORTED_MODULE_0__["subscribeToArray"])(result); - } - else if (Object(_isPromise__WEBPACK_IMPORTED_MODULE_5__["isPromise"])(result)) { - return Object(_subscribeToPromise__WEBPACK_IMPORTED_MODULE_1__["subscribeToPromise"])(result); +var none = {}; +function combineLatest() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; } - else if (!!result && typeof result[_symbol_iterator__WEBPACK_IMPORTED_MODULE_7__["iterator"]] === 'function') { - return Object(_subscribeToIterable__WEBPACK_IMPORTED_MODULE_2__["subscribeToIterable"])(result); + var project = null; + if (typeof observables[observables.length - 1] === 'function') { + project = observables.pop(); } - else { - var value = Object(_isObject__WEBPACK_IMPORTED_MODULE_6__["isObject"])(result) ? 'an invalid object' : "'" + result + "'"; - var msg = "You provided " + value + " where a stream was expected." - + ' You can provide an Observable, Promise, Array, or Iterable.'; - throw new TypeError(msg); + if (observables.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_0__["isArray"])(observables[0])) { + observables = observables[0].slice(); } -}; -//# sourceMappingURL=subscribeTo.js.map + return function (source) { return source.lift.call(Object(_observable_from__WEBPACK_IMPORTED_MODULE_2__["from"])([source].concat(observables)), new _observable_combineLatest__WEBPACK_IMPORTED_MODULE_1__["CombineLatestOperator"](project)); }; +} +//# sourceMappingURL=combineLatest.js.map /***/ }), -/* 233 */ +/* 252 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeToPromise", function() { return subscribeToPromise; }); -/* harmony import */ var _hostReportError__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(176); -/** PURE_IMPORTS_START _hostReportError PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat", function() { return concat; }); +/* harmony import */ var _observable_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(210); +/** PURE_IMPORTS_START _observable_concat PURE_IMPORTS_END */ -var subscribeToPromise = function (promise) { - return function (subscriber) { - promise.then(function (value) { - if (!subscriber.closed) { - subscriber.next(value); - subscriber.complete(); - } - }, function (err) { return subscriber.error(err); }) - .then(null, _hostReportError__WEBPACK_IMPORTED_MODULE_0__["hostReportError"]); - return subscriber; - }; -}; -//# sourceMappingURL=subscribeToPromise.js.map +function concat() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; + } + return function (source) { return source.lift.call(_observable_concat__WEBPACK_IMPORTED_MODULE_0__["concat"].apply(void 0, [source].concat(observables))); }; +} +//# sourceMappingURL=concat.js.map /***/ }), -/* 234 */ +/* 253 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeToIterable", function() { return subscribeToIterable; }); -/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(235); -/** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concatMap", function() { return concatMap; }); +/* harmony import */ var _mergeMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(213); +/** PURE_IMPORTS_START _mergeMap PURE_IMPORTS_END */ -var subscribeToIterable = function (iterable) { - return function (subscriber) { - var iterator = iterable[_symbol_iterator__WEBPACK_IMPORTED_MODULE_0__["iterator"]](); - do { - var item = iterator.next(); - if (item.done) { - subscriber.complete(); - break; - } - subscriber.next(item.value); - if (subscriber.closed) { - break; - } - } while (true); - if (typeof iterator.return === 'function') { - subscriber.add(function () { - if (iterator.return) { - iterator.return(); - } - }); - } - return subscriber; - }; -}; -//# sourceMappingURL=subscribeToIterable.js.map +function concatMap(project, resultSelector) { + return Object(_mergeMap__WEBPACK_IMPORTED_MODULE_0__["mergeMap"])(project, resultSelector, 1); +} +//# sourceMappingURL=concatMap.js.map /***/ }), -/* 235 */ +/* 254 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getSymbolIterator", function() { return getSymbolIterator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "iterator", function() { return iterator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "$$iterator", function() { return $$iterator; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function getSymbolIterator() { - if (typeof Symbol !== 'function' || !Symbol.iterator) { - return '@@iterator'; - } - return Symbol.iterator; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concatMapTo", function() { return concatMapTo; }); +/* harmony import */ var _concatMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(253); +/** PURE_IMPORTS_START _concatMap PURE_IMPORTS_END */ + +function concatMapTo(innerObservable, resultSelector) { + return Object(_concatMap__WEBPACK_IMPORTED_MODULE_0__["concatMap"])(function () { return innerObservable; }, resultSelector); } -var iterator = /*@__PURE__*/ getSymbolIterator(); -var $$iterator = iterator; -//# sourceMappingURL=iterator.js.map +//# sourceMappingURL=concatMapTo.js.map /***/ }), -/* 236 */ +/* 255 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeToObservable", function() { return subscribeToObservable; }); -/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(183); -/** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "count", function() { return count; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -var subscribeToObservable = function (obj) { - return function (subscriber) { - var obs = obj[_symbol_observable__WEBPACK_IMPORTED_MODULE_0__["observable"]](); - if (typeof obs.subscribe !== 'function') { - throw new TypeError('Provided object does not correctly implement Symbol.observable'); + +function count(predicate) { + return function (source) { return source.lift(new CountOperator(predicate, source)); }; +} +var CountOperator = /*@__PURE__*/ (function () { + function CountOperator(predicate, source) { + this.predicate = predicate; + this.source = source; + } + CountOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new CountSubscriber(subscriber, this.predicate, this.source)); + }; + return CountOperator; +}()); +var CountSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CountSubscriber, _super); + function CountSubscriber(destination, predicate, source) { + var _this = _super.call(this, destination) || this; + _this.predicate = predicate; + _this.source = source; + _this.count = 0; + _this.index = 0; + return _this; + } + CountSubscriber.prototype._next = function (value) { + if (this.predicate) { + this._tryPredicate(value); } else { - return obs.subscribe(subscriber); + this.count++; } }; -}; -//# sourceMappingURL=subscribeToObservable.js.map + CountSubscriber.prototype._tryPredicate = function (value) { + var result; + try { + result = this.predicate(value, this.index++, this.source); + } + catch (err) { + this.destination.error(err); + return; + } + if (result) { + this.count++; + } + }; + CountSubscriber.prototype._complete = function () { + this.destination.next(this.count); + this.destination.complete(); + }; + return CountSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=count.js.map /***/ }), -/* 237 */ +/* 256 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isArrayLike", function() { return isArrayLike; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; }); -//# sourceMappingURL=isArrayLike.js.map +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "debounce", function() { return debounce; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -/***/ }), -/* 238 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPromise", function() { return isPromise; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function isPromise(value) { - return !!value && typeof value.subscribe !== 'function' && typeof value.then === 'function'; +function debounce(durationSelector) { + return function (source) { return source.lift(new DebounceOperator(durationSelector)); }; } -//# sourceMappingURL=isPromise.js.map +var DebounceOperator = /*@__PURE__*/ (function () { + function DebounceOperator(durationSelector) { + this.durationSelector = durationSelector; + } + DebounceOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DebounceSubscriber(subscriber, this.durationSelector)); + }; + return DebounceOperator; +}()); +var DebounceSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DebounceSubscriber, _super); + function DebounceSubscriber(destination, durationSelector) { + var _this = _super.call(this, destination) || this; + _this.durationSelector = durationSelector; + _this.hasValue = false; + _this.durationSubscription = null; + return _this; + } + DebounceSubscriber.prototype._next = function (value) { + try { + var result = this.durationSelector.call(this, value); + if (result) { + this._tryNext(value, result); + } + } + catch (err) { + this.destination.error(err); + } + }; + DebounceSubscriber.prototype._complete = function () { + this.emitValue(); + this.destination.complete(); + }; + DebounceSubscriber.prototype._tryNext = function (value, duration) { + var subscription = this.durationSubscription; + this.value = value; + this.hasValue = true; + if (subscription) { + subscription.unsubscribe(); + this.remove(subscription); + } + subscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, duration); + if (subscription && !subscription.closed) { + this.add(this.durationSubscription = subscription); + } + }; + DebounceSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.emitValue(); + }; + DebounceSubscriber.prototype.notifyComplete = function () { + this.emitValue(); + }; + DebounceSubscriber.prototype.emitValue = function () { + if (this.hasValue) { + var value = this.value; + var subscription = this.durationSubscription; + if (subscription) { + this.durationSubscription = null; + subscription.unsubscribe(); + this.remove(subscription); + } + this.value = null; + this.hasValue = false; + _super.prototype._next.call(this, value); + } + }; + return DebounceSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); +//# sourceMappingURL=debounce.js.map /***/ }), -/* 239 */ +/* 257 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat", function() { return concat; }); -/* harmony import */ var _of__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(204); -/* harmony import */ var _operators_concatAll__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(240); -/** PURE_IMPORTS_START _of,_operators_concatAll PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "debounceTime", function() { return debounceTime; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(186); +/** PURE_IMPORTS_START tslib,_Subscriber,_scheduler_async PURE_IMPORTS_END */ -function concat() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; + +function debounceTime(dueTime, scheduler) { + if (scheduler === void 0) { + scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_2__["async"]; } - return Object(_operators_concatAll__WEBPACK_IMPORTED_MODULE_1__["concatAll"])()(_of__WEBPACK_IMPORTED_MODULE_0__["of"].apply(void 0, observables)); + return function (source) { return source.lift(new DebounceTimeOperator(dueTime, scheduler)); }; } -//# sourceMappingURL=concat.js.map - - -/***/ }), -/* 240 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concatAll", function() { return concatAll; }); -/* harmony import */ var _mergeAll__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(241); -/** PURE_IMPORTS_START _mergeAll PURE_IMPORTS_END */ - -function concatAll() { - return Object(_mergeAll__WEBPACK_IMPORTED_MODULE_0__["mergeAll"])(1); +var DebounceTimeOperator = /*@__PURE__*/ (function () { + function DebounceTimeOperator(dueTime, scheduler) { + this.dueTime = dueTime; + this.scheduler = scheduler; + } + DebounceTimeOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler)); + }; + return DebounceTimeOperator; +}()); +var DebounceTimeSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DebounceTimeSubscriber, _super); + function DebounceTimeSubscriber(destination, dueTime, scheduler) { + var _this = _super.call(this, destination) || this; + _this.dueTime = dueTime; + _this.scheduler = scheduler; + _this.debouncedSubscription = null; + _this.lastValue = null; + _this.hasValue = false; + return _this; + } + DebounceTimeSubscriber.prototype._next = function (value) { + this.clearDebounce(); + this.lastValue = value; + this.hasValue = true; + this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this)); + }; + DebounceTimeSubscriber.prototype._complete = function () { + this.debouncedNext(); + this.destination.complete(); + }; + DebounceTimeSubscriber.prototype.debouncedNext = function () { + this.clearDebounce(); + if (this.hasValue) { + var lastValue = this.lastValue; + this.lastValue = null; + this.hasValue = false; + this.destination.next(lastValue); + } + }; + DebounceTimeSubscriber.prototype.clearDebounce = function () { + var debouncedSubscription = this.debouncedSubscription; + if (debouncedSubscription !== null) { + this.remove(debouncedSubscription); + debouncedSubscription.unsubscribe(); + this.debouncedSubscription = null; + } + }; + return DebounceTimeSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +function dispatchNext(subscriber) { + subscriber.debouncedNext(); } -//# sourceMappingURL=concatAll.js.map +//# sourceMappingURL=debounceTime.js.map /***/ }), -/* 241 */ +/* 258 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeAll", function() { return mergeAll; }); -/* harmony import */ var _mergeMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(242); -/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(220); -/** PURE_IMPORTS_START _mergeMap,_util_identity PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultIfEmpty", function() { return defaultIfEmpty; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function mergeAll(concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; +function defaultIfEmpty(defaultValue) { + if (defaultValue === void 0) { + defaultValue = null; } - return Object(_mergeMap__WEBPACK_IMPORTED_MODULE_0__["mergeMap"])(_util_identity__WEBPACK_IMPORTED_MODULE_1__["identity"], concurrent); + return function (source) { return source.lift(new DefaultIfEmptyOperator(defaultValue)); }; } -//# sourceMappingURL=mergeAll.js.map +var DefaultIfEmptyOperator = /*@__PURE__*/ (function () { + function DefaultIfEmptyOperator(defaultValue) { + this.defaultValue = defaultValue; + } + DefaultIfEmptyOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue)); + }; + return DefaultIfEmptyOperator; +}()); +var DefaultIfEmptySubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DefaultIfEmptySubscriber, _super); + function DefaultIfEmptySubscriber(destination, defaultValue) { + var _this = _super.call(this, destination) || this; + _this.defaultValue = defaultValue; + _this.isEmpty = true; + return _this; + } + DefaultIfEmptySubscriber.prototype._next = function (value) { + this.isEmpty = false; + this.destination.next(value); + }; + DefaultIfEmptySubscriber.prototype._complete = function () { + if (this.isEmpty) { + this.destination.next(this.defaultValue); + } + this.destination.complete(); + }; + return DefaultIfEmptySubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=defaultIfEmpty.js.map /***/ }), -/* 242 */ +/* 259 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeMap", function() { return mergeMap; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MergeMapOperator", function() { return MergeMapOperator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MergeMapSubscriber", function() { return MergeMapSubscriber; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(230); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(229); -/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(231); -/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(226); -/* harmony import */ var _observable_from__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(243); -/** PURE_IMPORTS_START tslib,_util_subscribeToResult,_OuterSubscriber,_InnerSubscriber,_map,_observable_from PURE_IMPORTS_END */ - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "delay", function() { return delay; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(186); +/* harmony import */ var _util_isDate__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(260); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(143); +/* harmony import */ var _Notification__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(173); +/** PURE_IMPORTS_START tslib,_scheduler_async,_util_isDate,_Subscriber,_Notification PURE_IMPORTS_END */ -function mergeMap(project, resultSelector, concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - if (typeof resultSelector === 'function') { - return function (source) { return source.pipe(mergeMap(function (a, i) { return Object(_observable_from__WEBPACK_IMPORTED_MODULE_5__["from"])(project(a, i)).pipe(Object(_map__WEBPACK_IMPORTED_MODULE_4__["map"])(function (b, ii) { return resultSelector(a, b, i, ii); })); }, concurrent)); }; - } - else if (typeof resultSelector === 'number') { - concurrent = resultSelector; +function delay(delay, scheduler) { + if (scheduler === void 0) { + scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__["async"]; } - return function (source) { return source.lift(new MergeMapOperator(project, concurrent)); }; + var absoluteDelay = Object(_util_isDate__WEBPACK_IMPORTED_MODULE_2__["isDate"])(delay); + var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay); + return function (source) { return source.lift(new DelayOperator(delayFor, scheduler)); }; } -var MergeMapOperator = /*@__PURE__*/ (function () { - function MergeMapOperator(project, concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - this.project = project; - this.concurrent = concurrent; +var DelayOperator = /*@__PURE__*/ (function () { + function DelayOperator(delay, scheduler) { + this.delay = delay; + this.scheduler = scheduler; } - MergeMapOperator.prototype.call = function (observer, source) { - return source.subscribe(new MergeMapSubscriber(observer, this.project, this.concurrent)); + DelayOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler)); }; - return MergeMapOperator; + return DelayOperator; }()); - -var MergeMapSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MergeMapSubscriber, _super); - function MergeMapSubscriber(destination, project, concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } +var DelaySubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DelaySubscriber, _super); + function DelaySubscriber(destination, delay, scheduler) { var _this = _super.call(this, destination) || this; - _this.project = project; - _this.concurrent = concurrent; - _this.hasCompleted = false; - _this.buffer = []; - _this.active = 0; - _this.index = 0; + _this.delay = delay; + _this.scheduler = scheduler; + _this.queue = []; + _this.active = false; + _this.errored = false; return _this; } - MergeMapSubscriber.prototype._next = function (value) { - if (this.active < this.concurrent) { - this._tryNext(value); + DelaySubscriber.dispatch = function (state) { + var source = state.source; + var queue = source.queue; + var scheduler = state.scheduler; + var destination = state.destination; + while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) { + queue.shift().notification.observe(destination); + } + if (queue.length > 0) { + var delay_1 = Math.max(0, queue[0].time - scheduler.now()); + this.schedule(state, delay_1); } else { - this.buffer.push(value); + this.unsubscribe(); + source.active = false; } }; - MergeMapSubscriber.prototype._tryNext = function (value) { - var result; - var index = this.index++; - try { - result = this.project(value, index); - } - catch (err) { - this.destination.error(err); + DelaySubscriber.prototype._schedule = function (scheduler) { + this.active = true; + var destination = this.destination; + destination.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, { + source: this, destination: this.destination, scheduler: scheduler + })); + }; + DelaySubscriber.prototype.scheduleNotification = function (notification) { + if (this.errored === true) { return; } - this.active++; - this._innerSub(result, value, index); + var scheduler = this.scheduler; + var message = new DelayMessage(scheduler.now() + this.delay, notification); + this.queue.push(message); + if (this.active === false) { + this._schedule(scheduler); + } }; - MergeMapSubscriber.prototype._innerSub = function (ish, value, index) { - var innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_3__["InnerSubscriber"](this, undefined, undefined); - var destination = this.destination; - destination.add(innerSubscriber); - Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__["subscribeToResult"])(this, ish, value, index, innerSubscriber); + DelaySubscriber.prototype._next = function (value) { + this.scheduleNotification(_Notification__WEBPACK_IMPORTED_MODULE_4__["Notification"].createNext(value)); }; - MergeMapSubscriber.prototype._complete = function () { - this.hasCompleted = true; - if (this.active === 0 && this.buffer.length === 0) { - this.destination.complete(); - } + DelaySubscriber.prototype._error = function (err) { + this.errored = true; + this.queue = []; + this.destination.error(err); this.unsubscribe(); }; - MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.destination.next(innerValue); - }; - MergeMapSubscriber.prototype.notifyComplete = function (innerSub) { - var buffer = this.buffer; - this.remove(innerSub); - this.active--; - if (buffer.length > 0) { - this._next(buffer.shift()); - } - else if (this.active === 0 && this.hasCompleted) { - this.destination.complete(); - } + DelaySubscriber.prototype._complete = function () { + this.scheduleNotification(_Notification__WEBPACK_IMPORTED_MODULE_4__["Notification"].createComplete()); + this.unsubscribe(); }; - return MergeMapSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"])); - -//# sourceMappingURL=mergeMap.js.map + return DelaySubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_3__["Subscriber"])); +var DelayMessage = /*@__PURE__*/ (function () { + function DelayMessage(time, notification) { + this.time = time; + this.notification = notification; + } + return DelayMessage; +}()); +//# sourceMappingURL=delay.js.map /***/ }), -/* 243 */ +/* 260 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "from", function() { return from; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _util_subscribeTo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(232); -/* harmony import */ var _scheduled_scheduled__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(244); -/** PURE_IMPORTS_START _Observable,_util_subscribeTo,_scheduled_scheduled PURE_IMPORTS_END */ - - - -function from(input, scheduler) { - if (!scheduler) { - if (input instanceof _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]) { - return input; - } - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](Object(_util_subscribeTo__WEBPACK_IMPORTED_MODULE_1__["subscribeTo"])(input)); - } - else { - return Object(_scheduled_scheduled__WEBPACK_IMPORTED_MODULE_2__["scheduled"])(input, scheduler); - } +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDate", function() { return isDate; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function isDate(value) { + return value instanceof Date && !isNaN(+value); } -//# sourceMappingURL=from.js.map +//# sourceMappingURL=isDate.js.map /***/ }), -/* 244 */ +/* 261 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scheduled", function() { return scheduled; }); -/* harmony import */ var _scheduleObservable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(245); -/* harmony import */ var _schedulePromise__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(246); -/* harmony import */ var _scheduleArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(208); -/* harmony import */ var _scheduleIterable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(247); -/* harmony import */ var _util_isInteropObservable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(248); -/* harmony import */ var _util_isPromise__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(238); -/* harmony import */ var _util_isArrayLike__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(237); -/* harmony import */ var _util_isIterable__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(249); -/** PURE_IMPORTS_START _scheduleObservable,_schedulePromise,_scheduleArray,_scheduleIterable,_util_isInteropObservable,_util_isPromise,_util_isArrayLike,_util_isIterable PURE_IMPORTS_END */ - - - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "delayWhen", function() { return delayWhen; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(141); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_Subscriber,_Observable,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function scheduled(input, scheduler) { - if (input != null) { - if (Object(_util_isInteropObservable__WEBPACK_IMPORTED_MODULE_4__["isInteropObservable"])(input)) { - return Object(_scheduleObservable__WEBPACK_IMPORTED_MODULE_0__["scheduleObservable"])(input, scheduler); +function delayWhen(delayDurationSelector, subscriptionDelay) { + if (subscriptionDelay) { + return function (source) { + return new SubscriptionDelayObservable(source, subscriptionDelay) + .lift(new DelayWhenOperator(delayDurationSelector)); + }; + } + return function (source) { return source.lift(new DelayWhenOperator(delayDurationSelector)); }; +} +var DelayWhenOperator = /*@__PURE__*/ (function () { + function DelayWhenOperator(delayDurationSelector) { + this.delayDurationSelector = delayDurationSelector; + } + DelayWhenOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DelayWhenSubscriber(subscriber, this.delayDurationSelector)); + }; + return DelayWhenOperator; +}()); +var DelayWhenSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DelayWhenSubscriber, _super); + function DelayWhenSubscriber(destination, delayDurationSelector) { + var _this = _super.call(this, destination) || this; + _this.delayDurationSelector = delayDurationSelector; + _this.completed = false; + _this.delayNotifierSubscriptions = []; + _this.index = 0; + return _this; + } + DelayWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.destination.next(outerValue); + this.removeSubscription(innerSub); + this.tryComplete(); + }; + DelayWhenSubscriber.prototype.notifyError = function (error, innerSub) { + this._error(error); + }; + DelayWhenSubscriber.prototype.notifyComplete = function (innerSub) { + var value = this.removeSubscription(innerSub); + if (value) { + this.destination.next(value); } - else if (Object(_util_isPromise__WEBPACK_IMPORTED_MODULE_5__["isPromise"])(input)) { - return Object(_schedulePromise__WEBPACK_IMPORTED_MODULE_1__["schedulePromise"])(input, scheduler); + this.tryComplete(); + }; + DelayWhenSubscriber.prototype._next = function (value) { + var index = this.index++; + try { + var delayNotifier = this.delayDurationSelector(value, index); + if (delayNotifier) { + this.tryDelay(delayNotifier, value); + } } - else if (Object(_util_isArrayLike__WEBPACK_IMPORTED_MODULE_6__["isArrayLike"])(input)) { - return Object(_scheduleArray__WEBPACK_IMPORTED_MODULE_2__["scheduleArray"])(input, scheduler); + catch (err) { + this.destination.error(err); } - else if (Object(_util_isIterable__WEBPACK_IMPORTED_MODULE_7__["isIterable"])(input) || typeof input === 'string') { - return Object(_scheduleIterable__WEBPACK_IMPORTED_MODULE_3__["scheduleIterable"])(input, scheduler); + }; + DelayWhenSubscriber.prototype._complete = function () { + this.completed = true; + this.tryComplete(); + this.unsubscribe(); + }; + DelayWhenSubscriber.prototype.removeSubscription = function (subscription) { + subscription.unsubscribe(); + var subscriptionIdx = this.delayNotifierSubscriptions.indexOf(subscription); + if (subscriptionIdx !== -1) { + this.delayNotifierSubscriptions.splice(subscriptionIdx, 1); + } + return subscription.outerValue; + }; + DelayWhenSubscriber.prototype.tryDelay = function (delayNotifier, value) { + var notifierSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__["subscribeToResult"])(this, delayNotifier, value); + if (notifierSubscription && !notifierSubscription.closed) { + var destination = this.destination; + destination.add(notifierSubscription); + this.delayNotifierSubscriptions.push(notifierSubscription); + } + }; + DelayWhenSubscriber.prototype.tryComplete = function () { + if (this.completed && this.delayNotifierSubscriptions.length === 0) { + this.destination.complete(); } + }; + return DelayWhenSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__["OuterSubscriber"])); +var SubscriptionDelayObservable = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SubscriptionDelayObservable, _super); + function SubscriptionDelayObservable(source, subscriptionDelay) { + var _this = _super.call(this) || this; + _this.source = source; + _this.subscriptionDelay = subscriptionDelay; + return _this; } - throw new TypeError((input !== null && typeof input || input) + ' is not observable'); -} -//# sourceMappingURL=scheduled.js.map + SubscriptionDelayObservable.prototype._subscribe = function (subscriber) { + this.subscriptionDelay.subscribe(new SubscriptionDelaySubscriber(subscriber, this.source)); + }; + return SubscriptionDelayObservable; +}(_Observable__WEBPACK_IMPORTED_MODULE_2__["Observable"])); +var SubscriptionDelaySubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SubscriptionDelaySubscriber, _super); + function SubscriptionDelaySubscriber(parent, source) { + var _this = _super.call(this) || this; + _this.parent = parent; + _this.source = source; + _this.sourceSubscribed = false; + return _this; + } + SubscriptionDelaySubscriber.prototype._next = function (unused) { + this.subscribeToSource(); + }; + SubscriptionDelaySubscriber.prototype._error = function (err) { + this.unsubscribe(); + this.parent.error(err); + }; + SubscriptionDelaySubscriber.prototype._complete = function () { + this.unsubscribe(); + this.subscribeToSource(); + }; + SubscriptionDelaySubscriber.prototype.subscribeToSource = function () { + if (!this.sourceSubscribed) { + this.sourceSubscribed = true; + this.unsubscribe(); + this.source.subscribe(this.parent); + } + }; + return SubscriptionDelaySubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=delayWhen.js.map /***/ }), -/* 245 */ +/* 262 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scheduleObservable", function() { return scheduleObservable; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(177); -/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(183); -/** PURE_IMPORTS_START _Observable,_Subscription,_symbol_observable PURE_IMPORTS_END */ - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dematerialize", function() { return dematerialize; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function scheduleObservable(input, scheduler) { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { - var sub = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"](); - sub.add(scheduler.schedule(function () { - var observable = input[_symbol_observable__WEBPACK_IMPORTED_MODULE_2__["observable"]](); - sub.add(observable.subscribe({ - next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); }, - error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); }, - complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); }, - })); - })); - return sub; - }); +function dematerialize() { + return function dematerializeOperatorFunction(source) { + return source.lift(new DeMaterializeOperator()); + }; } -//# sourceMappingURL=scheduleObservable.js.map +var DeMaterializeOperator = /*@__PURE__*/ (function () { + function DeMaterializeOperator() { + } + DeMaterializeOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DeMaterializeSubscriber(subscriber)); + }; + return DeMaterializeOperator; +}()); +var DeMaterializeSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DeMaterializeSubscriber, _super); + function DeMaterializeSubscriber(destination) { + return _super.call(this, destination) || this; + } + DeMaterializeSubscriber.prototype._next = function (value) { + value.observe(this.destination); + }; + return DeMaterializeSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=dematerialize.js.map /***/ }), -/* 246 */ +/* 263 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "schedulePromise", function() { return schedulePromise; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(177); -/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "distinct", function() { return distinct; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DistinctSubscriber", function() { return DistinctSubscriber; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function schedulePromise(input, scheduler) { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { - var sub = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"](); - sub.add(scheduler.schedule(function () { - return input.then(function (value) { - sub.add(scheduler.schedule(function () { - subscriber.next(value); - sub.add(scheduler.schedule(function () { return subscriber.complete(); })); - })); - }, function (err) { - sub.add(scheduler.schedule(function () { return subscriber.error(err); })); - }); - })); - return sub; - }); + +function distinct(keySelector, flushes) { + return function (source) { return source.lift(new DistinctOperator(keySelector, flushes)); }; } -//# sourceMappingURL=schedulePromise.js.map +var DistinctOperator = /*@__PURE__*/ (function () { + function DistinctOperator(keySelector, flushes) { + this.keySelector = keySelector; + this.flushes = flushes; + } + DistinctOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes)); + }; + return DistinctOperator; +}()); +var DistinctSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DistinctSubscriber, _super); + function DistinctSubscriber(destination, keySelector, flushes) { + var _this = _super.call(this, destination) || this; + _this.keySelector = keySelector; + _this.values = new Set(); + if (flushes) { + _this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(_this, flushes)); + } + return _this; + } + DistinctSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.values.clear(); + }; + DistinctSubscriber.prototype.notifyError = function (error, innerSub) { + this._error(error); + }; + DistinctSubscriber.prototype._next = function (value) { + if (this.keySelector) { + this._useKeySelector(value); + } + else { + this._finalizeNext(value, value); + } + }; + DistinctSubscriber.prototype._useKeySelector = function (value) { + var key; + var destination = this.destination; + try { + key = this.keySelector(value); + } + catch (err) { + destination.error(err); + return; + } + this._finalizeNext(key, value); + }; + DistinctSubscriber.prototype._finalizeNext = function (key, value) { + var values = this.values; + if (!values.has(key)) { + values.add(key); + this.destination.next(value); + } + }; + return DistinctSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); + +//# sourceMappingURL=distinct.js.map /***/ }), -/* 247 */ +/* 264 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scheduleIterable", function() { return scheduleIterable; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(177); -/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(235); -/** PURE_IMPORTS_START _Observable,_Subscription,_symbol_iterator PURE_IMPORTS_END */ - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "distinctUntilChanged", function() { return distinctUntilChanged; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function scheduleIterable(input, scheduler) { - if (!input) { - throw new Error('Iterable cannot be null'); +function distinctUntilChanged(compare, keySelector) { + return function (source) { return source.lift(new DistinctUntilChangedOperator(compare, keySelector)); }; +} +var DistinctUntilChangedOperator = /*@__PURE__*/ (function () { + function DistinctUntilChangedOperator(compare, keySelector) { + this.compare = compare; + this.keySelector = keySelector; } - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { - var sub = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"](); - var iterator; - sub.add(function () { - if (iterator && typeof iterator.return === 'function') { - iterator.return(); + DistinctUntilChangedOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector)); + }; + return DistinctUntilChangedOperator; +}()); +var DistinctUntilChangedSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DistinctUntilChangedSubscriber, _super); + function DistinctUntilChangedSubscriber(destination, compare, keySelector) { + var _this = _super.call(this, destination) || this; + _this.keySelector = keySelector; + _this.hasKey = false; + if (typeof compare === 'function') { + _this.compare = compare; + } + return _this; + } + DistinctUntilChangedSubscriber.prototype.compare = function (x, y) { + return x === y; + }; + DistinctUntilChangedSubscriber.prototype._next = function (value) { + var key; + try { + var keySelector = this.keySelector; + key = keySelector ? keySelector(value) : value; + } + catch (err) { + return this.destination.error(err); + } + var result = false; + if (this.hasKey) { + try { + var compare = this.compare; + result = compare(this.key, key); } - }); - sub.add(scheduler.schedule(function () { - iterator = input[_symbol_iterator__WEBPACK_IMPORTED_MODULE_2__["iterator"]](); - sub.add(scheduler.schedule(function () { - if (subscriber.closed) { - return; - } - var value; - var done; - try { - var result = iterator.next(); - value = result.value; - done = result.done; - } - catch (err) { - subscriber.error(err); - return; - } - if (done) { - subscriber.complete(); - } - else { - subscriber.next(value); - this.schedule(); - } - })); - })); - return sub; - }); -} -//# sourceMappingURL=scheduleIterable.js.map + catch (err) { + return this.destination.error(err); + } + } + else { + this.hasKey = true; + } + if (!result) { + this.key = key; + this.destination.next(value); + } + }; + return DistinctUntilChangedSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=distinctUntilChanged.js.map /***/ }), -/* 248 */ +/* 265 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isInteropObservable", function() { return isInteropObservable; }); -/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(183); -/** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "distinctUntilKeyChanged", function() { return distinctUntilKeyChanged; }); +/* harmony import */ var _distinctUntilChanged__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(264); +/** PURE_IMPORTS_START _distinctUntilChanged PURE_IMPORTS_END */ -function isInteropObservable(input) { - return input && typeof input[_symbol_observable__WEBPACK_IMPORTED_MODULE_0__["observable"]] === 'function'; +function distinctUntilKeyChanged(key, compare) { + return Object(_distinctUntilChanged__WEBPACK_IMPORTED_MODULE_0__["distinctUntilChanged"])(function (x, y) { return compare ? compare(x[key], y[key]) : x[key] === y[key]; }); } -//# sourceMappingURL=isInteropObservable.js.map +//# sourceMappingURL=distinctUntilKeyChanged.js.map /***/ }), -/* 249 */ +/* 266 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isIterable", function() { return isIterable; }); -/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(235); -/** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "elementAt", function() { return elementAt; }); +/* harmony import */ var _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(193); +/* harmony import */ var _filter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(235); +/* harmony import */ var _throwIfEmpty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(267); +/* harmony import */ var _defaultIfEmpty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(258); +/* harmony import */ var _take__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(268); +/** PURE_IMPORTS_START _util_ArgumentOutOfRangeError,_filter,_throwIfEmpty,_defaultIfEmpty,_take PURE_IMPORTS_END */ -function isIterable(input) { - return input && typeof input[_symbol_iterator__WEBPACK_IMPORTED_MODULE_0__["iterator"]] === 'function'; + + + + +function elementAt(index, defaultValue) { + if (index < 0) { + throw new _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_0__["ArgumentOutOfRangeError"](); + } + var hasDefaultValue = arguments.length >= 2; + return function (source) { + return source.pipe(Object(_filter__WEBPACK_IMPORTED_MODULE_1__["filter"])(function (v, i) { return i === index; }), Object(_take__WEBPACK_IMPORTED_MODULE_4__["take"])(1), hasDefaultValue + ? Object(_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_3__["defaultIfEmpty"])(defaultValue) + : Object(_throwIfEmpty__WEBPACK_IMPORTED_MODULE_2__["throwIfEmpty"])(function () { return new _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_0__["ArgumentOutOfRangeError"](); })); + }; } -//# sourceMappingURL=isIterable.js.map +//# sourceMappingURL=elementAt.js.map /***/ }), -/* 250 */ +/* 267 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defer", function() { return defer; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(243); -/* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(203); -/** PURE_IMPORTS_START _Observable,_from,_empty PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "throwIfEmpty", function() { return throwIfEmpty; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _util_EmptyError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(194); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_util_EmptyError,_Subscriber PURE_IMPORTS_END */ -function defer(observableFactory) { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { - var input; - try { - input = observableFactory(); +function throwIfEmpty(errorFactory) { + if (errorFactory === void 0) { + errorFactory = defaultErrorFactory; + } + return function (source) { + return source.lift(new ThrowIfEmptyOperator(errorFactory)); + }; +} +var ThrowIfEmptyOperator = /*@__PURE__*/ (function () { + function ThrowIfEmptyOperator(errorFactory) { + this.errorFactory = errorFactory; + } + ThrowIfEmptyOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ThrowIfEmptySubscriber(subscriber, this.errorFactory)); + }; + return ThrowIfEmptyOperator; +}()); +var ThrowIfEmptySubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ThrowIfEmptySubscriber, _super); + function ThrowIfEmptySubscriber(destination, errorFactory) { + var _this = _super.call(this, destination) || this; + _this.errorFactory = errorFactory; + _this.hasValue = false; + return _this; + } + ThrowIfEmptySubscriber.prototype._next = function (value) { + this.hasValue = true; + this.destination.next(value); + }; + ThrowIfEmptySubscriber.prototype._complete = function () { + if (!this.hasValue) { + var err = void 0; + try { + err = this.errorFactory(); + } + catch (e) { + err = e; + } + this.destination.error(err); } - catch (err) { - subscriber.error(err); - return undefined; + else { + return this.destination.complete(); } - var source = input ? Object(_from__WEBPACK_IMPORTED_MODULE_1__["from"])(input) : Object(_empty__WEBPACK_IMPORTED_MODULE_2__["empty"])(); - return source.subscribe(subscriber); - }); + }; + return ThrowIfEmptySubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_2__["Subscriber"])); +function defaultErrorFactory() { + return new _util_EmptyError__WEBPACK_IMPORTED_MODULE_1__["EmptyError"](); } -//# sourceMappingURL=defer.js.map +//# sourceMappingURL=throwIfEmpty.js.map /***/ }), -/* 251 */ +/* 268 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "forkJoin", function() { return forkJoin; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(178); -/* harmony import */ var _operators_map__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(226); -/* harmony import */ var _util_isObject__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(179); -/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(243); -/** PURE_IMPORTS_START _Observable,_util_isArray,_operators_map,_util_isObject,_from PURE_IMPORTS_END */ - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "take", function() { return take; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/* harmony import */ var _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(193); +/* harmony import */ var _observable_empty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(174); +/** PURE_IMPORTS_START tslib,_Subscriber,_util_ArgumentOutOfRangeError,_observable_empty PURE_IMPORTS_END */ -function forkJoin() { - var sources = []; - for (var _i = 0; _i < arguments.length; _i++) { - sources[_i] = arguments[_i]; - } - if (sources.length === 1) { - var first_1 = sources[0]; - if (Object(_util_isArray__WEBPACK_IMPORTED_MODULE_1__["isArray"])(first_1)) { - return forkJoinInternal(first_1, null); +function take(count) { + return function (source) { + if (count === 0) { + return Object(_observable_empty__WEBPACK_IMPORTED_MODULE_3__["empty"])(); } - if (Object(_util_isObject__WEBPACK_IMPORTED_MODULE_3__["isObject"])(first_1) && Object.getPrototypeOf(first_1) === Object.prototype) { - var keys = Object.keys(first_1); - return forkJoinInternal(keys.map(function (key) { return first_1[key]; }), keys); + else { + return source.lift(new TakeOperator(count)); } - } - if (typeof sources[sources.length - 1] === 'function') { - var resultSelector_1 = sources.pop(); - sources = (sources.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_1__["isArray"])(sources[0])) ? sources[0] : sources; - return forkJoinInternal(sources, null).pipe(Object(_operators_map__WEBPACK_IMPORTED_MODULE_2__["map"])(function (args) { return resultSelector_1.apply(void 0, args); })); - } - return forkJoinInternal(sources, null); + }; } -function forkJoinInternal(sources, keys) { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { - var len = sources.length; - if (len === 0) { - subscriber.complete(); - return; +var TakeOperator = /*@__PURE__*/ (function () { + function TakeOperator(total) { + this.total = total; + if (this.total < 0) { + throw new _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_2__["ArgumentOutOfRangeError"]; } - var values = new Array(len); - var completed = 0; - var emitted = 0; - var _loop_1 = function (i) { - var source = Object(_from__WEBPACK_IMPORTED_MODULE_4__["from"])(sources[i]); - var hasValue = false; - subscriber.add(source.subscribe({ - next: function (value) { - if (!hasValue) { - hasValue = true; - emitted++; - } - values[i] = value; - }, - error: function (err) { return subscriber.error(err); }, - complete: function () { - completed++; - if (completed === len || !hasValue) { - if (emitted === len) { - subscriber.next(keys ? - keys.reduce(function (result, key, i) { return (result[key] = values[i], result); }, {}) : - values); - } - subscriber.complete(); - } - } - })); - }; - for (var i = 0; i < len; i++) { - _loop_1(i); + } + TakeOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new TakeSubscriber(subscriber, this.total)); + }; + return TakeOperator; +}()); +var TakeSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TakeSubscriber, _super); + function TakeSubscriber(destination, total) { + var _this = _super.call(this, destination) || this; + _this.total = total; + _this.count = 0; + return _this; + } + TakeSubscriber.prototype._next = function (value) { + var total = this.total; + var count = ++this.count; + if (count <= total) { + this.destination.next(value); + if (count === total) { + this.destination.complete(); + this.unsubscribe(); + } } - }); -} -//# sourceMappingURL=forkJoin.js.map + }; + return TakeSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=take.js.map /***/ }), -/* 252 */ +/* 269 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromEvent", function() { return fromEvent; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(178); -/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(173); -/* harmony import */ var _operators_map__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(226); -/** PURE_IMPORTS_START _Observable,_util_isArray,_util_isFunction,_operators_map PURE_IMPORTS_END */ - - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "endWith", function() { return endWith; }); +/* harmony import */ var _observable_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(210); +/* harmony import */ var _observable_of__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(175); +/** PURE_IMPORTS_START _observable_concat,_observable_of PURE_IMPORTS_END */ -var toString = /*@__PURE__*/ (function () { return Object.prototype.toString; })(); -function fromEvent(target, eventName, options, resultSelector) { - if (Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_2__["isFunction"])(options)) { - resultSelector = options; - options = undefined; - } - if (resultSelector) { - return fromEvent(target, eventName, options).pipe(Object(_operators_map__WEBPACK_IMPORTED_MODULE_3__["map"])(function (args) { return Object(_util_isArray__WEBPACK_IMPORTED_MODULE_1__["isArray"])(args) ? resultSelector.apply(void 0, args) : resultSelector(args); })); - } - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { - function handler(e) { - if (arguments.length > 1) { - subscriber.next(Array.prototype.slice.call(arguments)); - } - else { - subscriber.next(e); - } - } - setupSubscription(target, eventName, handler, subscriber, options); - }); -} -function setupSubscription(sourceObj, eventName, handler, subscriber, options) { - var unsubscribe; - if (isEventTarget(sourceObj)) { - var source_1 = sourceObj; - sourceObj.addEventListener(eventName, handler, options); - unsubscribe = function () { return source_1.removeEventListener(eventName, handler, options); }; - } - else if (isJQueryStyleEventEmitter(sourceObj)) { - var source_2 = sourceObj; - sourceObj.on(eventName, handler); - unsubscribe = function () { return source_2.off(eventName, handler); }; - } - else if (isNodeStyleEventEmitter(sourceObj)) { - var source_3 = sourceObj; - sourceObj.addListener(eventName, handler); - unsubscribe = function () { return source_3.removeListener(eventName, handler); }; - } - else if (sourceObj && sourceObj.length) { - for (var i = 0, len = sourceObj.length; i < len; i++) { - setupSubscription(sourceObj[i], eventName, handler, subscriber, options); - } - } - else { - throw new TypeError('Invalid event target'); +function endWith() { + var array = []; + for (var _i = 0; _i < arguments.length; _i++) { + array[_i] = arguments[_i]; } - subscriber.add(unsubscribe); -} -function isNodeStyleEventEmitter(sourceObj) { - return sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function'; -} -function isJQueryStyleEventEmitter(sourceObj) { - return sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function'; -} -function isEventTarget(sourceObj) { - return sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function'; + return function (source) { return Object(_observable_concat__WEBPACK_IMPORTED_MODULE_0__["concat"])(source, _observable_of__WEBPACK_IMPORTED_MODULE_1__["of"].apply(void 0, array)); }; } -//# sourceMappingURL=fromEvent.js.map +//# sourceMappingURL=endWith.js.map /***/ }), -/* 253 */ +/* 270 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromEventPattern", function() { return fromEventPattern; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(178); -/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(173); -/* harmony import */ var _operators_map__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(226); -/** PURE_IMPORTS_START _Observable,_util_isArray,_util_isFunction,_operators_map PURE_IMPORTS_END */ - - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "every", function() { return every; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function fromEventPattern(addHandler, removeHandler, resultSelector) { - if (resultSelector) { - return fromEventPattern(addHandler, removeHandler).pipe(Object(_operators_map__WEBPACK_IMPORTED_MODULE_3__["map"])(function (args) { return Object(_util_isArray__WEBPACK_IMPORTED_MODULE_1__["isArray"])(args) ? resultSelector.apply(void 0, args) : resultSelector(args); })); +function every(predicate, thisArg) { + return function (source) { return source.lift(new EveryOperator(predicate, thisArg, source)); }; +} +var EveryOperator = /*@__PURE__*/ (function () { + function EveryOperator(predicate, thisArg, source) { + this.predicate = predicate; + this.thisArg = thisArg; + this.source = source; } - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { - var handler = function () { - var e = []; - for (var _i = 0; _i < arguments.length; _i++) { - e[_i] = arguments[_i]; - } - return subscriber.next(e.length === 1 ? e[0] : e); - }; - var retValue; + EveryOperator.prototype.call = function (observer, source) { + return source.subscribe(new EverySubscriber(observer, this.predicate, this.thisArg, this.source)); + }; + return EveryOperator; +}()); +var EverySubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](EverySubscriber, _super); + function EverySubscriber(destination, predicate, thisArg, source) { + var _this = _super.call(this, destination) || this; + _this.predicate = predicate; + _this.thisArg = thisArg; + _this.source = source; + _this.index = 0; + _this.thisArg = thisArg || _this; + return _this; + } + EverySubscriber.prototype.notifyComplete = function (everyValueMatch) { + this.destination.next(everyValueMatch); + this.destination.complete(); + }; + EverySubscriber.prototype._next = function (value) { + var result = false; try { - retValue = addHandler(handler); + result = this.predicate.call(this.thisArg, value, this.index++, this.source); } catch (err) { - subscriber.error(err); - return undefined; + this.destination.error(err); + return; } - if (!Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_2__["isFunction"])(removeHandler)) { - return undefined; + if (!result) { + this.notifyComplete(false); } - return function () { return removeHandler(handler, retValue); }; - }); -} -//# sourceMappingURL=fromEventPattern.js.map + }; + EverySubscriber.prototype._complete = function () { + this.notifyComplete(true); + }; + return EverySubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=every.js.map /***/ }), -/* 254 */ +/* 271 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "generate", function() { return generate; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(220); -/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(205); -/** PURE_IMPORTS_START _Observable,_util_identity,_util_isScheduler PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exhaust", function() { return exhaust; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function generate(initialStateOrOptions, condition, iterate, resultSelectorOrObservable, scheduler) { - var resultSelector; - var initialState; - if (arguments.length == 1) { - var options = initialStateOrOptions; - initialState = options.initialState; - condition = options.condition; - iterate = options.iterate; - resultSelector = options.resultSelector || _util_identity__WEBPACK_IMPORTED_MODULE_1__["identity"]; - scheduler = options.scheduler; - } - else if (resultSelectorOrObservable === undefined || Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_2__["isScheduler"])(resultSelectorOrObservable)) { - initialState = initialStateOrOptions; - resultSelector = _util_identity__WEBPACK_IMPORTED_MODULE_1__["identity"]; - scheduler = resultSelectorOrObservable; - } - else { - initialState = initialStateOrOptions; - resultSelector = resultSelectorOrObservable; - } - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { - var state = initialState; - if (scheduler) { - return scheduler.schedule(dispatch, 0, { - subscriber: subscriber, - iterate: iterate, - condition: condition, - resultSelector: resultSelector, - state: state - }); - } - do { - if (condition) { - var conditionResult = void 0; - try { - conditionResult = condition(state); - } - catch (err) { - subscriber.error(err); - return undefined; - } - if (!conditionResult) { - subscriber.complete(); - break; - } - } - var value = void 0; - try { - value = resultSelector(state); - } - catch (err) { - subscriber.error(err); - return undefined; - } - subscriber.next(value); - if (subscriber.closed) { - break; - } - try { - state = iterate(state); - } - catch (err) { - subscriber.error(err); - return undefined; - } - } while (true); - return undefined; - }); +function exhaust() { + return function (source) { return source.lift(new SwitchFirstOperator()); }; } -function dispatch(state) { - var subscriber = state.subscriber, condition = state.condition; - if (subscriber.closed) { - return undefined; - } - if (state.needIterate) { - try { - state.state = state.iterate(state.state); - } - catch (err) { - subscriber.error(err); - return undefined; - } +var SwitchFirstOperator = /*@__PURE__*/ (function () { + function SwitchFirstOperator() { } - else { - state.needIterate = true; + SwitchFirstOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new SwitchFirstSubscriber(subscriber)); + }; + return SwitchFirstOperator; +}()); +var SwitchFirstSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SwitchFirstSubscriber, _super); + function SwitchFirstSubscriber(destination) { + var _this = _super.call(this, destination) || this; + _this.hasCompleted = false; + _this.hasSubscription = false; + return _this; } - if (condition) { - var conditionResult = void 0; - try { - conditionResult = condition(state.state); - } - catch (err) { - subscriber.error(err); - return undefined; + SwitchFirstSubscriber.prototype._next = function (value) { + if (!this.hasSubscription) { + this.hasSubscription = true; + this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, value)); } - if (!conditionResult) { - subscriber.complete(); - return undefined; + }; + SwitchFirstSubscriber.prototype._complete = function () { + this.hasCompleted = true; + if (!this.hasSubscription) { + this.destination.complete(); } - if (subscriber.closed) { - return undefined; + }; + SwitchFirstSubscriber.prototype.notifyComplete = function (innerSub) { + this.remove(innerSub); + this.hasSubscription = false; + if (this.hasCompleted) { + this.destination.complete(); } - } - var value; - try { - value = state.resultSelector(state.state); - } - catch (err) { - subscriber.error(err); - return undefined; - } - if (subscriber.closed) { - return undefined; - } - subscriber.next(value); - if (subscriber.closed) { - return undefined; - } - return this.schedule(state); -} -//# sourceMappingURL=generate.js.map + }; + return SwitchFirstSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); +//# sourceMappingURL=exhaust.js.map /***/ }), -/* 255 */ +/* 272 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "iif", function() { return iif; }); -/* harmony import */ var _defer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(250); -/* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(203); -/** PURE_IMPORTS_START _defer,_empty PURE_IMPORTS_END */ - - -function iif(condition, trueResult, falseResult) { - if (trueResult === void 0) { - trueResult = _empty__WEBPACK_IMPORTED_MODULE_1__["EMPTY"]; - } - if (falseResult === void 0) { - falseResult = _empty__WEBPACK_IMPORTED_MODULE_1__["EMPTY"]; - } - return Object(_defer__WEBPACK_IMPORTED_MODULE_0__["defer"])(function () { return condition() ? trueResult : falseResult; }); -} -//# sourceMappingURL=iif.js.map +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exhaustMap", function() { return exhaustMap; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(200); +/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(202); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(201); +/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(197); +/* harmony import */ var _observable_from__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(214); +/** PURE_IMPORTS_START tslib,_OuterSubscriber,_InnerSubscriber,_util_subscribeToResult,_map,_observable_from PURE_IMPORTS_END */ -/***/ }), -/* 256 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "interval", function() { return interval; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(215); -/* harmony import */ var _util_isNumeric__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(257); -/** PURE_IMPORTS_START _Observable,_scheduler_async,_util_isNumeric PURE_IMPORTS_END */ -function interval(period, scheduler) { - if (period === void 0) { - period = 0; +function exhaustMap(project, resultSelector) { + if (resultSelector) { + return function (source) { return source.pipe(exhaustMap(function (a, i) { return Object(_observable_from__WEBPACK_IMPORTED_MODULE_5__["from"])(project(a, i)).pipe(Object(_map__WEBPACK_IMPORTED_MODULE_4__["map"])(function (b, ii) { return resultSelector(a, b, i, ii); })); })); }; } - if (scheduler === void 0) { - scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__["async"]; + return function (source) { + return source.lift(new ExhaustMapOperator(project)); + }; +} +var ExhaustMapOperator = /*@__PURE__*/ (function () { + function ExhaustMapOperator(project) { + this.project = project; } - if (!Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_2__["isNumeric"])(period) || period < 0) { - period = 0; + ExhaustMapOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ExhaustMapSubscriber(subscriber, this.project)); + }; + return ExhaustMapOperator; +}()); +var ExhaustMapSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ExhaustMapSubscriber, _super); + function ExhaustMapSubscriber(destination, project) { + var _this = _super.call(this, destination) || this; + _this.project = project; + _this.hasSubscription = false; + _this.hasCompleted = false; + _this.index = 0; + return _this; } - if (!scheduler || typeof scheduler.schedule !== 'function') { - scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__["async"]; - } - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { - subscriber.add(scheduler.schedule(dispatch, period, { subscriber: subscriber, counter: 0, period: period })); - return subscriber; - }); -} -function dispatch(state) { - var subscriber = state.subscriber, counter = state.counter, period = state.period; - subscriber.next(counter); - this.schedule({ subscriber: subscriber, counter: counter + 1, period: period }, period); -} -//# sourceMappingURL=interval.js.map - - -/***/ }), -/* 257 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNumeric", function() { return isNumeric; }); -/* harmony import */ var _isArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(178); -/** PURE_IMPORTS_START _isArray PURE_IMPORTS_END */ - -function isNumeric(val) { - return !Object(_isArray__WEBPACK_IMPORTED_MODULE_0__["isArray"])(val) && (val - parseFloat(val) + 1) >= 0; -} -//# sourceMappingURL=isNumeric.js.map + ExhaustMapSubscriber.prototype._next = function (value) { + if (!this.hasSubscription) { + this.tryNext(value); + } + }; + ExhaustMapSubscriber.prototype.tryNext = function (value) { + var result; + var index = this.index++; + try { + result = this.project(value, index); + } + catch (err) { + this.destination.error(err); + return; + } + this.hasSubscription = true; + this._innerSub(result, value, index); + }; + ExhaustMapSubscriber.prototype._innerSub = function (result, value, index) { + var innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__["InnerSubscriber"](this, undefined, undefined); + var destination = this.destination; + destination.add(innerSubscriber); + Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(this, result, value, index, innerSubscriber); + }; + ExhaustMapSubscriber.prototype._complete = function () { + this.hasCompleted = true; + if (!this.hasSubscription) { + this.destination.complete(); + } + this.unsubscribe(); + }; + ExhaustMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.destination.next(innerValue); + }; + ExhaustMapSubscriber.prototype.notifyError = function (err) { + this.destination.error(err); + }; + ExhaustMapSubscriber.prototype.notifyComplete = function (innerSub) { + var destination = this.destination; + destination.remove(innerSub); + this.hasSubscription = false; + if (this.hasCompleted) { + this.destination.complete(); + } + }; + return ExhaustMapSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); +//# sourceMappingURL=exhaustMap.js.map /***/ }), -/* 258 */ +/* 273 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "merge", function() { return merge; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(205); -/* harmony import */ var _operators_mergeAll__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(241); -/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(206); -/** PURE_IMPORTS_START _Observable,_util_isScheduler,_operators_mergeAll,_fromArray PURE_IMPORTS_END */ - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "expand", function() { return expand; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExpandOperator", function() { return ExpandOperator; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExpandSubscriber", function() { return ExpandSubscriber; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function merge() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; +function expand(project, concurrent, scheduler) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; } - var concurrent = Number.POSITIVE_INFINITY; - var scheduler = null; - var last = observables[observables.length - 1]; - if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_1__["isScheduler"])(last)) { - scheduler = observables.pop(); - if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') { - concurrent = observables.pop(); - } + if (scheduler === void 0) { + scheduler = undefined; } - else if (typeof last === 'number') { - concurrent = observables.pop(); + concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent; + return function (source) { return source.lift(new ExpandOperator(project, concurrent, scheduler)); }; +} +var ExpandOperator = /*@__PURE__*/ (function () { + function ExpandOperator(project, concurrent, scheduler) { + this.project = project; + this.concurrent = concurrent; + this.scheduler = scheduler; } - if (scheduler === null && observables.length === 1 && observables[0] instanceof _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]) { - return observables[0]; + ExpandOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler)); + }; + return ExpandOperator; +}()); + +var ExpandSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ExpandSubscriber, _super); + function ExpandSubscriber(destination, project, concurrent, scheduler) { + var _this = _super.call(this, destination) || this; + _this.project = project; + _this.concurrent = concurrent; + _this.scheduler = scheduler; + _this.index = 0; + _this.active = 0; + _this.hasCompleted = false; + if (concurrent < Number.POSITIVE_INFINITY) { + _this.buffer = []; + } + return _this; } - return Object(_operators_mergeAll__WEBPACK_IMPORTED_MODULE_2__["mergeAll"])(concurrent)(Object(_fromArray__WEBPACK_IMPORTED_MODULE_3__["fromArray"])(observables, scheduler)); -} -//# sourceMappingURL=merge.js.map + ExpandSubscriber.dispatch = function (arg) { + var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index; + subscriber.subscribeToProjection(result, value, index); + }; + ExpandSubscriber.prototype._next = function (value) { + var destination = this.destination; + if (destination.closed) { + this._complete(); + return; + } + var index = this.index++; + if (this.active < this.concurrent) { + destination.next(value); + try { + var project = this.project; + var result = project(value, index); + if (!this.scheduler) { + this.subscribeToProjection(result, value, index); + } + else { + var state = { subscriber: this, result: result, value: value, index: index }; + var destination_1 = this.destination; + destination_1.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state)); + } + } + catch (e) { + destination.error(e); + } + } + else { + this.buffer.push(value); + } + }; + ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) { + this.active++; + var destination = this.destination; + destination.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, result, value, index)); + }; + ExpandSubscriber.prototype._complete = function () { + this.hasCompleted = true; + if (this.hasCompleted && this.active === 0) { + this.destination.complete(); + } + this.unsubscribe(); + }; + ExpandSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this._next(innerValue); + }; + ExpandSubscriber.prototype.notifyComplete = function (innerSub) { + var buffer = this.buffer; + var destination = this.destination; + destination.remove(innerSub); + this.active--; + if (buffer && buffer.length > 0) { + this._next(buffer.shift()); + } + if (this.hasCompleted && this.active === 0) { + this.destination.complete(); + } + }; + return ExpandSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); + +//# sourceMappingURL=expand.js.map /***/ }), -/* 259 */ +/* 274 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NEVER", function() { return NEVER; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "never", function() { return never; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _util_noop__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(185); -/** PURE_IMPORTS_START _Observable,_util_noop PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "finalize", function() { return finalize; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(148); +/** PURE_IMPORTS_START tslib,_Subscriber,_Subscription PURE_IMPORTS_END */ -var NEVER = /*@__PURE__*/ new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](_util_noop__WEBPACK_IMPORTED_MODULE_1__["noop"]); -function never() { - return NEVER; + +function finalize(callback) { + return function (source) { return source.lift(new FinallyOperator(callback)); }; } -//# sourceMappingURL=never.js.map +var FinallyOperator = /*@__PURE__*/ (function () { + function FinallyOperator(callback) { + this.callback = callback; + } + FinallyOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new FinallySubscriber(subscriber, this.callback)); + }; + return FinallyOperator; +}()); +var FinallySubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FinallySubscriber, _super); + function FinallySubscriber(destination, callback) { + var _this = _super.call(this, destination) || this; + _this.add(new _Subscription__WEBPACK_IMPORTED_MODULE_2__["Subscription"](callback)); + return _this; + } + return FinallySubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=finalize.js.map /***/ }), -/* 260 */ +/* 275 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onErrorResumeNext", function() { return onErrorResumeNext; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(243); -/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(178); -/* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(203); -/** PURE_IMPORTS_START _Observable,_from,_util_isArray,_empty PURE_IMPORTS_END */ - - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "find", function() { return find; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FindValueOperator", function() { return FindValueOperator; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FindValueSubscriber", function() { return FindValueSubscriber; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function onErrorResumeNext() { - var sources = []; - for (var _i = 0; _i < arguments.length; _i++) { - sources[_i] = arguments[_i]; +function find(predicate, thisArg) { + if (typeof predicate !== 'function') { + throw new TypeError('predicate is not a function'); } - if (sources.length === 0) { - return _empty__WEBPACK_IMPORTED_MODULE_3__["EMPTY"]; + return function (source) { return source.lift(new FindValueOperator(predicate, source, false, thisArg)); }; +} +var FindValueOperator = /*@__PURE__*/ (function () { + function FindValueOperator(predicate, source, yieldIndex, thisArg) { + this.predicate = predicate; + this.source = source; + this.yieldIndex = yieldIndex; + this.thisArg = thisArg; } - var first = sources[0], remainder = sources.slice(1); - if (sources.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_2__["isArray"])(first)) { - return onErrorResumeNext.apply(void 0, first); + FindValueOperator.prototype.call = function (observer, source) { + return source.subscribe(new FindValueSubscriber(observer, this.predicate, this.source, this.yieldIndex, this.thisArg)); + }; + return FindValueOperator; +}()); + +var FindValueSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FindValueSubscriber, _super); + function FindValueSubscriber(destination, predicate, source, yieldIndex, thisArg) { + var _this = _super.call(this, destination) || this; + _this.predicate = predicate; + _this.source = source; + _this.yieldIndex = yieldIndex; + _this.thisArg = thisArg; + _this.index = 0; + return _this; } - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { - var subNext = function () { return subscriber.add(onErrorResumeNext.apply(void 0, remainder).subscribe(subscriber)); }; - return Object(_from__WEBPACK_IMPORTED_MODULE_1__["from"])(first).subscribe({ - next: function (value) { subscriber.next(value); }, - error: subNext, - complete: subNext, - }); - }); -} -//# sourceMappingURL=onErrorResumeNext.js.map + FindValueSubscriber.prototype.notifyComplete = function (value) { + var destination = this.destination; + destination.next(value); + destination.complete(); + this.unsubscribe(); + }; + FindValueSubscriber.prototype._next = function (value) { + var _a = this, predicate = _a.predicate, thisArg = _a.thisArg; + var index = this.index++; + try { + var result = predicate.call(thisArg || this, value, index, this.source); + if (result) { + this.notifyComplete(this.yieldIndex ? index : value); + } + } + catch (err) { + this.destination.error(err); + } + }; + FindValueSubscriber.prototype._complete = function () { + this.notifyComplete(this.yieldIndex ? -1 : undefined); + }; + return FindValueSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); + +//# sourceMappingURL=find.js.map /***/ }), -/* 261 */ +/* 276 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pairs", function() { return pairs; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dispatch", function() { return dispatch; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(177); -/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findIndex", function() { return findIndex; }); +/* harmony import */ var _operators_find__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(275); +/** PURE_IMPORTS_START _operators_find PURE_IMPORTS_END */ -function pairs(obj, scheduler) { - if (!scheduler) { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { - var keys = Object.keys(obj); - for (var i = 0; i < keys.length && !subscriber.closed; i++) { - var key = keys[i]; - if (obj.hasOwnProperty(key)) { - subscriber.next([key, obj[key]]); - } - } - subscriber.complete(); - }); - } - else { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { - var keys = Object.keys(obj); - var subscription = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"](); - subscription.add(scheduler.schedule(dispatch, 0, { keys: keys, index: 0, subscriber: subscriber, subscription: subscription, obj: obj })); - return subscription; - }); - } -} -function dispatch(state) { - var keys = state.keys, index = state.index, subscriber = state.subscriber, subscription = state.subscription, obj = state.obj; - if (!subscriber.closed) { - if (index < keys.length) { - var key = keys[index]; - subscriber.next([key, obj[key]]); - subscription.add(this.schedule({ keys: keys, index: index + 1, subscriber: subscriber, subscription: subscription, obj: obj })); - } - else { - subscriber.complete(); - } - } +function findIndex(predicate, thisArg) { + return function (source) { return source.lift(new _operators_find__WEBPACK_IMPORTED_MODULE_0__["FindValueOperator"](predicate, source, true, thisArg)); }; } -//# sourceMappingURL=pairs.js.map +//# sourceMappingURL=findIndex.js.map /***/ }), -/* 262 */ +/* 277 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "partition", function() { return partition; }); -/* harmony import */ var _util_not__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(263); -/* harmony import */ var _util_subscribeTo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(232); -/* harmony import */ var _operators_filter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(264); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(170); -/** PURE_IMPORTS_START _util_not,_util_subscribeTo,_operators_filter,_Observable PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "first", function() { return first; }); +/* harmony import */ var _util_EmptyError__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(194); +/* harmony import */ var _filter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(235); +/* harmony import */ var _take__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(268); +/* harmony import */ var _defaultIfEmpty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(258); +/* harmony import */ var _throwIfEmpty__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(267); +/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(191); +/** PURE_IMPORTS_START _util_EmptyError,_filter,_take,_defaultIfEmpty,_throwIfEmpty,_util_identity PURE_IMPORTS_END */ -function partition(source, predicate, thisArg) { - return [ - Object(_operators_filter__WEBPACK_IMPORTED_MODULE_2__["filter"])(predicate, thisArg)(new _Observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](Object(_util_subscribeTo__WEBPACK_IMPORTED_MODULE_1__["subscribeTo"])(source))), - Object(_operators_filter__WEBPACK_IMPORTED_MODULE_2__["filter"])(Object(_util_not__WEBPACK_IMPORTED_MODULE_0__["not"])(predicate, thisArg))(new _Observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](Object(_util_subscribeTo__WEBPACK_IMPORTED_MODULE_1__["subscribeTo"])(source))) - ]; + + +function first(predicate, defaultValue) { + var hasDefaultValue = arguments.length >= 2; + return function (source) { return source.pipe(predicate ? Object(_filter__WEBPACK_IMPORTED_MODULE_1__["filter"])(function (v, i) { return predicate(v, i, source); }) : _util_identity__WEBPACK_IMPORTED_MODULE_5__["identity"], Object(_take__WEBPACK_IMPORTED_MODULE_2__["take"])(1), hasDefaultValue ? Object(_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_3__["defaultIfEmpty"])(defaultValue) : Object(_throwIfEmpty__WEBPACK_IMPORTED_MODULE_4__["throwIfEmpty"])(function () { return new _util_EmptyError__WEBPACK_IMPORTED_MODULE_0__["EmptyError"](); })); }; } -//# sourceMappingURL=partition.js.map +//# sourceMappingURL=first.js.map /***/ }), -/* 263 */ +/* 278 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "not", function() { return not; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function not(pred, thisArg) { - function notPred() { - return !(notPred.pred.apply(notPred.thisArg, arguments)); - } - notPred.pred = pred; - notPred.thisArg = thisArg; - return notPred; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ignoreElements", function() { return ignoreElements; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ + + +function ignoreElements() { + return function ignoreElementsOperatorFunction(source) { + return source.lift(new IgnoreElementsOperator()); + }; } -//# sourceMappingURL=not.js.map +var IgnoreElementsOperator = /*@__PURE__*/ (function () { + function IgnoreElementsOperator() { + } + IgnoreElementsOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new IgnoreElementsSubscriber(subscriber)); + }; + return IgnoreElementsOperator; +}()); +var IgnoreElementsSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](IgnoreElementsSubscriber, _super); + function IgnoreElementsSubscriber() { + return _super !== null && _super.apply(this, arguments) || this; + } + IgnoreElementsSubscriber.prototype._next = function (unused) { + }; + return IgnoreElementsSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=ignoreElements.js.map /***/ }), -/* 264 */ +/* 279 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "filter", function() { return filter; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isEmpty", function() { return isEmpty; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function filter(predicate, thisArg) { - return function filterOperatorFunction(source) { - return source.lift(new FilterOperator(predicate, thisArg)); - }; +function isEmpty() { + return function (source) { return source.lift(new IsEmptyOperator()); }; } -var FilterOperator = /*@__PURE__*/ (function () { - function FilterOperator(predicate, thisArg) { - this.predicate = predicate; - this.thisArg = thisArg; +var IsEmptyOperator = /*@__PURE__*/ (function () { + function IsEmptyOperator() { } - FilterOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg)); + IsEmptyOperator.prototype.call = function (observer, source) { + return source.subscribe(new IsEmptySubscriber(observer)); }; - return FilterOperator; + return IsEmptyOperator; }()); -var FilterSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FilterSubscriber, _super); - function FilterSubscriber(destination, predicate, thisArg) { - var _this = _super.call(this, destination) || this; - _this.predicate = predicate; - _this.thisArg = thisArg; - _this.count = 0; - return _this; +var IsEmptySubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](IsEmptySubscriber, _super); + function IsEmptySubscriber(destination) { + return _super.call(this, destination) || this; } - FilterSubscriber.prototype._next = function (value) { - var result; - try { - result = this.predicate.call(this.thisArg, value, this.count++); - } - catch (err) { - this.destination.error(err); - return; - } - if (result) { - this.destination.next(value); - } + IsEmptySubscriber.prototype.notifyComplete = function (isEmpty) { + var destination = this.destination; + destination.next(isEmpty); + destination.complete(); }; - return FilterSubscriber; + IsEmptySubscriber.prototype._next = function (value) { + this.notifyComplete(false); + }; + IsEmptySubscriber.prototype._complete = function () { + this.notifyComplete(true); + }; + return IsEmptySubscriber; }(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=filter.js.map +//# sourceMappingURL=isEmpty.js.map /***/ }), -/* 265 */ +/* 280 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "race", function() { return race; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RaceOperator", function() { return RaceOperator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RaceSubscriber", function() { return RaceSubscriber; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(178); -/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(206); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_util_isArray,_fromArray,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "last", function() { return last; }); +/* harmony import */ var _util_EmptyError__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(194); +/* harmony import */ var _filter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(235); +/* harmony import */ var _takeLast__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(281); +/* harmony import */ var _throwIfEmpty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(267); +/* harmony import */ var _defaultIfEmpty__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(258); +/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(191); +/** PURE_IMPORTS_START _util_EmptyError,_filter,_takeLast,_throwIfEmpty,_defaultIfEmpty,_util_identity PURE_IMPORTS_END */ -function race() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; - } - if (observables.length === 1) { - if (Object(_util_isArray__WEBPACK_IMPORTED_MODULE_1__["isArray"])(observables[0])) { - observables = observables[0]; - } - else { - return observables[0]; - } - } - return Object(_fromArray__WEBPACK_IMPORTED_MODULE_2__["fromArray"])(observables, undefined).lift(new RaceOperator()); -} -var RaceOperator = /*@__PURE__*/ (function () { - function RaceOperator() { - } - RaceOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new RaceSubscriber(subscriber)); - }; - return RaceOperator; -}()); -var RaceSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RaceSubscriber, _super); - function RaceSubscriber(destination) { +function last(predicate, defaultValue) { + var hasDefaultValue = arguments.length >= 2; + return function (source) { return source.pipe(predicate ? Object(_filter__WEBPACK_IMPORTED_MODULE_1__["filter"])(function (v, i) { return predicate(v, i, source); }) : _util_identity__WEBPACK_IMPORTED_MODULE_5__["identity"], Object(_takeLast__WEBPACK_IMPORTED_MODULE_2__["takeLast"])(1), hasDefaultValue ? Object(_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_4__["defaultIfEmpty"])(defaultValue) : Object(_throwIfEmpty__WEBPACK_IMPORTED_MODULE_3__["throwIfEmpty"])(function () { return new _util_EmptyError__WEBPACK_IMPORTED_MODULE_0__["EmptyError"](); })); }; +} +//# sourceMappingURL=last.js.map + + +/***/ }), +/* 281 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "takeLast", function() { return takeLast; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/* harmony import */ var _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(193); +/* harmony import */ var _observable_empty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(174); +/** PURE_IMPORTS_START tslib,_Subscriber,_util_ArgumentOutOfRangeError,_observable_empty PURE_IMPORTS_END */ + + + + +function takeLast(count) { + return function takeLastOperatorFunction(source) { + if (count === 0) { + return Object(_observable_empty__WEBPACK_IMPORTED_MODULE_3__["empty"])(); + } + else { + return source.lift(new TakeLastOperator(count)); + } + }; +} +var TakeLastOperator = /*@__PURE__*/ (function () { + function TakeLastOperator(total) { + this.total = total; + if (this.total < 0) { + throw new _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_2__["ArgumentOutOfRangeError"]; + } + } + TakeLastOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new TakeLastSubscriber(subscriber, this.total)); + }; + return TakeLastOperator; +}()); +var TakeLastSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TakeLastSubscriber, _super); + function TakeLastSubscriber(destination, total) { var _this = _super.call(this, destination) || this; - _this.hasFirst = false; - _this.observables = []; - _this.subscriptions = []; + _this.total = total; + _this.ring = new Array(); + _this.count = 0; return _this; } - RaceSubscriber.prototype._next = function (observable) { - this.observables.push(observable); - }; - RaceSubscriber.prototype._complete = function () { - var observables = this.observables; - var len = observables.length; - if (len === 0) { - this.destination.complete(); + TakeLastSubscriber.prototype._next = function (value) { + var ring = this.ring; + var total = this.total; + var count = this.count++; + if (ring.length < total) { + ring.push(value); } else { - for (var i = 0; i < len && !this.hasFirst; i++) { - var observable = observables[i]; - var subscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__["subscribeToResult"])(this, observable, observable, i); - if (this.subscriptions) { - this.subscriptions.push(subscription); - } - this.add(subscription); - } - this.observables = null; + var index = count % total; + ring[index] = value; } }; - RaceSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - if (!this.hasFirst) { - this.hasFirst = true; - for (var i = 0; i < this.subscriptions.length; i++) { - if (i !== outerIndex) { - var subscription = this.subscriptions[i]; - subscription.unsubscribe(); - this.remove(subscription); - } + TakeLastSubscriber.prototype._complete = function () { + var destination = this.destination; + var count = this.count; + if (count > 0) { + var total = this.count >= this.total ? this.total : this.count; + var ring = this.ring; + for (var i = 0; i < total; i++) { + var idx = (count++) % total; + destination.next(ring[idx]); } - this.subscriptions = null; } - this.destination.next(innerValue); + destination.complete(); }; - return RaceSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__["OuterSubscriber"])); - -//# sourceMappingURL=race.js.map + return TakeLastSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=takeLast.js.map /***/ }), -/* 266 */ +/* 282 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "range", function() { return range; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dispatch", function() { return dispatch; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapTo", function() { return mapTo; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function range(start, count, scheduler) { - if (start === void 0) { - start = 0; - } - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { - if (count === undefined) { - count = start; - start = 0; - } - var index = 0; - var current = start; - if (scheduler) { - return scheduler.schedule(dispatch, 0, { - index: index, count: count, start: start, subscriber: subscriber - }); - } - else { - do { - if (index++ >= count) { - subscriber.complete(); - break; - } - subscriber.next(current++); - if (subscriber.closed) { - break; - } - } while (true); - } - return undefined; - }); + +function mapTo(value) { + return function (source) { return source.lift(new MapToOperator(value)); }; } -function dispatch(state) { - var start = state.start, index = state.index, count = state.count, subscriber = state.subscriber; - if (index >= count) { - subscriber.complete(); - return; +var MapToOperator = /*@__PURE__*/ (function () { + function MapToOperator(value) { + this.value = value; } - subscriber.next(start); - if (subscriber.closed) { - return; + MapToOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new MapToSubscriber(subscriber, this.value)); + }; + return MapToOperator; +}()); +var MapToSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MapToSubscriber, _super); + function MapToSubscriber(destination, value) { + var _this = _super.call(this, destination) || this; + _this.value = value; + return _this; } - state.index = index + 1; - state.start = start + 1; - this.schedule(state); -} -//# sourceMappingURL=range.js.map + MapToSubscriber.prototype._next = function (x) { + this.destination.next(this.value); + }; + return MapToSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=mapTo.js.map /***/ }), -/* 267 */ +/* 283 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timer", function() { return timer; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(215); -/* harmony import */ var _util_isNumeric__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(257); -/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(205); -/** PURE_IMPORTS_START _Observable,_scheduler_async,_util_isNumeric,_util_isScheduler PURE_IMPORTS_END */ - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "materialize", function() { return materialize; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/* harmony import */ var _Notification__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(173); +/** PURE_IMPORTS_START tslib,_Subscriber,_Notification PURE_IMPORTS_END */ -function timer(dueTime, periodOrScheduler, scheduler) { - if (dueTime === void 0) { - dueTime = 0; - } - var period = -1; - if (Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_2__["isNumeric"])(periodOrScheduler)) { - period = Number(periodOrScheduler) < 1 && 1 || Number(periodOrScheduler); - } - else if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_3__["isScheduler"])(periodOrScheduler)) { - scheduler = periodOrScheduler; - } - if (!Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_3__["isScheduler"])(scheduler)) { - scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__["async"]; - } - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { - var due = Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_2__["isNumeric"])(dueTime) - ? dueTime - : (+dueTime - scheduler.now()); - return scheduler.schedule(dispatch, due, { - index: 0, period: period, subscriber: subscriber - }); - }); +function materialize() { + return function materializeOperatorFunction(source) { + return source.lift(new MaterializeOperator()); + }; } -function dispatch(state) { - var index = state.index, period = state.period, subscriber = state.subscriber; - subscriber.next(index); - if (subscriber.closed) { - return; +var MaterializeOperator = /*@__PURE__*/ (function () { + function MaterializeOperator() { } - else if (period === -1) { - return subscriber.complete(); + MaterializeOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new MaterializeSubscriber(subscriber)); + }; + return MaterializeOperator; +}()); +var MaterializeSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MaterializeSubscriber, _super); + function MaterializeSubscriber(destination) { + return _super.call(this, destination) || this; } - state.index = index + 1; - this.schedule(state, period); + MaterializeSubscriber.prototype._next = function (value) { + this.destination.next(_Notification__WEBPACK_IMPORTED_MODULE_2__["Notification"].createNext(value)); + }; + MaterializeSubscriber.prototype._error = function (err) { + var destination = this.destination; + destination.next(_Notification__WEBPACK_IMPORTED_MODULE_2__["Notification"].createError(err)); + destination.complete(); + }; + MaterializeSubscriber.prototype._complete = function () { + var destination = this.destination; + destination.next(_Notification__WEBPACK_IMPORTED_MODULE_2__["Notification"].createComplete()); + destination.complete(); + }; + return MaterializeSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=materialize.js.map + + +/***/ }), +/* 284 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "max", function() { return max; }); +/* harmony import */ var _reduce__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(285); +/** PURE_IMPORTS_START _reduce PURE_IMPORTS_END */ + +function max(comparer) { + var max = (typeof comparer === 'function') + ? function (x, y) { return comparer(x, y) > 0 ? x : y; } + : function (x, y) { return x > y ? x : y; }; + return Object(_reduce__WEBPACK_IMPORTED_MODULE_0__["reduce"])(max); } -//# sourceMappingURL=timer.js.map +//# sourceMappingURL=max.js.map /***/ }), -/* 268 */ +/* 285 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "using", function() { return using; }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(170); -/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(243); -/* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(203); -/** PURE_IMPORTS_START _Observable,_from,_empty PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reduce", function() { return reduce; }); +/* harmony import */ var _scan__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(286); +/* harmony import */ var _takeLast__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(281); +/* harmony import */ var _defaultIfEmpty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(258); +/* harmony import */ var _util_pipe__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(155); +/** PURE_IMPORTS_START _scan,_takeLast,_defaultIfEmpty,_util_pipe PURE_IMPORTS_END */ -function using(resourceFactory, observableFactory) { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) { - var resource; - try { - resource = resourceFactory(); + +function reduce(accumulator, seed) { + if (arguments.length >= 2) { + return function reduceOperatorFunctionWithSeed(source) { + return Object(_util_pipe__WEBPACK_IMPORTED_MODULE_3__["pipe"])(Object(_scan__WEBPACK_IMPORTED_MODULE_0__["scan"])(accumulator, seed), Object(_takeLast__WEBPACK_IMPORTED_MODULE_1__["takeLast"])(1), Object(_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_2__["defaultIfEmpty"])(seed))(source); + }; + } + return function reduceOperatorFunction(source) { + return Object(_util_pipe__WEBPACK_IMPORTED_MODULE_3__["pipe"])(Object(_scan__WEBPACK_IMPORTED_MODULE_0__["scan"])(function (acc, value, index) { return accumulator(acc, value, index + 1); }), Object(_takeLast__WEBPACK_IMPORTED_MODULE_1__["takeLast"])(1))(source); + }; +} +//# sourceMappingURL=reduce.js.map + + +/***/ }), +/* 286 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scan", function() { return scan; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ + + +function scan(accumulator, seed) { + var hasSeed = false; + if (arguments.length >= 2) { + hasSeed = true; + } + return function scanOperatorFunction(source) { + return source.lift(new ScanOperator(accumulator, seed, hasSeed)); + }; +} +var ScanOperator = /*@__PURE__*/ (function () { + function ScanOperator(accumulator, seed, hasSeed) { + if (hasSeed === void 0) { + hasSeed = false; } - catch (err) { - subscriber.error(err); - return undefined; + this.accumulator = accumulator; + this.seed = seed; + this.hasSeed = hasSeed; + } + ScanOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed)); + }; + return ScanOperator; +}()); +var ScanSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ScanSubscriber, _super); + function ScanSubscriber(destination, accumulator, _seed, hasSeed) { + var _this = _super.call(this, destination) || this; + _this.accumulator = accumulator; + _this._seed = _seed; + _this.hasSeed = hasSeed; + _this.index = 0; + return _this; + } + Object.defineProperty(ScanSubscriber.prototype, "seed", { + get: function () { + return this._seed; + }, + set: function (value) { + this.hasSeed = true; + this._seed = value; + }, + enumerable: true, + configurable: true + }); + ScanSubscriber.prototype._next = function (value) { + if (!this.hasSeed) { + this.seed = value; + this.destination.next(value); + } + else { + return this._tryNext(value); } + }; + ScanSubscriber.prototype._tryNext = function (value) { + var index = this.index++; var result; try { - result = observableFactory(resource); + result = this.accumulator(this.seed, value, index); } catch (err) { - subscriber.error(err); - return undefined; + this.destination.error(err); } - var source = result ? Object(_from__WEBPACK_IMPORTED_MODULE_1__["from"])(result) : _empty__WEBPACK_IMPORTED_MODULE_2__["EMPTY"]; - var subscription = source.subscribe(subscriber); - return function () { - subscription.unsubscribe(); - if (resource) { - resource.unsubscribe(); - } - }; - }); + this.seed = result; + this.destination.next(result); + }; + return ScanSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=scan.js.map + + +/***/ }), +/* 287 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "merge", function() { return merge; }); +/* harmony import */ var _observable_merge__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(229); +/** PURE_IMPORTS_START _observable_merge PURE_IMPORTS_END */ + +function merge() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; + } + return function (source) { return source.lift.call(_observable_merge__WEBPACK_IMPORTED_MODULE_0__["merge"].apply(void 0, [source].concat(observables))); }; } -//# sourceMappingURL=using.js.map +//# sourceMappingURL=merge.js.map /***/ }), -/* 269 */ +/* 288 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "zip", function() { return zip; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ZipOperator", function() { return ZipOperator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ZipSubscriber", function() { return ZipSubscriber; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(206); -/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(178); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(172); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(230); -/* harmony import */ var _internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(235); -/** PURE_IMPORTS_START tslib,_fromArray,_util_isArray,_Subscriber,_OuterSubscriber,_util_subscribeToResult,_.._internal_symbol_iterator PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeMapTo", function() { return mergeMapTo; }); +/* harmony import */ var _mergeMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(213); +/** PURE_IMPORTS_START _mergeMap PURE_IMPORTS_END */ + +function mergeMapTo(innerObservable, resultSelector, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + if (typeof resultSelector === 'function') { + return Object(_mergeMap__WEBPACK_IMPORTED_MODULE_0__["mergeMap"])(function () { return innerObservable; }, resultSelector, concurrent); + } + if (typeof resultSelector === 'number') { + concurrent = resultSelector; + } + return Object(_mergeMap__WEBPACK_IMPORTED_MODULE_0__["mergeMap"])(function () { return innerObservable; }, concurrent); +} +//# sourceMappingURL=mergeMapTo.js.map +/***/ }), +/* 289 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeScan", function() { return mergeScan; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MergeScanOperator", function() { return MergeScanOperator; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MergeScanSubscriber", function() { return MergeScanSubscriber; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(201); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(200); +/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(202); +/** PURE_IMPORTS_START tslib,_util_subscribeToResult,_OuterSubscriber,_InnerSubscriber PURE_IMPORTS_END */ -function zip() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; - } - var resultSelector = observables[observables.length - 1]; - if (typeof resultSelector === 'function') { - observables.pop(); +function mergeScan(accumulator, seed, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; } - return Object(_fromArray__WEBPACK_IMPORTED_MODULE_1__["fromArray"])(observables, undefined).lift(new ZipOperator(resultSelector)); + return function (source) { return source.lift(new MergeScanOperator(accumulator, seed, concurrent)); }; } -var ZipOperator = /*@__PURE__*/ (function () { - function ZipOperator(resultSelector) { - this.resultSelector = resultSelector; +var MergeScanOperator = /*@__PURE__*/ (function () { + function MergeScanOperator(accumulator, seed, concurrent) { + this.accumulator = accumulator; + this.seed = seed; + this.concurrent = concurrent; } - ZipOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new ZipSubscriber(subscriber, this.resultSelector)); + MergeScanOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new MergeScanSubscriber(subscriber, this.accumulator, this.seed, this.concurrent)); }; - return ZipOperator; + return MergeScanOperator; }()); -var ZipSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ZipSubscriber, _super); - function ZipSubscriber(destination, resultSelector, values) { - if (values === void 0) { - values = Object.create(null); - } +var MergeScanSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MergeScanSubscriber, _super); + function MergeScanSubscriber(destination, accumulator, acc, concurrent) { var _this = _super.call(this, destination) || this; - _this.iterators = []; + _this.accumulator = accumulator; + _this.acc = acc; + _this.concurrent = concurrent; + _this.hasValue = false; + _this.hasCompleted = false; + _this.buffer = []; _this.active = 0; - _this.resultSelector = (typeof resultSelector === 'function') ? resultSelector : null; - _this.values = values; + _this.index = 0; return _this; } - ZipSubscriber.prototype._next = function (value) { - var iterators = this.iterators; - if (Object(_util_isArray__WEBPACK_IMPORTED_MODULE_2__["isArray"])(value)) { - iterators.push(new StaticArrayIterator(value)); - } - else if (typeof value[_internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_6__["iterator"]] === 'function') { - iterators.push(new StaticIterator(value[_internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_6__["iterator"]]())); + MergeScanSubscriber.prototype._next = function (value) { + if (this.active < this.concurrent) { + var index = this.index++; + var destination = this.destination; + var ish = void 0; + try { + var accumulator = this.accumulator; + ish = accumulator(this.acc, value, index); + } + catch (e) { + return destination.error(e); + } + this.active++; + this._innerSub(ish, value, index); } else { - iterators.push(new ZipBufferIterator(this.destination, this, value)); + this.buffer.push(value); } }; - ZipSubscriber.prototype._complete = function () { - var iterators = this.iterators; - var len = iterators.length; - this.unsubscribe(); - if (len === 0) { + MergeScanSubscriber.prototype._innerSub = function (ish, value, index) { + var innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_3__["InnerSubscriber"](this, undefined, undefined); + var destination = this.destination; + destination.add(innerSubscriber); + Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__["subscribeToResult"])(this, ish, value, index, innerSubscriber); + }; + MergeScanSubscriber.prototype._complete = function () { + this.hasCompleted = true; + if (this.active === 0 && this.buffer.length === 0) { + if (this.hasValue === false) { + this.destination.next(this.acc); + } this.destination.complete(); - return; - } - this.active = len; - for (var i = 0; i < len; i++) { - var iterator = iterators[i]; - if (iterator.stillUnsubscribed) { - var destination = this.destination; - destination.add(iterator.subscribe(iterator, i)); - } - else { - this.active--; - } } + this.unsubscribe(); }; - ZipSubscriber.prototype.notifyInactive = function () { - this.active--; - if (this.active === 0) { - this.destination.complete(); - } + MergeScanSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + var destination = this.destination; + this.acc = innerValue; + this.hasValue = true; + destination.next(innerValue); }; - ZipSubscriber.prototype.checkIterators = function () { - var iterators = this.iterators; - var len = iterators.length; + MergeScanSubscriber.prototype.notifyComplete = function (innerSub) { + var buffer = this.buffer; var destination = this.destination; - for (var i = 0; i < len; i++) { - var iterator = iterators[i]; - if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) { - return; - } + destination.remove(innerSub); + this.active--; + if (buffer.length > 0) { + this._next(buffer.shift()); } - var shouldComplete = false; - var args = []; - for (var i = 0; i < len; i++) { - var iterator = iterators[i]; - var result = iterator.next(); - if (iterator.hasCompleted()) { - shouldComplete = true; - } - if (result.done) { - destination.complete(); - return; + else if (this.active === 0 && this.hasCompleted) { + if (this.hasValue === false) { + this.destination.next(this.acc); } - args.push(result.value); + this.destination.complete(); } - if (this.resultSelector) { - this._tryresultSelector(args); + }; + return MergeScanSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"])); + +//# sourceMappingURL=mergeScan.js.map + + +/***/ }), +/* 290 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "min", function() { return min; }); +/* harmony import */ var _reduce__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(285); +/** PURE_IMPORTS_START _reduce PURE_IMPORTS_END */ + +function min(comparer) { + var min = (typeof comparer === 'function') + ? function (x, y) { return comparer(x, y) < 0 ? x : y; } + : function (x, y) { return x < y ? x : y; }; + return Object(_reduce__WEBPACK_IMPORTED_MODULE_0__["reduce"])(min); +} +//# sourceMappingURL=min.js.map + + +/***/ }), +/* 291 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "multicast", function() { return multicast; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MulticastOperator", function() { return MulticastOperator; }); +/* harmony import */ var _observable_ConnectableObservable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(157); +/** PURE_IMPORTS_START _observable_ConnectableObservable PURE_IMPORTS_END */ + +function multicast(subjectOrSubjectFactory, selector) { + return function multicastOperatorFunction(source) { + var subjectFactory; + if (typeof subjectOrSubjectFactory === 'function') { + subjectFactory = subjectOrSubjectFactory; } else { - destination.next(args); - } - if (shouldComplete) { - destination.complete(); - } - }; - ZipSubscriber.prototype._tryresultSelector = function (args) { - var result; - try { - result = this.resultSelector.apply(this, args); + subjectFactory = function subjectFactory() { + return subjectOrSubjectFactory; + }; } - catch (err) { - this.destination.error(err); - return; + if (typeof selector === 'function') { + return source.lift(new MulticastOperator(subjectFactory, selector)); } - this.destination.next(result); + var connectable = Object.create(source, _observable_ConnectableObservable__WEBPACK_IMPORTED_MODULE_0__["connectableObservableDescriptor"]); + connectable.source = source; + connectable.subjectFactory = subjectFactory; + return connectable; }; - return ZipSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_3__["Subscriber"])); - -var StaticIterator = /*@__PURE__*/ (function () { - function StaticIterator(iterator) { - this.iterator = iterator; - this.nextResult = iterator.next(); +} +var MulticastOperator = /*@__PURE__*/ (function () { + function MulticastOperator(subjectFactory, selector) { + this.subjectFactory = subjectFactory; + this.selector = selector; } - StaticIterator.prototype.hasValue = function () { - return true; - }; - StaticIterator.prototype.next = function () { - var result = this.nextResult; - this.nextResult = this.iterator.next(); - return result; - }; - StaticIterator.prototype.hasCompleted = function () { - var nextResult = this.nextResult; - return nextResult && nextResult.done; + MulticastOperator.prototype.call = function (subscriber, source) { + var selector = this.selector; + var subject = this.subjectFactory(); + var subscription = selector(subject).subscribe(subscriber); + subscription.add(source.subscribe(subject)); + return subscription; }; - return StaticIterator; + return MulticastOperator; }()); -var StaticArrayIterator = /*@__PURE__*/ (function () { - function StaticArrayIterator(array) { - this.array = array; - this.index = 0; - this.length = 0; - this.length = array.length; + +//# sourceMappingURL=multicast.js.map + + +/***/ }), +/* 292 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onErrorResumeNext", function() { return onErrorResumeNext; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onErrorResumeNextStatic", function() { return onErrorResumeNextStatic; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _observable_from__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(214); +/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(149); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(200); +/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(202); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_observable_from,_util_isArray,_OuterSubscriber,_InnerSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ + + + + + + +function onErrorResumeNext() { + var nextSources = []; + for (var _i = 0; _i < arguments.length; _i++) { + nextSources[_i] = arguments[_i]; } - StaticArrayIterator.prototype[_internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_6__["iterator"]] = function () { - return this; - }; - StaticArrayIterator.prototype.next = function (value) { - var i = this.index++; - var array = this.array; - return i < this.length ? { value: array[i], done: false } : { value: null, done: true }; - }; - StaticArrayIterator.prototype.hasValue = function () { - return this.array.length > this.index; - }; - StaticArrayIterator.prototype.hasCompleted = function () { - return this.array.length === this.index; + if (nextSources.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_2__["isArray"])(nextSources[0])) { + nextSources = nextSources[0]; + } + return function (source) { return source.lift(new OnErrorResumeNextOperator(nextSources)); }; +} +function onErrorResumeNextStatic() { + var nextSources = []; + for (var _i = 0; _i < arguments.length; _i++) { + nextSources[_i] = arguments[_i]; + } + var source = null; + if (nextSources.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_2__["isArray"])(nextSources[0])) { + nextSources = nextSources[0]; + } + source = nextSources.shift(); + return Object(_observable_from__WEBPACK_IMPORTED_MODULE_1__["from"])(source, null).lift(new OnErrorResumeNextOperator(nextSources)); +} +var OnErrorResumeNextOperator = /*@__PURE__*/ (function () { + function OnErrorResumeNextOperator(nextSources) { + this.nextSources = nextSources; + } + OnErrorResumeNextOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new OnErrorResumeNextSubscriber(subscriber, this.nextSources)); }; - return StaticArrayIterator; + return OnErrorResumeNextOperator; }()); -var ZipBufferIterator = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ZipBufferIterator, _super); - function ZipBufferIterator(destination, parent, observable) { +var OnErrorResumeNextSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](OnErrorResumeNextSubscriber, _super); + function OnErrorResumeNextSubscriber(destination, nextSources) { var _this = _super.call(this, destination) || this; - _this.parent = parent; - _this.observable = observable; - _this.stillUnsubscribed = true; - _this.buffer = []; - _this.isComplete = false; + _this.destination = destination; + _this.nextSources = nextSources; return _this; } - ZipBufferIterator.prototype[_internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_6__["iterator"]] = function () { - return this; + OnErrorResumeNextSubscriber.prototype.notifyError = function (error, innerSub) { + this.subscribeToNextSource(); }; - ZipBufferIterator.prototype.next = function () { - var buffer = this.buffer; - if (buffer.length === 0 && this.isComplete) { - return { value: null, done: true }; - } - else { - return { value: buffer.shift(), done: false }; - } + OnErrorResumeNextSubscriber.prototype.notifyComplete = function (innerSub) { + this.subscribeToNextSource(); }; - ZipBufferIterator.prototype.hasValue = function () { - return this.buffer.length > 0; + OnErrorResumeNextSubscriber.prototype._error = function (err) { + this.subscribeToNextSource(); + this.unsubscribe(); }; - ZipBufferIterator.prototype.hasCompleted = function () { - return this.buffer.length === 0 && this.isComplete; + OnErrorResumeNextSubscriber.prototype._complete = function () { + this.subscribeToNextSource(); + this.unsubscribe(); }; - ZipBufferIterator.prototype.notifyComplete = function () { - if (this.buffer.length > 0) { - this.isComplete = true; - this.parent.notifyInactive(); + OnErrorResumeNextSubscriber.prototype.subscribeToNextSource = function () { + var next = this.nextSources.shift(); + if (!!next) { + var innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_4__["InnerSubscriber"](this, undefined, undefined); + var destination = this.destination; + destination.add(innerSubscriber); + Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_5__["subscribeToResult"])(this, next, undefined, undefined, innerSubscriber); } else { this.destination.complete(); } }; - ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.buffer.push(innerValue); - this.parent.checkIterators(); - }; - ZipBufferIterator.prototype.subscribe = function (value, index) { - return Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_5__["subscribeToResult"])(this, this.observable, this, index); - }; - return ZipBufferIterator; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_4__["OuterSubscriber"])); -//# sourceMappingURL=zip.js.map + return OnErrorResumeNextSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__["OuterSubscriber"])); +//# sourceMappingURL=onErrorResumeNext.js.map /***/ }), -/* 270 */ +/* 293 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony import */ var _internal_operators_audit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(271); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "audit", function() { return _internal_operators_audit__WEBPACK_IMPORTED_MODULE_0__["audit"]; }); - -/* harmony import */ var _internal_operators_auditTime__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(272); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "auditTime", function() { return _internal_operators_auditTime__WEBPACK_IMPORTED_MODULE_1__["auditTime"]; }); - -/* harmony import */ var _internal_operators_buffer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(273); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "buffer", function() { return _internal_operators_buffer__WEBPACK_IMPORTED_MODULE_2__["buffer"]; }); - -/* harmony import */ var _internal_operators_bufferCount__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(274); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bufferCount", function() { return _internal_operators_bufferCount__WEBPACK_IMPORTED_MODULE_3__["bufferCount"]; }); - -/* harmony import */ var _internal_operators_bufferTime__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(275); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bufferTime", function() { return _internal_operators_bufferTime__WEBPACK_IMPORTED_MODULE_4__["bufferTime"]; }); - -/* harmony import */ var _internal_operators_bufferToggle__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(276); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bufferToggle", function() { return _internal_operators_bufferToggle__WEBPACK_IMPORTED_MODULE_5__["bufferToggle"]; }); - -/* harmony import */ var _internal_operators_bufferWhen__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(277); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bufferWhen", function() { return _internal_operators_bufferWhen__WEBPACK_IMPORTED_MODULE_6__["bufferWhen"]; }); - -/* harmony import */ var _internal_operators_catchError__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(278); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "catchError", function() { return _internal_operators_catchError__WEBPACK_IMPORTED_MODULE_7__["catchError"]; }); - -/* harmony import */ var _internal_operators_combineAll__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(279); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "combineAll", function() { return _internal_operators_combineAll__WEBPACK_IMPORTED_MODULE_8__["combineAll"]; }); - -/* harmony import */ var _internal_operators_combineLatest__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(280); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "combineLatest", function() { return _internal_operators_combineLatest__WEBPACK_IMPORTED_MODULE_9__["combineLatest"]; }); - -/* harmony import */ var _internal_operators_concat__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(281); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "concat", function() { return _internal_operators_concat__WEBPACK_IMPORTED_MODULE_10__["concat"]; }); - -/* harmony import */ var _internal_operators_concatAll__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(240); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "concatAll", function() { return _internal_operators_concatAll__WEBPACK_IMPORTED_MODULE_11__["concatAll"]; }); - -/* harmony import */ var _internal_operators_concatMap__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(282); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "concatMap", function() { return _internal_operators_concatMap__WEBPACK_IMPORTED_MODULE_12__["concatMap"]; }); - -/* harmony import */ var _internal_operators_concatMapTo__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(283); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "concatMapTo", function() { return _internal_operators_concatMapTo__WEBPACK_IMPORTED_MODULE_13__["concatMapTo"]; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pairwise", function() { return pairwise; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -/* harmony import */ var _internal_operators_count__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(284); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "count", function() { return _internal_operators_count__WEBPACK_IMPORTED_MODULE_14__["count"]; }); -/* harmony import */ var _internal_operators_debounce__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(285); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "debounce", function() { return _internal_operators_debounce__WEBPACK_IMPORTED_MODULE_15__["debounce"]; }); +function pairwise() { + return function (source) { return source.lift(new PairwiseOperator()); }; +} +var PairwiseOperator = /*@__PURE__*/ (function () { + function PairwiseOperator() { + } + PairwiseOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new PairwiseSubscriber(subscriber)); + }; + return PairwiseOperator; +}()); +var PairwiseSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PairwiseSubscriber, _super); + function PairwiseSubscriber(destination) { + var _this = _super.call(this, destination) || this; + _this.hasPrev = false; + return _this; + } + PairwiseSubscriber.prototype._next = function (value) { + var pair; + if (this.hasPrev) { + pair = [this.prev, value]; + } + else { + this.hasPrev = true; + } + this.prev = value; + if (pair) { + this.destination.next(pair); + } + }; + return PairwiseSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=pairwise.js.map -/* harmony import */ var _internal_operators_debounceTime__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(286); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "debounceTime", function() { return _internal_operators_debounceTime__WEBPACK_IMPORTED_MODULE_16__["debounceTime"]; }); -/* harmony import */ var _internal_operators_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(287); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "defaultIfEmpty", function() { return _internal_operators_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_17__["defaultIfEmpty"]; }); +/***/ }), +/* 294 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -/* harmony import */ var _internal_operators_delay__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(288); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "delay", function() { return _internal_operators_delay__WEBPACK_IMPORTED_MODULE_18__["delay"]; }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "partition", function() { return partition; }); +/* harmony import */ var _util_not__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(234); +/* harmony import */ var _filter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(235); +/** PURE_IMPORTS_START _util_not,_filter PURE_IMPORTS_END */ -/* harmony import */ var _internal_operators_delayWhen__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(290); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "delayWhen", function() { return _internal_operators_delayWhen__WEBPACK_IMPORTED_MODULE_19__["delayWhen"]; }); -/* harmony import */ var _internal_operators_dematerialize__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(291); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "dematerialize", function() { return _internal_operators_dematerialize__WEBPACK_IMPORTED_MODULE_20__["dematerialize"]; }); +function partition(predicate, thisArg) { + return function (source) { + return [ + Object(_filter__WEBPACK_IMPORTED_MODULE_1__["filter"])(predicate, thisArg)(source), + Object(_filter__WEBPACK_IMPORTED_MODULE_1__["filter"])(Object(_util_not__WEBPACK_IMPORTED_MODULE_0__["not"])(predicate, thisArg))(source) + ]; + }; +} +//# sourceMappingURL=partition.js.map -/* harmony import */ var _internal_operators_distinct__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(292); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "distinct", function() { return _internal_operators_distinct__WEBPACK_IMPORTED_MODULE_21__["distinct"]; }); -/* harmony import */ var _internal_operators_distinctUntilChanged__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(293); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "distinctUntilChanged", function() { return _internal_operators_distinctUntilChanged__WEBPACK_IMPORTED_MODULE_22__["distinctUntilChanged"]; }); +/***/ }), +/* 295 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -/* harmony import */ var _internal_operators_distinctUntilKeyChanged__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(294); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "distinctUntilKeyChanged", function() { return _internal_operators_distinctUntilKeyChanged__WEBPACK_IMPORTED_MODULE_23__["distinctUntilKeyChanged"]; }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pluck", function() { return pluck; }); +/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(197); +/** PURE_IMPORTS_START _map PURE_IMPORTS_END */ -/* harmony import */ var _internal_operators_elementAt__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(295); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "elementAt", function() { return _internal_operators_elementAt__WEBPACK_IMPORTED_MODULE_24__["elementAt"]; }); +function pluck() { + var properties = []; + for (var _i = 0; _i < arguments.length; _i++) { + properties[_i] = arguments[_i]; + } + var length = properties.length; + if (length === 0) { + throw new Error('list of properties cannot be empty.'); + } + return function (source) { return Object(_map__WEBPACK_IMPORTED_MODULE_0__["map"])(plucker(properties, length))(source); }; +} +function plucker(props, length) { + var mapper = function (x) { + var currentProp = x; + for (var i = 0; i < length; i++) { + var p = currentProp[props[i]]; + if (typeof p !== 'undefined') { + currentProp = p; + } + else { + return undefined; + } + } + return currentProp; + }; + return mapper; +} +//# sourceMappingURL=pluck.js.map -/* harmony import */ var _internal_operators_endWith__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(298); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "endWith", function() { return _internal_operators_endWith__WEBPACK_IMPORTED_MODULE_25__["endWith"]; }); -/* harmony import */ var _internal_operators_every__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(299); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "every", function() { return _internal_operators_every__WEBPACK_IMPORTED_MODULE_26__["every"]; }); +/***/ }), +/* 296 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -/* harmony import */ var _internal_operators_exhaust__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(300); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "exhaust", function() { return _internal_operators_exhaust__WEBPACK_IMPORTED_MODULE_27__["exhaust"]; }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "publish", function() { return publish; }); +/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(158); +/* harmony import */ var _multicast__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(291); +/** PURE_IMPORTS_START _Subject,_multicast PURE_IMPORTS_END */ -/* harmony import */ var _internal_operators_exhaustMap__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(301); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "exhaustMap", function() { return _internal_operators_exhaustMap__WEBPACK_IMPORTED_MODULE_28__["exhaustMap"]; }); -/* harmony import */ var _internal_operators_expand__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(302); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "expand", function() { return _internal_operators_expand__WEBPACK_IMPORTED_MODULE_29__["expand"]; }); +function publish(selector) { + return selector ? + Object(_multicast__WEBPACK_IMPORTED_MODULE_1__["multicast"])(function () { return new _Subject__WEBPACK_IMPORTED_MODULE_0__["Subject"](); }, selector) : + Object(_multicast__WEBPACK_IMPORTED_MODULE_1__["multicast"])(new _Subject__WEBPACK_IMPORTED_MODULE_0__["Subject"]()); +} +//# sourceMappingURL=publish.js.map -/* harmony import */ var _internal_operators_filter__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(264); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "filter", function() { return _internal_operators_filter__WEBPACK_IMPORTED_MODULE_30__["filter"]; }); -/* harmony import */ var _internal_operators_finalize__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(303); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "finalize", function() { return _internal_operators_finalize__WEBPACK_IMPORTED_MODULE_31__["finalize"]; }); +/***/ }), +/* 297 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -/* harmony import */ var _internal_operators_find__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(304); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "find", function() { return _internal_operators_find__WEBPACK_IMPORTED_MODULE_32__["find"]; }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "publishBehavior", function() { return publishBehavior; }); +/* harmony import */ var _BehaviorSubject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(163); +/* harmony import */ var _multicast__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(291); +/** PURE_IMPORTS_START _BehaviorSubject,_multicast PURE_IMPORTS_END */ -/* harmony import */ var _internal_operators_findIndex__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(305); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "findIndex", function() { return _internal_operators_findIndex__WEBPACK_IMPORTED_MODULE_33__["findIndex"]; }); -/* harmony import */ var _internal_operators_first__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(306); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "first", function() { return _internal_operators_first__WEBPACK_IMPORTED_MODULE_34__["first"]; }); +function publishBehavior(value) { + return function (source) { return Object(_multicast__WEBPACK_IMPORTED_MODULE_1__["multicast"])(new _BehaviorSubject__WEBPACK_IMPORTED_MODULE_0__["BehaviorSubject"](value))(source); }; +} +//# sourceMappingURL=publishBehavior.js.map -/* harmony import */ var _internal_operators_groupBy__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(191); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "groupBy", function() { return _internal_operators_groupBy__WEBPACK_IMPORTED_MODULE_35__["groupBy"]; }); -/* harmony import */ var _internal_operators_ignoreElements__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(307); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ignoreElements", function() { return _internal_operators_ignoreElements__WEBPACK_IMPORTED_MODULE_36__["ignoreElements"]; }); +/***/ }), +/* 298 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -/* harmony import */ var _internal_operators_isEmpty__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(308); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isEmpty", function() { return _internal_operators_isEmpty__WEBPACK_IMPORTED_MODULE_37__["isEmpty"]; }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "publishLast", function() { return publishLast; }); +/* harmony import */ var _AsyncSubject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(181); +/* harmony import */ var _multicast__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(291); +/** PURE_IMPORTS_START _AsyncSubject,_multicast PURE_IMPORTS_END */ -/* harmony import */ var _internal_operators_last__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(309); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "last", function() { return _internal_operators_last__WEBPACK_IMPORTED_MODULE_38__["last"]; }); -/* harmony import */ var _internal_operators_map__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(226); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "map", function() { return _internal_operators_map__WEBPACK_IMPORTED_MODULE_39__["map"]; }); +function publishLast() { + return function (source) { return Object(_multicast__WEBPACK_IMPORTED_MODULE_1__["multicast"])(new _AsyncSubject__WEBPACK_IMPORTED_MODULE_0__["AsyncSubject"]())(source); }; +} +//# sourceMappingURL=publishLast.js.map -/* harmony import */ var _internal_operators_mapTo__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(311); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mapTo", function() { return _internal_operators_mapTo__WEBPACK_IMPORTED_MODULE_40__["mapTo"]; }); -/* harmony import */ var _internal_operators_materialize__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(312); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "materialize", function() { return _internal_operators_materialize__WEBPACK_IMPORTED_MODULE_41__["materialize"]; }); +/***/ }), +/* 299 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -/* harmony import */ var _internal_operators_max__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(313); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "max", function() { return _internal_operators_max__WEBPACK_IMPORTED_MODULE_42__["max"]; }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "publishReplay", function() { return publishReplay; }); +/* harmony import */ var _ReplaySubject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(164); +/* harmony import */ var _multicast__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(291); +/** PURE_IMPORTS_START _ReplaySubject,_multicast PURE_IMPORTS_END */ -/* harmony import */ var _internal_operators_merge__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(316); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "merge", function() { return _internal_operators_merge__WEBPACK_IMPORTED_MODULE_43__["merge"]; }); -/* harmony import */ var _internal_operators_mergeAll__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(241); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mergeAll", function() { return _internal_operators_mergeAll__WEBPACK_IMPORTED_MODULE_44__["mergeAll"]; }); +function publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler) { + if (selectorOrScheduler && typeof selectorOrScheduler !== 'function') { + scheduler = selectorOrScheduler; + } + var selector = typeof selectorOrScheduler === 'function' ? selectorOrScheduler : undefined; + var subject = new _ReplaySubject__WEBPACK_IMPORTED_MODULE_0__["ReplaySubject"](bufferSize, windowTime, scheduler); + return function (source) { return Object(_multicast__WEBPACK_IMPORTED_MODULE_1__["multicast"])(function () { return subject; }, selector)(source); }; +} +//# sourceMappingURL=publishReplay.js.map -/* harmony import */ var _internal_operators_mergeMap__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(242); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mergeMap", function() { return _internal_operators_mergeMap__WEBPACK_IMPORTED_MODULE_45__["mergeMap"]; }); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "flatMap", function() { return _internal_operators_mergeMap__WEBPACK_IMPORTED_MODULE_45__["mergeMap"]; }); +/***/ }), +/* 300 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -/* harmony import */ var _internal_operators_mergeMapTo__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(317); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mergeMapTo", function() { return _internal_operators_mergeMapTo__WEBPACK_IMPORTED_MODULE_46__["mergeMapTo"]; }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "race", function() { return race; }); +/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); +/* harmony import */ var _observable_race__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(236); +/** PURE_IMPORTS_START _util_isArray,_observable_race PURE_IMPORTS_END */ -/* harmony import */ var _internal_operators_mergeScan__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(318); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mergeScan", function() { return _internal_operators_mergeScan__WEBPACK_IMPORTED_MODULE_47__["mergeScan"]; }); -/* harmony import */ var _internal_operators_min__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(319); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "min", function() { return _internal_operators_min__WEBPACK_IMPORTED_MODULE_48__["min"]; }); +function race() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; + } + return function raceOperatorFunction(source) { + if (observables.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_0__["isArray"])(observables[0])) { + observables = observables[0]; + } + return source.lift.call(_observable_race__WEBPACK_IMPORTED_MODULE_1__["race"].apply(void 0, [source].concat(observables))); + }; +} +//# sourceMappingURL=race.js.map -/* harmony import */ var _internal_operators_multicast__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(320); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "multicast", function() { return _internal_operators_multicast__WEBPACK_IMPORTED_MODULE_49__["multicast"]; }); -/* harmony import */ var _internal_operators_observeOn__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(201); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "observeOn", function() { return _internal_operators_observeOn__WEBPACK_IMPORTED_MODULE_50__["observeOn"]; }); +/***/ }), +/* 301 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -/* harmony import */ var _internal_operators_onErrorResumeNext__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(321); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "onErrorResumeNext", function() { return _internal_operators_onErrorResumeNext__WEBPACK_IMPORTED_MODULE_51__["onErrorResumeNext"]; }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "repeat", function() { return repeat; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/* harmony import */ var _observable_empty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(174); +/** PURE_IMPORTS_START tslib,_Subscriber,_observable_empty PURE_IMPORTS_END */ -/* harmony import */ var _internal_operators_pairwise__WEBPACK_IMPORTED_MODULE_52__ = __webpack_require__(322); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "pairwise", function() { return _internal_operators_pairwise__WEBPACK_IMPORTED_MODULE_52__["pairwise"]; }); -/* harmony import */ var _internal_operators_partition__WEBPACK_IMPORTED_MODULE_53__ = __webpack_require__(323); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "partition", function() { return _internal_operators_partition__WEBPACK_IMPORTED_MODULE_53__["partition"]; }); -/* harmony import */ var _internal_operators_pluck__WEBPACK_IMPORTED_MODULE_54__ = __webpack_require__(324); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "pluck", function() { return _internal_operators_pluck__WEBPACK_IMPORTED_MODULE_54__["pluck"]; }); - -/* harmony import */ var _internal_operators_publish__WEBPACK_IMPORTED_MODULE_55__ = __webpack_require__(325); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "publish", function() { return _internal_operators_publish__WEBPACK_IMPORTED_MODULE_55__["publish"]; }); - -/* harmony import */ var _internal_operators_publishBehavior__WEBPACK_IMPORTED_MODULE_56__ = __webpack_require__(326); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "publishBehavior", function() { return _internal_operators_publishBehavior__WEBPACK_IMPORTED_MODULE_56__["publishBehavior"]; }); - -/* harmony import */ var _internal_operators_publishLast__WEBPACK_IMPORTED_MODULE_57__ = __webpack_require__(327); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "publishLast", function() { return _internal_operators_publishLast__WEBPACK_IMPORTED_MODULE_57__["publishLast"]; }); - -/* harmony import */ var _internal_operators_publishReplay__WEBPACK_IMPORTED_MODULE_58__ = __webpack_require__(328); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "publishReplay", function() { return _internal_operators_publishReplay__WEBPACK_IMPORTED_MODULE_58__["publishReplay"]; }); - -/* harmony import */ var _internal_operators_race__WEBPACK_IMPORTED_MODULE_59__ = __webpack_require__(329); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "race", function() { return _internal_operators_race__WEBPACK_IMPORTED_MODULE_59__["race"]; }); - -/* harmony import */ var _internal_operators_reduce__WEBPACK_IMPORTED_MODULE_60__ = __webpack_require__(314); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "reduce", function() { return _internal_operators_reduce__WEBPACK_IMPORTED_MODULE_60__["reduce"]; }); - -/* harmony import */ var _internal_operators_repeat__WEBPACK_IMPORTED_MODULE_61__ = __webpack_require__(330); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "repeat", function() { return _internal_operators_repeat__WEBPACK_IMPORTED_MODULE_61__["repeat"]; }); - -/* harmony import */ var _internal_operators_repeatWhen__WEBPACK_IMPORTED_MODULE_62__ = __webpack_require__(331); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "repeatWhen", function() { return _internal_operators_repeatWhen__WEBPACK_IMPORTED_MODULE_62__["repeatWhen"]; }); - -/* harmony import */ var _internal_operators_retry__WEBPACK_IMPORTED_MODULE_63__ = __webpack_require__(332); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "retry", function() { return _internal_operators_retry__WEBPACK_IMPORTED_MODULE_63__["retry"]; }); - -/* harmony import */ var _internal_operators_retryWhen__WEBPACK_IMPORTED_MODULE_64__ = __webpack_require__(333); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "retryWhen", function() { return _internal_operators_retryWhen__WEBPACK_IMPORTED_MODULE_64__["retryWhen"]; }); - -/* harmony import */ var _internal_operators_refCount__WEBPACK_IMPORTED_MODULE_65__ = __webpack_require__(190); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "refCount", function() { return _internal_operators_refCount__WEBPACK_IMPORTED_MODULE_65__["refCount"]; }); - -/* harmony import */ var _internal_operators_sample__WEBPACK_IMPORTED_MODULE_66__ = __webpack_require__(334); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sample", function() { return _internal_operators_sample__WEBPACK_IMPORTED_MODULE_66__["sample"]; }); - -/* harmony import */ var _internal_operators_sampleTime__WEBPACK_IMPORTED_MODULE_67__ = __webpack_require__(335); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sampleTime", function() { return _internal_operators_sampleTime__WEBPACK_IMPORTED_MODULE_67__["sampleTime"]; }); - -/* harmony import */ var _internal_operators_scan__WEBPACK_IMPORTED_MODULE_68__ = __webpack_require__(315); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "scan", function() { return _internal_operators_scan__WEBPACK_IMPORTED_MODULE_68__["scan"]; }); - -/* harmony import */ var _internal_operators_sequenceEqual__WEBPACK_IMPORTED_MODULE_69__ = __webpack_require__(336); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sequenceEqual", function() { return _internal_operators_sequenceEqual__WEBPACK_IMPORTED_MODULE_69__["sequenceEqual"]; }); - -/* harmony import */ var _internal_operators_share__WEBPACK_IMPORTED_MODULE_70__ = __webpack_require__(337); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "share", function() { return _internal_operators_share__WEBPACK_IMPORTED_MODULE_70__["share"]; }); - -/* harmony import */ var _internal_operators_shareReplay__WEBPACK_IMPORTED_MODULE_71__ = __webpack_require__(338); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "shareReplay", function() { return _internal_operators_shareReplay__WEBPACK_IMPORTED_MODULE_71__["shareReplay"]; }); - -/* harmony import */ var _internal_operators_single__WEBPACK_IMPORTED_MODULE_72__ = __webpack_require__(339); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "single", function() { return _internal_operators_single__WEBPACK_IMPORTED_MODULE_72__["single"]; }); - -/* harmony import */ var _internal_operators_skip__WEBPACK_IMPORTED_MODULE_73__ = __webpack_require__(340); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "skip", function() { return _internal_operators_skip__WEBPACK_IMPORTED_MODULE_73__["skip"]; }); - -/* harmony import */ var _internal_operators_skipLast__WEBPACK_IMPORTED_MODULE_74__ = __webpack_require__(341); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "skipLast", function() { return _internal_operators_skipLast__WEBPACK_IMPORTED_MODULE_74__["skipLast"]; }); - -/* harmony import */ var _internal_operators_skipUntil__WEBPACK_IMPORTED_MODULE_75__ = __webpack_require__(342); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "skipUntil", function() { return _internal_operators_skipUntil__WEBPACK_IMPORTED_MODULE_75__["skipUntil"]; }); - -/* harmony import */ var _internal_operators_skipWhile__WEBPACK_IMPORTED_MODULE_76__ = __webpack_require__(343); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "skipWhile", function() { return _internal_operators_skipWhile__WEBPACK_IMPORTED_MODULE_76__["skipWhile"]; }); - -/* harmony import */ var _internal_operators_startWith__WEBPACK_IMPORTED_MODULE_77__ = __webpack_require__(344); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "startWith", function() { return _internal_operators_startWith__WEBPACK_IMPORTED_MODULE_77__["startWith"]; }); - -/* harmony import */ var _internal_operators_subscribeOn__WEBPACK_IMPORTED_MODULE_78__ = __webpack_require__(345); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "subscribeOn", function() { return _internal_operators_subscribeOn__WEBPACK_IMPORTED_MODULE_78__["subscribeOn"]; }); - -/* harmony import */ var _internal_operators_switchAll__WEBPACK_IMPORTED_MODULE_79__ = __webpack_require__(347); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "switchAll", function() { return _internal_operators_switchAll__WEBPACK_IMPORTED_MODULE_79__["switchAll"]; }); - -/* harmony import */ var _internal_operators_switchMap__WEBPACK_IMPORTED_MODULE_80__ = __webpack_require__(348); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "switchMap", function() { return _internal_operators_switchMap__WEBPACK_IMPORTED_MODULE_80__["switchMap"]; }); - -/* harmony import */ var _internal_operators_switchMapTo__WEBPACK_IMPORTED_MODULE_81__ = __webpack_require__(349); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "switchMapTo", function() { return _internal_operators_switchMapTo__WEBPACK_IMPORTED_MODULE_81__["switchMapTo"]; }); - -/* harmony import */ var _internal_operators_take__WEBPACK_IMPORTED_MODULE_82__ = __webpack_require__(297); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "take", function() { return _internal_operators_take__WEBPACK_IMPORTED_MODULE_82__["take"]; }); - -/* harmony import */ var _internal_operators_takeLast__WEBPACK_IMPORTED_MODULE_83__ = __webpack_require__(310); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "takeLast", function() { return _internal_operators_takeLast__WEBPACK_IMPORTED_MODULE_83__["takeLast"]; }); - -/* harmony import */ var _internal_operators_takeUntil__WEBPACK_IMPORTED_MODULE_84__ = __webpack_require__(350); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "takeUntil", function() { return _internal_operators_takeUntil__WEBPACK_IMPORTED_MODULE_84__["takeUntil"]; }); - -/* harmony import */ var _internal_operators_takeWhile__WEBPACK_IMPORTED_MODULE_85__ = __webpack_require__(351); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "takeWhile", function() { return _internal_operators_takeWhile__WEBPACK_IMPORTED_MODULE_85__["takeWhile"]; }); - -/* harmony import */ var _internal_operators_tap__WEBPACK_IMPORTED_MODULE_86__ = __webpack_require__(352); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "tap", function() { return _internal_operators_tap__WEBPACK_IMPORTED_MODULE_86__["tap"]; }); - -/* harmony import */ var _internal_operators_throttle__WEBPACK_IMPORTED_MODULE_87__ = __webpack_require__(353); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "throttle", function() { return _internal_operators_throttle__WEBPACK_IMPORTED_MODULE_87__["throttle"]; }); - -/* harmony import */ var _internal_operators_throttleTime__WEBPACK_IMPORTED_MODULE_88__ = __webpack_require__(354); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "throttleTime", function() { return _internal_operators_throttleTime__WEBPACK_IMPORTED_MODULE_88__["throttleTime"]; }); - -/* harmony import */ var _internal_operators_throwIfEmpty__WEBPACK_IMPORTED_MODULE_89__ = __webpack_require__(296); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "throwIfEmpty", function() { return _internal_operators_throwIfEmpty__WEBPACK_IMPORTED_MODULE_89__["throwIfEmpty"]; }); - -/* harmony import */ var _internal_operators_timeInterval__WEBPACK_IMPORTED_MODULE_90__ = __webpack_require__(355); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "timeInterval", function() { return _internal_operators_timeInterval__WEBPACK_IMPORTED_MODULE_90__["timeInterval"]; }); - -/* harmony import */ var _internal_operators_timeout__WEBPACK_IMPORTED_MODULE_91__ = __webpack_require__(356); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "timeout", function() { return _internal_operators_timeout__WEBPACK_IMPORTED_MODULE_91__["timeout"]; }); - -/* harmony import */ var _internal_operators_timeoutWith__WEBPACK_IMPORTED_MODULE_92__ = __webpack_require__(357); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "timeoutWith", function() { return _internal_operators_timeoutWith__WEBPACK_IMPORTED_MODULE_92__["timeoutWith"]; }); - -/* harmony import */ var _internal_operators_timestamp__WEBPACK_IMPORTED_MODULE_93__ = __webpack_require__(358); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "timestamp", function() { return _internal_operators_timestamp__WEBPACK_IMPORTED_MODULE_93__["timestamp"]; }); - -/* harmony import */ var _internal_operators_toArray__WEBPACK_IMPORTED_MODULE_94__ = __webpack_require__(359); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toArray", function() { return _internal_operators_toArray__WEBPACK_IMPORTED_MODULE_94__["toArray"]; }); - -/* harmony import */ var _internal_operators_window__WEBPACK_IMPORTED_MODULE_95__ = __webpack_require__(360); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "window", function() { return _internal_operators_window__WEBPACK_IMPORTED_MODULE_95__["window"]; }); - -/* harmony import */ var _internal_operators_windowCount__WEBPACK_IMPORTED_MODULE_96__ = __webpack_require__(361); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "windowCount", function() { return _internal_operators_windowCount__WEBPACK_IMPORTED_MODULE_96__["windowCount"]; }); - -/* harmony import */ var _internal_operators_windowTime__WEBPACK_IMPORTED_MODULE_97__ = __webpack_require__(362); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "windowTime", function() { return _internal_operators_windowTime__WEBPACK_IMPORTED_MODULE_97__["windowTime"]; }); - -/* harmony import */ var _internal_operators_windowToggle__WEBPACK_IMPORTED_MODULE_98__ = __webpack_require__(363); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "windowToggle", function() { return _internal_operators_windowToggle__WEBPACK_IMPORTED_MODULE_98__["windowToggle"]; }); - -/* harmony import */ var _internal_operators_windowWhen__WEBPACK_IMPORTED_MODULE_99__ = __webpack_require__(364); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "windowWhen", function() { return _internal_operators_windowWhen__WEBPACK_IMPORTED_MODULE_99__["windowWhen"]; }); - -/* harmony import */ var _internal_operators_withLatestFrom__WEBPACK_IMPORTED_MODULE_100__ = __webpack_require__(365); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "withLatestFrom", function() { return _internal_operators_withLatestFrom__WEBPACK_IMPORTED_MODULE_100__["withLatestFrom"]; }); - -/* harmony import */ var _internal_operators_zip__WEBPACK_IMPORTED_MODULE_101__ = __webpack_require__(366); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "zip", function() { return _internal_operators_zip__WEBPACK_IMPORTED_MODULE_101__["zip"]; }); - -/* harmony import */ var _internal_operators_zipAll__WEBPACK_IMPORTED_MODULE_102__ = __webpack_require__(367); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "zipAll", function() { return _internal_operators_zipAll__WEBPACK_IMPORTED_MODULE_102__["zipAll"]; }); - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//# sourceMappingURL=index.js.map +function repeat(count) { + if (count === void 0) { + count = -1; + } + return function (source) { + if (count === 0) { + return Object(_observable_empty__WEBPACK_IMPORTED_MODULE_2__["empty"])(); + } + else if (count < 0) { + return source.lift(new RepeatOperator(-1, source)); + } + else { + return source.lift(new RepeatOperator(count - 1, source)); + } + }; +} +var RepeatOperator = /*@__PURE__*/ (function () { + function RepeatOperator(count, source) { + this.count = count; + this.source = source; + } + RepeatOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new RepeatSubscriber(subscriber, this.count, this.source)); + }; + return RepeatOperator; +}()); +var RepeatSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RepeatSubscriber, _super); + function RepeatSubscriber(destination, count, source) { + var _this = _super.call(this, destination) || this; + _this.count = count; + _this.source = source; + return _this; + } + RepeatSubscriber.prototype.complete = function () { + if (!this.isStopped) { + var _a = this, source = _a.source, count = _a.count; + if (count === 0) { + return _super.prototype.complete.call(this); + } + else if (count > -1) { + this.count = count - 1; + } + source.subscribe(this._unsubscribeAndRecycle()); + } + }; + return RepeatSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=repeat.js.map /***/ }), -/* 271 */ +/* 302 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "audit", function() { return audit; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "repeatWhen", function() { return repeatWhen; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(158); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_Subject,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function audit(durationSelector) { - return function auditOperatorFunction(source) { - return source.lift(new AuditOperator(durationSelector)); - }; + +function repeatWhen(notifier) { + return function (source) { return source.lift(new RepeatWhenOperator(notifier)); }; } -var AuditOperator = /*@__PURE__*/ (function () { - function AuditOperator(durationSelector) { - this.durationSelector = durationSelector; +var RepeatWhenOperator = /*@__PURE__*/ (function () { + function RepeatWhenOperator(notifier) { + this.notifier = notifier; } - AuditOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new AuditSubscriber(subscriber, this.durationSelector)); + RepeatWhenOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new RepeatWhenSubscriber(subscriber, this.notifier, source)); }; - return AuditOperator; + return RepeatWhenOperator; }()); -var AuditSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AuditSubscriber, _super); - function AuditSubscriber(destination, durationSelector) { +var RepeatWhenSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RepeatWhenSubscriber, _super); + function RepeatWhenSubscriber(destination, notifier, source) { var _this = _super.call(this, destination) || this; - _this.durationSelector = durationSelector; - _this.hasValue = false; + _this.notifier = notifier; + _this.source = source; + _this.sourceIsBeingSubscribedTo = true; return _this; } - AuditSubscriber.prototype._next = function (value) { - this.value = value; - this.hasValue = true; - if (!this.throttled) { - var duration = void 0; - try { - var durationSelector = this.durationSelector; - duration = durationSelector(value); - } - catch (err) { - return this.destination.error(err); - } - var innerSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, duration); - if (!innerSubscription || innerSubscription.closed) { - this.clearThrottle(); + RepeatWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.sourceIsBeingSubscribedTo = true; + this.source.subscribe(this); + }; + RepeatWhenSubscriber.prototype.notifyComplete = function (innerSub) { + if (this.sourceIsBeingSubscribedTo === false) { + return _super.prototype.complete.call(this); + } + }; + RepeatWhenSubscriber.prototype.complete = function () { + this.sourceIsBeingSubscribedTo = false; + if (!this.isStopped) { + if (!this.retries) { + this.subscribeToRetries(); } - else { - this.add(this.throttled = innerSubscription); + if (!this.retriesSubscription || this.retriesSubscription.closed) { + return _super.prototype.complete.call(this); } + this._unsubscribeAndRecycle(); + this.notifications.next(); } }; - AuditSubscriber.prototype.clearThrottle = function () { - var _a = this, value = _a.value, hasValue = _a.hasValue, throttled = _a.throttled; - if (throttled) { - this.remove(throttled); - this.throttled = null; - throttled.unsubscribe(); + RepeatWhenSubscriber.prototype._unsubscribe = function () { + var _a = this, notifications = _a.notifications, retriesSubscription = _a.retriesSubscription; + if (notifications) { + notifications.unsubscribe(); + this.notifications = null; } - if (hasValue) { - this.value = null; - this.hasValue = false; - this.destination.next(value); + if (retriesSubscription) { + retriesSubscription.unsubscribe(); + this.retriesSubscription = null; } + this.retries = null; }; - AuditSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex) { - this.clearThrottle(); + RepeatWhenSubscriber.prototype._unsubscribeAndRecycle = function () { + var _unsubscribe = this._unsubscribe; + this._unsubscribe = null; + _super.prototype._unsubscribeAndRecycle.call(this); + this._unsubscribe = _unsubscribe; + return this; }; - AuditSubscriber.prototype.notifyComplete = function () { - this.clearThrottle(); + RepeatWhenSubscriber.prototype.subscribeToRetries = function () { + this.notifications = new _Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"](); + var retries; + try { + var notifier = this.notifier; + retries = notifier(this.notifications); + } + catch (e) { + return _super.prototype.complete.call(this); + } + this.retries = retries; + this.retriesSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(this, retries); }; - return AuditSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); -//# sourceMappingURL=audit.js.map + return RepeatWhenSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"])); +//# sourceMappingURL=repeatWhen.js.map /***/ }), -/* 272 */ +/* 303 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "auditTime", function() { return auditTime; }); -/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(215); -/* harmony import */ var _audit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(271); -/* harmony import */ var _observable_timer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(267); -/** PURE_IMPORTS_START _scheduler_async,_audit,_observable_timer PURE_IMPORTS_END */ - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "retry", function() { return retry; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function auditTime(duration, scheduler) { - if (scheduler === void 0) { - scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_0__["async"]; +function retry(count) { + if (count === void 0) { + count = -1; } - return Object(_audit__WEBPACK_IMPORTED_MODULE_1__["audit"])(function () { return Object(_observable_timer__WEBPACK_IMPORTED_MODULE_2__["timer"])(duration, scheduler); }); -} -//# sourceMappingURL=auditTime.js.map - - -/***/ }), -/* 273 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buffer", function() { return buffer; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ - - - -function buffer(closingNotifier) { - return function bufferOperatorFunction(source) { - return source.lift(new BufferOperator(closingNotifier)); - }; + return function (source) { return source.lift(new RetryOperator(count, source)); }; } -var BufferOperator = /*@__PURE__*/ (function () { - function BufferOperator(closingNotifier) { - this.closingNotifier = closingNotifier; +var RetryOperator = /*@__PURE__*/ (function () { + function RetryOperator(count, source) { + this.count = count; + this.source = source; } - BufferOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier)); + RetryOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new RetrySubscriber(subscriber, this.count, this.source)); }; - return BufferOperator; + return RetryOperator; }()); -var BufferSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BufferSubscriber, _super); - function BufferSubscriber(destination, closingNotifier) { +var RetrySubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RetrySubscriber, _super); + function RetrySubscriber(destination, count, source) { var _this = _super.call(this, destination) || this; - _this.buffer = []; - _this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(_this, closingNotifier)); + _this.count = count; + _this.source = source; return _this; } - BufferSubscriber.prototype._next = function (value) { - this.buffer.push(value); - }; - BufferSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - var buffer = this.buffer; - this.buffer = []; - this.destination.next(buffer); + RetrySubscriber.prototype.error = function (err) { + if (!this.isStopped) { + var _a = this, source = _a.source, count = _a.count; + if (count === 0) { + return _super.prototype.error.call(this, err); + } + else if (count > -1) { + this.count = count - 1; + } + source.subscribe(this._unsubscribeAndRecycle()); + } }; - return BufferSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); -//# sourceMappingURL=buffer.js.map + return RetrySubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=retry.js.map /***/ }), -/* 274 */ +/* 304 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bufferCount", function() { return bufferCount; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "retryWhen", function() { return retryWhen; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(158); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_Subject,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function bufferCount(bufferSize, startBufferEvery) { - if (startBufferEvery === void 0) { - startBufferEvery = null; - } - return function bufferCountOperatorFunction(source) { - return source.lift(new BufferCountOperator(bufferSize, startBufferEvery)); - }; + + +function retryWhen(notifier) { + return function (source) { return source.lift(new RetryWhenOperator(notifier, source)); }; } -var BufferCountOperator = /*@__PURE__*/ (function () { - function BufferCountOperator(bufferSize, startBufferEvery) { - this.bufferSize = bufferSize; - this.startBufferEvery = startBufferEvery; - if (!startBufferEvery || bufferSize === startBufferEvery) { - this.subscriberClass = BufferCountSubscriber; - } - else { - this.subscriberClass = BufferSkipCountSubscriber; - } +var RetryWhenOperator = /*@__PURE__*/ (function () { + function RetryWhenOperator(notifier, source) { + this.notifier = notifier; + this.source = source; } - BufferCountOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery)); + RetryWhenOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new RetryWhenSubscriber(subscriber, this.notifier, this.source)); }; - return BufferCountOperator; + return RetryWhenOperator; }()); -var BufferCountSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BufferCountSubscriber, _super); - function BufferCountSubscriber(destination, bufferSize) { +var RetryWhenSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RetryWhenSubscriber, _super); + function RetryWhenSubscriber(destination, notifier, source) { var _this = _super.call(this, destination) || this; - _this.bufferSize = bufferSize; - _this.buffer = []; + _this.notifier = notifier; + _this.source = source; return _this; } - BufferCountSubscriber.prototype._next = function (value) { - var buffer = this.buffer; - buffer.push(value); - if (buffer.length == this.bufferSize) { - this.destination.next(buffer); - this.buffer = []; - } - }; - BufferCountSubscriber.prototype._complete = function () { - var buffer = this.buffer; - if (buffer.length > 0) { - this.destination.next(buffer); - } - _super.prototype._complete.call(this); - }; - return BufferCountSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -var BufferSkipCountSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BufferSkipCountSubscriber, _super); - function BufferSkipCountSubscriber(destination, bufferSize, startBufferEvery) { - var _this = _super.call(this, destination) || this; - _this.bufferSize = bufferSize; - _this.startBufferEvery = startBufferEvery; - _this.buffers = []; - _this.count = 0; - return _this; - } - BufferSkipCountSubscriber.prototype._next = function (value) { - var _a = this, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers, count = _a.count; - this.count++; - if (count % startBufferEvery === 0) { - buffers.push([]); - } - for (var i = buffers.length; i--;) { - var buffer = buffers[i]; - buffer.push(value); - if (buffer.length === bufferSize) { - buffers.splice(i, 1); - this.destination.next(buffer); + RetryWhenSubscriber.prototype.error = function (err) { + if (!this.isStopped) { + var errors = this.errors; + var retries = this.retries; + var retriesSubscription = this.retriesSubscription; + if (!retries) { + errors = new _Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"](); + try { + var notifier = this.notifier; + retries = notifier(errors); + } + catch (e) { + return _super.prototype.error.call(this, e); + } + retriesSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(this, retries); } + else { + this.errors = null; + this.retriesSubscription = null; + } + this._unsubscribeAndRecycle(); + this.errors = errors; + this.retries = retries; + this.retriesSubscription = retriesSubscription; + errors.next(err); } }; - BufferSkipCountSubscriber.prototype._complete = function () { - var _a = this, buffers = _a.buffers, destination = _a.destination; - while (buffers.length > 0) { - var buffer = buffers.shift(); - if (buffer.length > 0) { - destination.next(buffer); - } + RetryWhenSubscriber.prototype._unsubscribe = function () { + var _a = this, errors = _a.errors, retriesSubscription = _a.retriesSubscription; + if (errors) { + errors.unsubscribe(); + this.errors = null; } - _super.prototype._complete.call(this); + if (retriesSubscription) { + retriesSubscription.unsubscribe(); + this.retriesSubscription = null; + } + this.retries = null; }; - return BufferSkipCountSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=bufferCount.js.map + RetryWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + var _unsubscribe = this._unsubscribe; + this._unsubscribe = null; + this._unsubscribeAndRecycle(); + this._unsubscribe = _unsubscribe; + this.source.subscribe(this); + }; + return RetryWhenSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"])); +//# sourceMappingURL=retryWhen.js.map /***/ }), -/* 275 */ +/* 305 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bufferTime", function() { return bufferTime; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(215); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(172); -/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(205); -/** PURE_IMPORTS_START tslib,_scheduler_async,_Subscriber,_util_isScheduler PURE_IMPORTS_END */ - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sample", function() { return sample; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function bufferTime(bufferTimeSpan) { - var length = arguments.length; - var scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__["async"]; - if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_3__["isScheduler"])(arguments[arguments.length - 1])) { - scheduler = arguments[arguments.length - 1]; - length--; - } - var bufferCreationInterval = null; - if (length >= 2) { - bufferCreationInterval = arguments[1]; - } - var maxBufferSize = Number.POSITIVE_INFINITY; - if (length >= 3) { - maxBufferSize = arguments[2]; - } - return function bufferTimeOperatorFunction(source) { - return source.lift(new BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler)); - }; +function sample(notifier) { + return function (source) { return source.lift(new SampleOperator(notifier)); }; } -var BufferTimeOperator = /*@__PURE__*/ (function () { - function BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) { - this.bufferTimeSpan = bufferTimeSpan; - this.bufferCreationInterval = bufferCreationInterval; - this.maxBufferSize = maxBufferSize; - this.scheduler = scheduler; +var SampleOperator = /*@__PURE__*/ (function () { + function SampleOperator(notifier) { + this.notifier = notifier; } - BufferTimeOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new BufferTimeSubscriber(subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.maxBufferSize, this.scheduler)); + SampleOperator.prototype.call = function (subscriber, source) { + var sampleSubscriber = new SampleSubscriber(subscriber); + var subscription = source.subscribe(sampleSubscriber); + subscription.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(sampleSubscriber, this.notifier)); + return subscription; }; - return BufferTimeOperator; -}()); -var Context = /*@__PURE__*/ (function () { - function Context() { - this.buffer = []; - } - return Context; + return SampleOperator; }()); -var BufferTimeSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BufferTimeSubscriber, _super); - function BufferTimeSubscriber(destination, bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) { - var _this = _super.call(this, destination) || this; - _this.bufferTimeSpan = bufferTimeSpan; - _this.bufferCreationInterval = bufferCreationInterval; - _this.maxBufferSize = maxBufferSize; - _this.scheduler = scheduler; - _this.contexts = []; - var context = _this.openContext(); - _this.timespanOnly = bufferCreationInterval == null || bufferCreationInterval < 0; - if (_this.timespanOnly) { - var timeSpanOnlyState = { subscriber: _this, context: context, bufferTimeSpan: bufferTimeSpan }; - _this.add(context.closeAction = scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState)); - } - else { - var closeState = { subscriber: _this, context: context }; - var creationState = { bufferTimeSpan: bufferTimeSpan, bufferCreationInterval: bufferCreationInterval, subscriber: _this, scheduler: scheduler }; - _this.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, closeState)); - _this.add(scheduler.schedule(dispatchBufferCreation, bufferCreationInterval, creationState)); - } +var SampleSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SampleSubscriber, _super); + function SampleSubscriber() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.hasValue = false; return _this; } - BufferTimeSubscriber.prototype._next = function (value) { - var contexts = this.contexts; - var len = contexts.length; - var filledBufferContext; - for (var i = 0; i < len; i++) { - var context_1 = contexts[i]; - var buffer = context_1.buffer; - buffer.push(value); - if (buffer.length == this.maxBufferSize) { - filledBufferContext = context_1; - } - } - if (filledBufferContext) { - this.onBufferFull(filledBufferContext); - } - }; - BufferTimeSubscriber.prototype._error = function (err) { - this.contexts.length = 0; - _super.prototype._error.call(this, err); - }; - BufferTimeSubscriber.prototype._complete = function () { - var _a = this, contexts = _a.contexts, destination = _a.destination; - while (contexts.length > 0) { - var context_2 = contexts.shift(); - destination.next(context_2.buffer); - } - _super.prototype._complete.call(this); - }; - BufferTimeSubscriber.prototype._unsubscribe = function () { - this.contexts = null; + SampleSubscriber.prototype._next = function (value) { + this.value = value; + this.hasValue = true; }; - BufferTimeSubscriber.prototype.onBufferFull = function (context) { - this.closeContext(context); - var closeAction = context.closeAction; - closeAction.unsubscribe(); - this.remove(closeAction); - if (!this.closed && this.timespanOnly) { - context = this.openContext(); - var bufferTimeSpan = this.bufferTimeSpan; - var timeSpanOnlyState = { subscriber: this, context: context, bufferTimeSpan: bufferTimeSpan }; - this.add(context.closeAction = this.scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState)); - } + SampleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.emitValue(); }; - BufferTimeSubscriber.prototype.openContext = function () { - var context = new Context(); - this.contexts.push(context); - return context; + SampleSubscriber.prototype.notifyComplete = function () { + this.emitValue(); }; - BufferTimeSubscriber.prototype.closeContext = function (context) { - this.destination.next(context.buffer); - var contexts = this.contexts; - var spliceIndex = contexts ? contexts.indexOf(context) : -1; - if (spliceIndex >= 0) { - contexts.splice(contexts.indexOf(context), 1); + SampleSubscriber.prototype.emitValue = function () { + if (this.hasValue) { + this.hasValue = false; + this.destination.next(this.value); } }; - return BufferTimeSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_2__["Subscriber"])); -function dispatchBufferTimeSpanOnly(state) { - var subscriber = state.subscriber; - var prevContext = state.context; - if (prevContext) { - subscriber.closeContext(prevContext); - } - if (!subscriber.closed) { - state.context = subscriber.openContext(); - state.context.closeAction = this.schedule(state, state.bufferTimeSpan); - } -} -function dispatchBufferCreation(state) { - var bufferCreationInterval = state.bufferCreationInterval, bufferTimeSpan = state.bufferTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler; - var context = subscriber.openContext(); - var action = this; - if (!subscriber.closed) { - subscriber.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, { subscriber: subscriber, context: context })); - action.schedule(state, bufferCreationInterval); - } -} -function dispatchBufferClose(arg) { - var subscriber = arg.subscriber, context = arg.context; - subscriber.closeContext(context); -} -//# sourceMappingURL=bufferTime.js.map + return SampleSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); +//# sourceMappingURL=sample.js.map /***/ }), -/* 276 */ +/* 306 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bufferToggle", function() { return bufferToggle; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(177); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(230); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(229); -/** PURE_IMPORTS_START tslib,_Subscription,_util_subscribeToResult,_OuterSubscriber PURE_IMPORTS_END */ - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sampleTime", function() { return sampleTime; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(186); +/** PURE_IMPORTS_START tslib,_Subscriber,_scheduler_async PURE_IMPORTS_END */ -function bufferToggle(openings, closingSelector) { - return function bufferToggleOperatorFunction(source) { - return source.lift(new BufferToggleOperator(openings, closingSelector)); - }; +function sampleTime(period, scheduler) { + if (scheduler === void 0) { + scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_2__["async"]; + } + return function (source) { return source.lift(new SampleTimeOperator(period, scheduler)); }; } -var BufferToggleOperator = /*@__PURE__*/ (function () { - function BufferToggleOperator(openings, closingSelector) { - this.openings = openings; - this.closingSelector = closingSelector; +var SampleTimeOperator = /*@__PURE__*/ (function () { + function SampleTimeOperator(period, scheduler) { + this.period = period; + this.scheduler = scheduler; } - BufferToggleOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new BufferToggleSubscriber(subscriber, this.openings, this.closingSelector)); + SampleTimeOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new SampleTimeSubscriber(subscriber, this.period, this.scheduler)); }; - return BufferToggleOperator; + return SampleTimeOperator; }()); -var BufferToggleSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BufferToggleSubscriber, _super); - function BufferToggleSubscriber(destination, openings, closingSelector) { +var SampleTimeSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SampleTimeSubscriber, _super); + function SampleTimeSubscriber(destination, period, scheduler) { var _this = _super.call(this, destination) || this; - _this.openings = openings; - _this.closingSelector = closingSelector; - _this.contexts = []; - _this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(_this, openings)); + _this.period = period; + _this.scheduler = scheduler; + _this.hasValue = false; + _this.add(scheduler.schedule(dispatchNotification, period, { subscriber: _this, period: period })); return _this; } - BufferToggleSubscriber.prototype._next = function (value) { - var contexts = this.contexts; - var len = contexts.length; - for (var i = 0; i < len; i++) { - contexts[i].buffer.push(value); - } - }; - BufferToggleSubscriber.prototype._error = function (err) { - var contexts = this.contexts; - while (contexts.length > 0) { - var context_1 = contexts.shift(); - context_1.subscription.unsubscribe(); - context_1.buffer = null; - context_1.subscription = null; - } - this.contexts = null; - _super.prototype._error.call(this, err); - }; - BufferToggleSubscriber.prototype._complete = function () { - var contexts = this.contexts; - while (contexts.length > 0) { - var context_2 = contexts.shift(); - this.destination.next(context_2.buffer); - context_2.subscription.unsubscribe(); - context_2.buffer = null; - context_2.subscription = null; - } - this.contexts = null; - _super.prototype._complete.call(this); - }; - BufferToggleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - outerValue ? this.closeBuffer(outerValue) : this.openBuffer(innerValue); - }; - BufferToggleSubscriber.prototype.notifyComplete = function (innerSub) { - this.closeBuffer(innerSub.context); - }; - BufferToggleSubscriber.prototype.openBuffer = function (value) { - try { - var closingSelector = this.closingSelector; - var closingNotifier = closingSelector.call(this, value); - if (closingNotifier) { - this.trySubscribe(closingNotifier); - } - } - catch (err) { - this._error(err); - } - }; - BufferToggleSubscriber.prototype.closeBuffer = function (context) { - var contexts = this.contexts; - if (contexts && context) { - var buffer = context.buffer, subscription = context.subscription; - this.destination.next(buffer); - contexts.splice(contexts.indexOf(context), 1); - this.remove(subscription); - subscription.unsubscribe(); - } + SampleTimeSubscriber.prototype._next = function (value) { + this.lastValue = value; + this.hasValue = true; }; - BufferToggleSubscriber.prototype.trySubscribe = function (closingNotifier) { - var contexts = this.contexts; - var buffer = []; - var subscription = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"](); - var context = { buffer: buffer, subscription: subscription }; - contexts.push(context); - var innerSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, closingNotifier, context); - if (!innerSubscription || innerSubscription.closed) { - this.closeBuffer(context); - } - else { - innerSubscription.context = context; - this.add(innerSubscription); - subscription.add(innerSubscription); + SampleTimeSubscriber.prototype.notifyNext = function () { + if (this.hasValue) { + this.hasValue = false; + this.destination.next(this.lastValue); } }; - return BufferToggleSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__["OuterSubscriber"])); -//# sourceMappingURL=bufferToggle.js.map + return SampleTimeSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +function dispatchNotification(state) { + var subscriber = state.subscriber, period = state.period; + subscriber.notifyNext(); + this.schedule(state, period); +} +//# sourceMappingURL=sampleTime.js.map /***/ }), -/* 277 */ +/* 307 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bufferWhen", function() { return bufferWhen; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(177); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_Subscription,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ - - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sequenceEqual", function() { return sequenceEqual; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SequenceEqualOperator", function() { return SequenceEqualOperator; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SequenceEqualSubscriber", function() { return SequenceEqualSubscriber; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function bufferWhen(closingSelector) { - return function (source) { - return source.lift(new BufferWhenOperator(closingSelector)); - }; +function sequenceEqual(compareTo, comparator) { + return function (source) { return source.lift(new SequenceEqualOperator(compareTo, comparator)); }; } -var BufferWhenOperator = /*@__PURE__*/ (function () { - function BufferWhenOperator(closingSelector) { - this.closingSelector = closingSelector; +var SequenceEqualOperator = /*@__PURE__*/ (function () { + function SequenceEqualOperator(compareTo, comparator) { + this.compareTo = compareTo; + this.comparator = comparator; } - BufferWhenOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector)); + SequenceEqualOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new SequenceEqualSubscriber(subscriber, this.compareTo, this.comparator)); }; - return BufferWhenOperator; + return SequenceEqualOperator; }()); -var BufferWhenSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BufferWhenSubscriber, _super); - function BufferWhenSubscriber(destination, closingSelector) { + +var SequenceEqualSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SequenceEqualSubscriber, _super); + function SequenceEqualSubscriber(destination, compareTo, comparator) { var _this = _super.call(this, destination) || this; - _this.closingSelector = closingSelector; - _this.subscribing = false; - _this.openBuffer(); + _this.compareTo = compareTo; + _this.comparator = comparator; + _this._a = []; + _this._b = []; + _this._oneComplete = false; + _this.destination.add(compareTo.subscribe(new SequenceEqualCompareToSubscriber(destination, _this))); return _this; } - BufferWhenSubscriber.prototype._next = function (value) { - this.buffer.push(value); + SequenceEqualSubscriber.prototype._next = function (value) { + if (this._oneComplete && this._b.length === 0) { + this.emit(false); + } + else { + this._a.push(value); + this.checkValues(); + } }; - BufferWhenSubscriber.prototype._complete = function () { - var buffer = this.buffer; - if (buffer) { - this.destination.next(buffer); + SequenceEqualSubscriber.prototype._complete = function () { + if (this._oneComplete) { + this.emit(this._a.length === 0 && this._b.length === 0); } - _super.prototype._complete.call(this); + else { + this._oneComplete = true; + } + this.unsubscribe(); }; - BufferWhenSubscriber.prototype._unsubscribe = function () { - this.buffer = null; - this.subscribing = false; + SequenceEqualSubscriber.prototype.checkValues = function () { + var _c = this, _a = _c._a, _b = _c._b, comparator = _c.comparator; + while (_a.length > 0 && _b.length > 0) { + var a = _a.shift(); + var b = _b.shift(); + var areEqual = false; + try { + areEqual = comparator ? comparator(a, b) : a === b; + } + catch (e) { + this.destination.error(e); + } + if (!areEqual) { + this.emit(false); + } + } }; - BufferWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.openBuffer(); + SequenceEqualSubscriber.prototype.emit = function (value) { + var destination = this.destination; + destination.next(value); + destination.complete(); }; - BufferWhenSubscriber.prototype.notifyComplete = function () { - if (this.subscribing) { - this.complete(); + SequenceEqualSubscriber.prototype.nextB = function (value) { + if (this._oneComplete && this._a.length === 0) { + this.emit(false); } else { - this.openBuffer(); + this._b.push(value); + this.checkValues(); } }; - BufferWhenSubscriber.prototype.openBuffer = function () { - var closingSubscription = this.closingSubscription; - if (closingSubscription) { - this.remove(closingSubscription); - closingSubscription.unsubscribe(); - } - var buffer = this.buffer; - if (this.buffer) { - this.destination.next(buffer); - } - this.buffer = []; - var closingNotifier; - try { - var closingSelector = this.closingSelector; - closingNotifier = closingSelector(); + SequenceEqualSubscriber.prototype.completeB = function () { + if (this._oneComplete) { + this.emit(this._a.length === 0 && this._b.length === 0); } - catch (err) { - return this.error(err); + else { + this._oneComplete = true; } - closingSubscription = new _Subscription__WEBPACK_IMPORTED_MODULE_1__["Subscription"](); - this.closingSubscription = closingSubscription; - this.add(closingSubscription); - this.subscribing = true; - closingSubscription.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(this, closingNotifier)); - this.subscribing = false; }; - return BufferWhenSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"])); -//# sourceMappingURL=bufferWhen.js.map - - -/***/ }), -/* 278 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "catchError", function() { return catchError; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(229); -/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(231); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_OuterSubscriber,_InnerSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ - - - + return SequenceEqualSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -function catchError(selector) { - return function catchErrorOperatorFunction(source) { - var operator = new CatchOperator(selector); - var caught = source.lift(operator); - return (operator.caught = caught); - }; -} -var CatchOperator = /*@__PURE__*/ (function () { - function CatchOperator(selector) { - this.selector = selector; - } - CatchOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught)); - }; - return CatchOperator; -}()); -var CatchSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CatchSubscriber, _super); - function CatchSubscriber(destination, selector, caught) { +var SequenceEqualCompareToSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SequenceEqualCompareToSubscriber, _super); + function SequenceEqualCompareToSubscriber(destination, parent) { var _this = _super.call(this, destination) || this; - _this.selector = selector; - _this.caught = caught; + _this.parent = parent; return _this; } - CatchSubscriber.prototype.error = function (err) { - if (!this.isStopped) { - var result = void 0; - try { - result = this.selector(err, this.caught); - } - catch (err2) { - _super.prototype.error.call(this, err2); - return; - } - this._unsubscribeAndRecycle(); - var innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__["InnerSubscriber"](this, undefined, undefined); - this.add(innerSubscriber); - Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(this, result, undefined, undefined, innerSubscriber); - } + SequenceEqualCompareToSubscriber.prototype._next = function (value) { + this.parent.nextB(value); }; - return CatchSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); -//# sourceMappingURL=catchError.js.map - - -/***/ }), -/* 279 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "combineAll", function() { return combineAll; }); -/* harmony import */ var _observable_combineLatest__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(228); -/** PURE_IMPORTS_START _observable_combineLatest PURE_IMPORTS_END */ - -function combineAll(project) { - return function (source) { return source.lift(new _observable_combineLatest__WEBPACK_IMPORTED_MODULE_0__["CombineLatestOperator"](project)); }; -} -//# sourceMappingURL=combineAll.js.map + SequenceEqualCompareToSubscriber.prototype._error = function (err) { + this.parent.error(err); + this.unsubscribe(); + }; + SequenceEqualCompareToSubscriber.prototype._complete = function () { + this.parent.completeB(); + this.unsubscribe(); + }; + return SequenceEqualCompareToSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=sequenceEqual.js.map /***/ }), -/* 280 */ +/* 308 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "combineLatest", function() { return combineLatest; }); -/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(178); -/* harmony import */ var _observable_combineLatest__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(228); -/* harmony import */ var _observable_from__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(243); -/** PURE_IMPORTS_START _util_isArray,_observable_combineLatest,_observable_from PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "share", function() { return share; }); +/* harmony import */ var _multicast__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(291); +/* harmony import */ var _refCount__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(161); +/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(158); +/** PURE_IMPORTS_START _multicast,_refCount,_Subject PURE_IMPORTS_END */ -var none = {}; -function combineLatest() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; - } - var project = null; - if (typeof observables[observables.length - 1] === 'function') { - project = observables.pop(); - } - if (observables.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_0__["isArray"])(observables[0])) { - observables = observables[0].slice(); - } - return function (source) { return source.lift.call(Object(_observable_from__WEBPACK_IMPORTED_MODULE_2__["from"])([source].concat(observables)), new _observable_combineLatest__WEBPACK_IMPORTED_MODULE_1__["CombineLatestOperator"](project)); }; +function shareSubjectFactory() { + return new _Subject__WEBPACK_IMPORTED_MODULE_2__["Subject"](); } -//# sourceMappingURL=combineLatest.js.map +function share() { + return function (source) { return Object(_refCount__WEBPACK_IMPORTED_MODULE_1__["refCount"])()(Object(_multicast__WEBPACK_IMPORTED_MODULE_0__["multicast"])(shareSubjectFactory)(source)); }; +} +//# sourceMappingURL=share.js.map /***/ }), -/* 281 */ +/* 309 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat", function() { return concat; }); -/* harmony import */ var _observable_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(239); -/** PURE_IMPORTS_START _observable_concat PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "shareReplay", function() { return shareReplay; }); +/* harmony import */ var _ReplaySubject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(164); +/** PURE_IMPORTS_START _ReplaySubject PURE_IMPORTS_END */ -function concat() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; +function shareReplay(configOrBufferSize, windowTime, scheduler) { + var config; + if (configOrBufferSize && typeof configOrBufferSize === 'object') { + config = configOrBufferSize; } - return function (source) { return source.lift.call(_observable_concat__WEBPACK_IMPORTED_MODULE_0__["concat"].apply(void 0, [source].concat(observables))); }; + else { + config = { + bufferSize: configOrBufferSize, + windowTime: windowTime, + refCount: false, + scheduler: scheduler + }; + } + return function (source) { return source.lift(shareReplayOperator(config)); }; } -//# sourceMappingURL=concat.js.map - - -/***/ }), -/* 282 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concatMap", function() { return concatMap; }); -/* harmony import */ var _mergeMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(242); -/** PURE_IMPORTS_START _mergeMap PURE_IMPORTS_END */ - -function concatMap(project, resultSelector) { - return Object(_mergeMap__WEBPACK_IMPORTED_MODULE_0__["mergeMap"])(project, resultSelector, 1); +function shareReplayOperator(_a) { + var _b = _a.bufferSize, bufferSize = _b === void 0 ? Number.POSITIVE_INFINITY : _b, _c = _a.windowTime, windowTime = _c === void 0 ? Number.POSITIVE_INFINITY : _c, useRefCount = _a.refCount, scheduler = _a.scheduler; + var subject; + var refCount = 0; + var subscription; + var hasError = false; + var isComplete = false; + return function shareReplayOperation(source) { + refCount++; + if (!subject || hasError) { + hasError = false; + subject = new _ReplaySubject__WEBPACK_IMPORTED_MODULE_0__["ReplaySubject"](bufferSize, windowTime, scheduler); + subscription = source.subscribe({ + next: function (value) { subject.next(value); }, + error: function (err) { + hasError = true; + subject.error(err); + }, + complete: function () { + isComplete = true; + subject.complete(); + }, + }); + } + var innerSub = subject.subscribe(this); + this.add(function () { + refCount--; + innerSub.unsubscribe(); + if (subscription && !isComplete && useRefCount && refCount === 0) { + subscription.unsubscribe(); + subscription = undefined; + subject = undefined; + } + }); + }; } -//# sourceMappingURL=concatMap.js.map +//# sourceMappingURL=shareReplay.js.map /***/ }), -/* 283 */ +/* 310 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concatMapTo", function() { return concatMapTo; }); -/* harmony import */ var _concatMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(282); -/** PURE_IMPORTS_START _concatMap PURE_IMPORTS_END */ - -function concatMapTo(innerObservable, resultSelector) { - return Object(_concatMap__WEBPACK_IMPORTED_MODULE_0__["concatMap"])(function () { return innerObservable; }, resultSelector); -} -//# sourceMappingURL=concatMapTo.js.map - - -/***/ }), -/* 284 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "single", function() { return single; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/* harmony import */ var _util_EmptyError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(194); +/** PURE_IMPORTS_START tslib,_Subscriber,_util_EmptyError PURE_IMPORTS_END */ -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "count", function() { return count; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function count(predicate) { - return function (source) { return source.lift(new CountOperator(predicate, source)); }; +function single(predicate) { + return function (source) { return source.lift(new SingleOperator(predicate, source)); }; } -var CountOperator = /*@__PURE__*/ (function () { - function CountOperator(predicate, source) { +var SingleOperator = /*@__PURE__*/ (function () { + function SingleOperator(predicate, source) { this.predicate = predicate; this.source = source; } - CountOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new CountSubscriber(subscriber, this.predicate, this.source)); + SingleOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new SingleSubscriber(subscriber, this.predicate, this.source)); }; - return CountOperator; + return SingleOperator; }()); -var CountSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CountSubscriber, _super); - function CountSubscriber(destination, predicate, source) { +var SingleSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SingleSubscriber, _super); + function SingleSubscriber(destination, predicate, source) { var _this = _super.call(this, destination) || this; _this.predicate = predicate; _this.source = source; - _this.count = 0; + _this.seenValue = false; _this.index = 0; return _this; } - CountSubscriber.prototype._next = function (value) { + SingleSubscriber.prototype.applySingleValue = function (value) { + if (this.seenValue) { + this.destination.error('Sequence contains more than one element'); + } + else { + this.seenValue = true; + this.singleValue = value; + } + }; + SingleSubscriber.prototype._next = function (value) { + var index = this.index++; if (this.predicate) { - this._tryPredicate(value); + this.tryNext(value, index); } else { - this.count++; + this.applySingleValue(value); } }; - CountSubscriber.prototype._tryPredicate = function (value) { - var result; + SingleSubscriber.prototype.tryNext = function (value, index) { try { - result = this.predicate(value, this.index++, this.source); + if (this.predicate(value, index, this.source)) { + this.applySingleValue(value); + } } catch (err) { this.destination.error(err); - return; - } - if (result) { - this.count++; } }; - CountSubscriber.prototype._complete = function () { - this.destination.next(this.count); - this.destination.complete(); + SingleSubscriber.prototype._complete = function () { + var destination = this.destination; + if (this.index > 0) { + destination.next(this.seenValue ? this.singleValue : undefined); + destination.complete(); + } + else { + destination.error(new _util_EmptyError__WEBPACK_IMPORTED_MODULE_2__["EmptyError"]); + } }; - return CountSubscriber; + return SingleSubscriber; }(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=count.js.map +//# sourceMappingURL=single.js.map /***/ }), -/* 285 */ +/* 311 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "debounce", function() { return debounce; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "skip", function() { return skip; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function debounce(durationSelector) { - return function (source) { return source.lift(new DebounceOperator(durationSelector)); }; +function skip(count) { + return function (source) { return source.lift(new SkipOperator(count)); }; } -var DebounceOperator = /*@__PURE__*/ (function () { - function DebounceOperator(durationSelector) { - this.durationSelector = durationSelector; +var SkipOperator = /*@__PURE__*/ (function () { + function SkipOperator(total) { + this.total = total; } - DebounceOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new DebounceSubscriber(subscriber, this.durationSelector)); + SkipOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new SkipSubscriber(subscriber, this.total)); }; - return DebounceOperator; + return SkipOperator; }()); -var DebounceSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DebounceSubscriber, _super); - function DebounceSubscriber(destination, durationSelector) { +var SkipSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SkipSubscriber, _super); + function SkipSubscriber(destination, total) { var _this = _super.call(this, destination) || this; - _this.durationSelector = durationSelector; - _this.hasValue = false; - _this.durationSubscription = null; + _this.total = total; + _this.count = 0; return _this; } - DebounceSubscriber.prototype._next = function (value) { - try { - var result = this.durationSelector.call(this, value); - if (result) { - this._tryNext(value, result); - } - } - catch (err) { - this.destination.error(err); - } - }; - DebounceSubscriber.prototype._complete = function () { - this.emitValue(); - this.destination.complete(); - }; - DebounceSubscriber.prototype._tryNext = function (value, duration) { - var subscription = this.durationSubscription; - this.value = value; - this.hasValue = true; - if (subscription) { - subscription.unsubscribe(); - this.remove(subscription); - } - subscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, duration); - if (subscription && !subscription.closed) { - this.add(this.durationSubscription = subscription); - } - }; - DebounceSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.emitValue(); - }; - DebounceSubscriber.prototype.notifyComplete = function () { - this.emitValue(); - }; - DebounceSubscriber.prototype.emitValue = function () { - if (this.hasValue) { - var value = this.value; - var subscription = this.durationSubscription; - if (subscription) { - this.durationSubscription = null; - subscription.unsubscribe(); - this.remove(subscription); - } - this.value = null; - this.hasValue = false; - _super.prototype._next.call(this, value); + SkipSubscriber.prototype._next = function (x) { + if (++this.count > this.total) { + this.destination.next(x); } }; - return DebounceSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); -//# sourceMappingURL=debounce.js.map + return SkipSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=skip.js.map /***/ }), -/* 286 */ +/* 312 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "debounceTime", function() { return debounceTime; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(215); -/** PURE_IMPORTS_START tslib,_Subscriber,_scheduler_async PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "skipLast", function() { return skipLast; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/* harmony import */ var _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(193); +/** PURE_IMPORTS_START tslib,_Subscriber,_util_ArgumentOutOfRangeError PURE_IMPORTS_END */ -function debounceTime(dueTime, scheduler) { - if (scheduler === void 0) { - scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_2__["async"]; - } - return function (source) { return source.lift(new DebounceTimeOperator(dueTime, scheduler)); }; +function skipLast(count) { + return function (source) { return source.lift(new SkipLastOperator(count)); }; } -var DebounceTimeOperator = /*@__PURE__*/ (function () { - function DebounceTimeOperator(dueTime, scheduler) { - this.dueTime = dueTime; - this.scheduler = scheduler; +var SkipLastOperator = /*@__PURE__*/ (function () { + function SkipLastOperator(_skipCount) { + this._skipCount = _skipCount; + if (this._skipCount < 0) { + throw new _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_2__["ArgumentOutOfRangeError"]; + } } - DebounceTimeOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler)); + SkipLastOperator.prototype.call = function (subscriber, source) { + if (this._skipCount === 0) { + return source.subscribe(new _Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"](subscriber)); + } + else { + return source.subscribe(new SkipLastSubscriber(subscriber, this._skipCount)); + } }; - return DebounceTimeOperator; + return SkipLastOperator; }()); -var DebounceTimeSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DebounceTimeSubscriber, _super); - function DebounceTimeSubscriber(destination, dueTime, scheduler) { +var SkipLastSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SkipLastSubscriber, _super); + function SkipLastSubscriber(destination, _skipCount) { var _this = _super.call(this, destination) || this; - _this.dueTime = dueTime; - _this.scheduler = scheduler; - _this.debouncedSubscription = null; - _this.lastValue = null; - _this.hasValue = false; + _this._skipCount = _skipCount; + _this._count = 0; + _this._ring = new Array(_skipCount); return _this; } - DebounceTimeSubscriber.prototype._next = function (value) { - this.clearDebounce(); - this.lastValue = value; - this.hasValue = true; - this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this)); - }; - DebounceTimeSubscriber.prototype._complete = function () { - this.debouncedNext(); - this.destination.complete(); - }; - DebounceTimeSubscriber.prototype.debouncedNext = function () { - this.clearDebounce(); - if (this.hasValue) { - var lastValue = this.lastValue; - this.lastValue = null; - this.hasValue = false; - this.destination.next(lastValue); + SkipLastSubscriber.prototype._next = function (value) { + var skipCount = this._skipCount; + var count = this._count++; + if (count < skipCount) { + this._ring[count] = value; } - }; - DebounceTimeSubscriber.prototype.clearDebounce = function () { - var debouncedSubscription = this.debouncedSubscription; - if (debouncedSubscription !== null) { - this.remove(debouncedSubscription); - debouncedSubscription.unsubscribe(); - this.debouncedSubscription = null; + else { + var currentIndex = count % skipCount; + var ring = this._ring; + var oldValue = ring[currentIndex]; + ring[currentIndex] = value; + this.destination.next(oldValue); } }; - return DebounceTimeSubscriber; + return SkipLastSubscriber; }(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -function dispatchNext(subscriber) { - subscriber.debouncedNext(); -} -//# sourceMappingURL=debounceTime.js.map +//# sourceMappingURL=skipLast.js.map /***/ }), -/* 287 */ +/* 313 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultIfEmpty", function() { return defaultIfEmpty; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "skipUntil", function() { return skipUntil; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(200); +/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(202); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_OuterSubscriber,_InnerSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function defaultIfEmpty(defaultValue) { - if (defaultValue === void 0) { - defaultValue = null; - } - return function (source) { return source.lift(new DefaultIfEmptyOperator(defaultValue)); }; + + +function skipUntil(notifier) { + return function (source) { return source.lift(new SkipUntilOperator(notifier)); }; } -var DefaultIfEmptyOperator = /*@__PURE__*/ (function () { - function DefaultIfEmptyOperator(defaultValue) { - this.defaultValue = defaultValue; +var SkipUntilOperator = /*@__PURE__*/ (function () { + function SkipUntilOperator(notifier) { + this.notifier = notifier; } - DefaultIfEmptyOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue)); + SkipUntilOperator.prototype.call = function (destination, source) { + return source.subscribe(new SkipUntilSubscriber(destination, this.notifier)); }; - return DefaultIfEmptyOperator; + return SkipUntilOperator; }()); -var DefaultIfEmptySubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DefaultIfEmptySubscriber, _super); - function DefaultIfEmptySubscriber(destination, defaultValue) { +var SkipUntilSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SkipUntilSubscriber, _super); + function SkipUntilSubscriber(destination, notifier) { var _this = _super.call(this, destination) || this; - _this.defaultValue = defaultValue; - _this.isEmpty = true; + _this.hasValue = false; + var innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__["InnerSubscriber"](_this, undefined, undefined); + _this.add(innerSubscriber); + _this.innerSubscription = innerSubscriber; + Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(_this, notifier, undefined, undefined, innerSubscriber); return _this; } - DefaultIfEmptySubscriber.prototype._next = function (value) { - this.isEmpty = false; - this.destination.next(value); + SkipUntilSubscriber.prototype._next = function (value) { + if (this.hasValue) { + _super.prototype._next.call(this, value); + } }; - DefaultIfEmptySubscriber.prototype._complete = function () { - if (this.isEmpty) { - this.destination.next(this.defaultValue); + SkipUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.hasValue = true; + if (this.innerSubscription) { + this.innerSubscription.unsubscribe(); } - this.destination.complete(); }; - return DefaultIfEmptySubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=defaultIfEmpty.js.map + SkipUntilSubscriber.prototype.notifyComplete = function () { + }; + return SkipUntilSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); +//# sourceMappingURL=skipUntil.js.map /***/ }), -/* 288 */ +/* 314 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "delay", function() { return delay; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(215); -/* harmony import */ var _util_isDate__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(289); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(172); -/* harmony import */ var _Notification__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(202); -/** PURE_IMPORTS_START tslib,_scheduler_async,_util_isDate,_Subscriber,_Notification PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "skipWhile", function() { return skipWhile; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ + +function skipWhile(predicate) { + return function (source) { return source.lift(new SkipWhileOperator(predicate)); }; +} +var SkipWhileOperator = /*@__PURE__*/ (function () { + function SkipWhileOperator(predicate) { + this.predicate = predicate; + } + SkipWhileOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate)); + }; + return SkipWhileOperator; +}()); +var SkipWhileSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SkipWhileSubscriber, _super); + function SkipWhileSubscriber(destination, predicate) { + var _this = _super.call(this, destination) || this; + _this.predicate = predicate; + _this.skipping = true; + _this.index = 0; + return _this; + } + SkipWhileSubscriber.prototype._next = function (value) { + var destination = this.destination; + if (this.skipping) { + this.tryCallPredicate(value); + } + if (!this.skipping) { + destination.next(value); + } + }; + SkipWhileSubscriber.prototype.tryCallPredicate = function (value) { + try { + var result = this.predicate(value, this.index++); + this.skipping = Boolean(result); + } + catch (err) { + this.destination.error(err); + } + }; + return SkipWhileSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +//# sourceMappingURL=skipWhile.js.map +/***/ }), +/* 315 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startWith", function() { return startWith; }); +/* harmony import */ var _observable_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(210); +/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(176); +/** PURE_IMPORTS_START _observable_concat,_util_isScheduler PURE_IMPORTS_END */ -function delay(delay, scheduler) { - if (scheduler === void 0) { - scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__["async"]; + +function startWith() { + var array = []; + for (var _i = 0; _i < arguments.length; _i++) { + array[_i] = arguments[_i]; + } + var scheduler = array[array.length - 1]; + if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_1__["isScheduler"])(scheduler)) { + array.pop(); + return function (source) { return Object(_observable_concat__WEBPACK_IMPORTED_MODULE_0__["concat"])(array, source, scheduler); }; + } + else { + return function (source) { return Object(_observable_concat__WEBPACK_IMPORTED_MODULE_0__["concat"])(array, source); }; } - var absoluteDelay = Object(_util_isDate__WEBPACK_IMPORTED_MODULE_2__["isDate"])(delay); - var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay); - return function (source) { return source.lift(new DelayOperator(delayFor, scheduler)); }; } -var DelayOperator = /*@__PURE__*/ (function () { - function DelayOperator(delay, scheduler) { - this.delay = delay; +//# sourceMappingURL=startWith.js.map + + +/***/ }), +/* 316 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeOn", function() { return subscribeOn; }); +/* harmony import */ var _observable_SubscribeOnObservable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(317); +/** PURE_IMPORTS_START _observable_SubscribeOnObservable PURE_IMPORTS_END */ + +function subscribeOn(scheduler, delay) { + if (delay === void 0) { + delay = 0; + } + return function subscribeOnOperatorFunction(source) { + return source.lift(new SubscribeOnOperator(scheduler, delay)); + }; +} +var SubscribeOnOperator = /*@__PURE__*/ (function () { + function SubscribeOnOperator(scheduler, delay) { this.scheduler = scheduler; + this.delay = delay; } - DelayOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler)); + SubscribeOnOperator.prototype.call = function (subscriber, source) { + return new _observable_SubscribeOnObservable__WEBPACK_IMPORTED_MODULE_0__["SubscribeOnObservable"](source, this.delay, this.scheduler).subscribe(subscriber); }; - return DelayOperator; + return SubscribeOnOperator; }()); -var DelaySubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DelaySubscriber, _super); - function DelaySubscriber(destination, delay, scheduler) { - var _this = _super.call(this, destination) || this; - _this.delay = delay; +//# sourceMappingURL=subscribeOn.js.map + + +/***/ }), +/* 317 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscribeOnObservable", function() { return SubscribeOnObservable; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(141); +/* harmony import */ var _scheduler_asap__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(182); +/* harmony import */ var _util_isNumeric__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(228); +/** PURE_IMPORTS_START tslib,_Observable,_scheduler_asap,_util_isNumeric PURE_IMPORTS_END */ + + + + +var SubscribeOnObservable = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SubscribeOnObservable, _super); + function SubscribeOnObservable(source, delayTime, scheduler) { + if (delayTime === void 0) { + delayTime = 0; + } + if (scheduler === void 0) { + scheduler = _scheduler_asap__WEBPACK_IMPORTED_MODULE_2__["asap"]; + } + var _this = _super.call(this) || this; + _this.source = source; + _this.delayTime = delayTime; _this.scheduler = scheduler; - _this.queue = []; - _this.active = false; - _this.errored = false; + if (!Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_3__["isNumeric"])(delayTime) || delayTime < 0) { + _this.delayTime = 0; + } + if (!scheduler || typeof scheduler.schedule !== 'function') { + _this.scheduler = _scheduler_asap__WEBPACK_IMPORTED_MODULE_2__["asap"]; + } return _this; } - DelaySubscriber.dispatch = function (state) { - var source = state.source; - var queue = source.queue; - var scheduler = state.scheduler; - var destination = state.destination; - while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) { - queue.shift().notification.observe(destination); - } - if (queue.length > 0) { - var delay_1 = Math.max(0, queue[0].time - scheduler.now()); - this.schedule(state, delay_1); + SubscribeOnObservable.create = function (source, delay, scheduler) { + if (delay === void 0) { + delay = 0; } - else { - this.unsubscribe(); - source.active = false; + if (scheduler === void 0) { + scheduler = _scheduler_asap__WEBPACK_IMPORTED_MODULE_2__["asap"]; } + return new SubscribeOnObservable(source, delay, scheduler); }; - DelaySubscriber.prototype._schedule = function (scheduler) { - this.active = true; - var destination = this.destination; - destination.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, { - source: this, destination: this.destination, scheduler: scheduler - })); + SubscribeOnObservable.dispatch = function (arg) { + var source = arg.source, subscriber = arg.subscriber; + return this.add(source.subscribe(subscriber)); }; - DelaySubscriber.prototype.scheduleNotification = function (notification) { - if (this.errored === true) { - return; - } + SubscribeOnObservable.prototype._subscribe = function (subscriber) { + var delay = this.delayTime; + var source = this.source; var scheduler = this.scheduler; - var message = new DelayMessage(scheduler.now() + this.delay, notification); - this.queue.push(message); - if (this.active === false) { - this._schedule(scheduler); - } - }; - DelaySubscriber.prototype._next = function (value) { - this.scheduleNotification(_Notification__WEBPACK_IMPORTED_MODULE_4__["Notification"].createNext(value)); - }; - DelaySubscriber.prototype._error = function (err) { - this.errored = true; - this.queue = []; - this.destination.error(err); - this.unsubscribe(); - }; - DelaySubscriber.prototype._complete = function () { - this.scheduleNotification(_Notification__WEBPACK_IMPORTED_MODULE_4__["Notification"].createComplete()); - this.unsubscribe(); + return scheduler.schedule(SubscribeOnObservable.dispatch, delay, { + source: source, subscriber: subscriber + }); }; - return DelaySubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_3__["Subscriber"])); -var DelayMessage = /*@__PURE__*/ (function () { - function DelayMessage(time, notification) { - this.time = time; - this.notification = notification; - } - return DelayMessage; -}()); -//# sourceMappingURL=delay.js.map + return SubscribeOnObservable; +}(_Observable__WEBPACK_IMPORTED_MODULE_1__["Observable"])); + +//# sourceMappingURL=SubscribeOnObservable.js.map /***/ }), -/* 289 */ +/* 318 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDate", function() { return isDate; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function isDate(value) { - return value instanceof Date && !isNaN(+value); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "switchAll", function() { return switchAll; }); +/* harmony import */ var _switchMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(319); +/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(191); +/** PURE_IMPORTS_START _switchMap,_util_identity PURE_IMPORTS_END */ + + +function switchAll() { + return Object(_switchMap__WEBPACK_IMPORTED_MODULE_0__["switchMap"])(_util_identity__WEBPACK_IMPORTED_MODULE_1__["identity"]); } -//# sourceMappingURL=isDate.js.map +//# sourceMappingURL=switchAll.js.map /***/ }), -/* 290 */ +/* 319 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "delayWhen", function() { return delayWhen; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(170); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_Subscriber,_Observable,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "switchMap", function() { return switchMap; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(200); +/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(202); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(201); +/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(197); +/* harmony import */ var _observable_from__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(214); +/** PURE_IMPORTS_START tslib,_OuterSubscriber,_InnerSubscriber,_util_subscribeToResult,_map,_observable_from PURE_IMPORTS_END */ -function delayWhen(delayDurationSelector, subscriptionDelay) { - if (subscriptionDelay) { - return function (source) { - return new SubscriptionDelayObservable(source, subscriptionDelay) - .lift(new DelayWhenOperator(delayDurationSelector)); - }; + +function switchMap(project, resultSelector) { + if (typeof resultSelector === 'function') { + return function (source) { return source.pipe(switchMap(function (a, i) { return Object(_observable_from__WEBPACK_IMPORTED_MODULE_5__["from"])(project(a, i)).pipe(Object(_map__WEBPACK_IMPORTED_MODULE_4__["map"])(function (b, ii) { return resultSelector(a, b, i, ii); })); })); }; } - return function (source) { return source.lift(new DelayWhenOperator(delayDurationSelector)); }; + return function (source) { return source.lift(new SwitchMapOperator(project)); }; } -var DelayWhenOperator = /*@__PURE__*/ (function () { - function DelayWhenOperator(delayDurationSelector) { - this.delayDurationSelector = delayDurationSelector; +var SwitchMapOperator = /*@__PURE__*/ (function () { + function SwitchMapOperator(project) { + this.project = project; } - DelayWhenOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new DelayWhenSubscriber(subscriber, this.delayDurationSelector)); + SwitchMapOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new SwitchMapSubscriber(subscriber, this.project)); }; - return DelayWhenOperator; + return SwitchMapOperator; }()); -var DelayWhenSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DelayWhenSubscriber, _super); - function DelayWhenSubscriber(destination, delayDurationSelector) { +var SwitchMapSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SwitchMapSubscriber, _super); + function SwitchMapSubscriber(destination, project) { var _this = _super.call(this, destination) || this; - _this.delayDurationSelector = delayDurationSelector; - _this.completed = false; - _this.delayNotifierSubscriptions = []; + _this.project = project; _this.index = 0; return _this; } - DelayWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.destination.next(outerValue); - this.removeSubscription(innerSub); - this.tryComplete(); - }; - DelayWhenSubscriber.prototype.notifyError = function (error, innerSub) { - this._error(error); - }; - DelayWhenSubscriber.prototype.notifyComplete = function (innerSub) { - var value = this.removeSubscription(innerSub); - if (value) { - this.destination.next(value); - } - this.tryComplete(); - }; - DelayWhenSubscriber.prototype._next = function (value) { + SwitchMapSubscriber.prototype._next = function (value) { + var result; var index = this.index++; try { - var delayNotifier = this.delayDurationSelector(value, index); - if (delayNotifier) { - this.tryDelay(delayNotifier, value); - } - } - catch (err) { - this.destination.error(err); + result = this.project(value, index); } - }; - DelayWhenSubscriber.prototype._complete = function () { - this.completed = true; - this.tryComplete(); - this.unsubscribe(); - }; - DelayWhenSubscriber.prototype.removeSubscription = function (subscription) { - subscription.unsubscribe(); - var subscriptionIdx = this.delayNotifierSubscriptions.indexOf(subscription); - if (subscriptionIdx !== -1) { - this.delayNotifierSubscriptions.splice(subscriptionIdx, 1); + catch (error) { + this.destination.error(error); + return; } - return subscription.outerValue; + this._innerSub(result, value, index); }; - DelayWhenSubscriber.prototype.tryDelay = function (delayNotifier, value) { - var notifierSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__["subscribeToResult"])(this, delayNotifier, value); - if (notifierSubscription && !notifierSubscription.closed) { - var destination = this.destination; - destination.add(notifierSubscription); - this.delayNotifierSubscriptions.push(notifierSubscription); + SwitchMapSubscriber.prototype._innerSub = function (result, value, index) { + var innerSubscription = this.innerSubscription; + if (innerSubscription) { + innerSubscription.unsubscribe(); } + var innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__["InnerSubscriber"](this, undefined, undefined); + var destination = this.destination; + destination.add(innerSubscriber); + this.innerSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(this, result, value, index, innerSubscriber); }; - DelayWhenSubscriber.prototype.tryComplete = function () { - if (this.completed && this.delayNotifierSubscriptions.length === 0) { - this.destination.complete(); + SwitchMapSubscriber.prototype._complete = function () { + var innerSubscription = this.innerSubscription; + if (!innerSubscription || innerSubscription.closed) { + _super.prototype._complete.call(this); } - }; - return DelayWhenSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__["OuterSubscriber"])); -var SubscriptionDelayObservable = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SubscriptionDelayObservable, _super); - function SubscriptionDelayObservable(source, subscriptionDelay) { - var _this = _super.call(this) || this; - _this.source = source; - _this.subscriptionDelay = subscriptionDelay; - return _this; - } - SubscriptionDelayObservable.prototype._subscribe = function (subscriber) { - this.subscriptionDelay.subscribe(new SubscriptionDelaySubscriber(subscriber, this.source)); - }; - return SubscriptionDelayObservable; -}(_Observable__WEBPACK_IMPORTED_MODULE_2__["Observable"])); -var SubscriptionDelaySubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SubscriptionDelaySubscriber, _super); - function SubscriptionDelaySubscriber(parent, source) { - var _this = _super.call(this) || this; - _this.parent = parent; - _this.source = source; - _this.sourceSubscribed = false; - return _this; - } - SubscriptionDelaySubscriber.prototype._next = function (unused) { - this.subscribeToSource(); - }; - SubscriptionDelaySubscriber.prototype._error = function (err) { this.unsubscribe(); - this.parent.error(err); }; - SubscriptionDelaySubscriber.prototype._complete = function () { - this.unsubscribe(); - this.subscribeToSource(); + SwitchMapSubscriber.prototype._unsubscribe = function () { + this.innerSubscription = null; }; - SubscriptionDelaySubscriber.prototype.subscribeToSource = function () { - if (!this.sourceSubscribed) { - this.sourceSubscribed = true; - this.unsubscribe(); - this.source.subscribe(this.parent); + SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) { + var destination = this.destination; + destination.remove(innerSub); + this.innerSubscription = null; + if (this.isStopped) { + _super.prototype._complete.call(this); } }; - return SubscriptionDelaySubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=delayWhen.js.map + SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.destination.next(innerValue); + }; + return SwitchMapSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); +//# sourceMappingURL=switchMap.js.map /***/ }), -/* 291 */ +/* 320 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dematerialize", function() { return dematerialize; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "switchMapTo", function() { return switchMapTo; }); +/* harmony import */ var _switchMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(319); +/** PURE_IMPORTS_START _switchMap PURE_IMPORTS_END */ -function dematerialize() { - return function dematerializeOperatorFunction(source) { - return source.lift(new DeMaterializeOperator()); - }; +function switchMapTo(innerObservable, resultSelector) { + return resultSelector ? Object(_switchMap__WEBPACK_IMPORTED_MODULE_0__["switchMap"])(function () { return innerObservable; }, resultSelector) : Object(_switchMap__WEBPACK_IMPORTED_MODULE_0__["switchMap"])(function () { return innerObservable; }); } -var DeMaterializeOperator = /*@__PURE__*/ (function () { - function DeMaterializeOperator() { - } - DeMaterializeOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new DeMaterializeSubscriber(subscriber)); - }; - return DeMaterializeOperator; -}()); -var DeMaterializeSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DeMaterializeSubscriber, _super); - function DeMaterializeSubscriber(destination) { - return _super.call(this, destination) || this; - } - DeMaterializeSubscriber.prototype._next = function (value) { - value.observe(this.destination); - }; - return DeMaterializeSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=dematerialize.js.map +//# sourceMappingURL=switchMapTo.js.map /***/ }), -/* 292 */ +/* 321 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "distinct", function() { return distinct; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DistinctSubscriber", function() { return DistinctSubscriber; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(230); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "takeUntil", function() { return takeUntil; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(201); /** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function distinct(keySelector, flushes) { - return function (source) { return source.lift(new DistinctOperator(keySelector, flushes)); }; +function takeUntil(notifier) { + return function (source) { return source.lift(new TakeUntilOperator(notifier)); }; } -var DistinctOperator = /*@__PURE__*/ (function () { - function DistinctOperator(keySelector, flushes) { - this.keySelector = keySelector; - this.flushes = flushes; +var TakeUntilOperator = /*@__PURE__*/ (function () { + function TakeUntilOperator(notifier) { + this.notifier = notifier; } - DistinctOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes)); + TakeUntilOperator.prototype.call = function (subscriber, source) { + var takeUntilSubscriber = new TakeUntilSubscriber(subscriber); + var notifierSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(takeUntilSubscriber, this.notifier); + if (notifierSubscription && !takeUntilSubscriber.seenValue) { + takeUntilSubscriber.add(notifierSubscription); + return source.subscribe(takeUntilSubscriber); + } + return takeUntilSubscriber; }; - return DistinctOperator; + return TakeUntilOperator; }()); -var DistinctSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DistinctSubscriber, _super); - function DistinctSubscriber(destination, keySelector, flushes) { +var TakeUntilSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TakeUntilSubscriber, _super); + function TakeUntilSubscriber(destination) { var _this = _super.call(this, destination) || this; - _this.keySelector = keySelector; - _this.values = new Set(); - if (flushes) { - _this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(_this, flushes)); - } + _this.seenValue = false; return _this; } - DistinctSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.values.clear(); - }; - DistinctSubscriber.prototype.notifyError = function (error, innerSub) { - this._error(error); - }; - DistinctSubscriber.prototype._next = function (value) { - if (this.keySelector) { - this._useKeySelector(value); - } - else { - this._finalizeNext(value, value); - } - }; - DistinctSubscriber.prototype._useKeySelector = function (value) { - var key; - var destination = this.destination; - try { - key = this.keySelector(value); - } - catch (err) { - destination.error(err); - return; - } - this._finalizeNext(key, value); + TakeUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.seenValue = true; + this.complete(); }; - DistinctSubscriber.prototype._finalizeNext = function (key, value) { - var values = this.values; - if (!values.has(key)) { - values.add(key); - this.destination.next(value); - } + TakeUntilSubscriber.prototype.notifyComplete = function () { }; - return DistinctSubscriber; + return TakeUntilSubscriber; }(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); - -//# sourceMappingURL=distinct.js.map +//# sourceMappingURL=takeUntil.js.map /***/ }), -/* 293 */ +/* 322 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "distinctUntilChanged", function() { return distinctUntilChanged; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "takeWhile", function() { return takeWhile; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function distinctUntilChanged(compare, keySelector) { - return function (source) { return source.lift(new DistinctUntilChangedOperator(compare, keySelector)); }; +function takeWhile(predicate, inclusive) { + if (inclusive === void 0) { + inclusive = false; + } + return function (source) { + return source.lift(new TakeWhileOperator(predicate, inclusive)); + }; } -var DistinctUntilChangedOperator = /*@__PURE__*/ (function () { - function DistinctUntilChangedOperator(compare, keySelector) { - this.compare = compare; - this.keySelector = keySelector; +var TakeWhileOperator = /*@__PURE__*/ (function () { + function TakeWhileOperator(predicate, inclusive) { + this.predicate = predicate; + this.inclusive = inclusive; } - DistinctUntilChangedOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector)); + TakeWhileOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new TakeWhileSubscriber(subscriber, this.predicate, this.inclusive)); }; - return DistinctUntilChangedOperator; + return TakeWhileOperator; }()); -var DistinctUntilChangedSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DistinctUntilChangedSubscriber, _super); - function DistinctUntilChangedSubscriber(destination, compare, keySelector) { +var TakeWhileSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TakeWhileSubscriber, _super); + function TakeWhileSubscriber(destination, predicate, inclusive) { var _this = _super.call(this, destination) || this; - _this.keySelector = keySelector; - _this.hasKey = false; - if (typeof compare === 'function') { - _this.compare = compare; - } + _this.predicate = predicate; + _this.inclusive = inclusive; + _this.index = 0; return _this; } - DistinctUntilChangedSubscriber.prototype.compare = function (x, y) { - return x === y; - }; - DistinctUntilChangedSubscriber.prototype._next = function (value) { - var key; + TakeWhileSubscriber.prototype._next = function (value) { + var destination = this.destination; + var result; try { - var keySelector = this.keySelector; - key = keySelector ? keySelector(value) : value; + result = this.predicate(value, this.index++); } catch (err) { - return this.destination.error(err); + destination.error(err); + return; } - var result = false; - if (this.hasKey) { - try { - var compare = this.compare; - result = compare(this.key, key); - } - catch (err) { - return this.destination.error(err); - } + this.nextOrComplete(value, result); + }; + TakeWhileSubscriber.prototype.nextOrComplete = function (value, predicateResult) { + var destination = this.destination; + if (Boolean(predicateResult)) { + destination.next(value); } else { - this.hasKey = true; - } - if (!result) { - this.key = key; - this.destination.next(value); + if (this.inclusive) { + destination.next(value); + } + destination.complete(); } }; - return DistinctUntilChangedSubscriber; + return TakeWhileSubscriber; }(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=distinctUntilChanged.js.map - - -/***/ }), -/* 294 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "distinctUntilKeyChanged", function() { return distinctUntilKeyChanged; }); -/* harmony import */ var _distinctUntilChanged__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(293); -/** PURE_IMPORTS_START _distinctUntilChanged PURE_IMPORTS_END */ - -function distinctUntilKeyChanged(key, compare) { - return Object(_distinctUntilChanged__WEBPACK_IMPORTED_MODULE_0__["distinctUntilChanged"])(function (x, y) { return compare ? compare(x[key], y[key]) : x[key] === y[key]; }); -} -//# sourceMappingURL=distinctUntilKeyChanged.js.map +//# sourceMappingURL=takeWhile.js.map /***/ }), -/* 295 */ +/* 323 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "elementAt", function() { return elementAt; }); -/* harmony import */ var _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(222); -/* harmony import */ var _filter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(264); -/* harmony import */ var _throwIfEmpty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(296); -/* harmony import */ var _defaultIfEmpty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(287); -/* harmony import */ var _take__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(297); -/** PURE_IMPORTS_START _util_ArgumentOutOfRangeError,_filter,_throwIfEmpty,_defaultIfEmpty,_take PURE_IMPORTS_END */ - - - - - -function elementAt(index, defaultValue) { - if (index < 0) { - throw new _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_0__["ArgumentOutOfRangeError"](); - } - var hasDefaultValue = arguments.length >= 2; - return function (source) { - return source.pipe(Object(_filter__WEBPACK_IMPORTED_MODULE_1__["filter"])(function (v, i) { return i === index; }), Object(_take__WEBPACK_IMPORTED_MODULE_4__["take"])(1), hasDefaultValue - ? Object(_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_3__["defaultIfEmpty"])(defaultValue) - : Object(_throwIfEmpty__WEBPACK_IMPORTED_MODULE_2__["throwIfEmpty"])(function () { return new _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_0__["ArgumentOutOfRangeError"](); })); - }; -} -//# sourceMappingURL=elementAt.js.map - - -/***/ }), -/* 296 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tap", function() { return tap; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/* harmony import */ var _util_noop__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(156); +/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(144); +/** PURE_IMPORTS_START tslib,_Subscriber,_util_noop,_util_isFunction PURE_IMPORTS_END */ -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "throwIfEmpty", function() { return throwIfEmpty; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _util_EmptyError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(223); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_util_EmptyError,_Subscriber PURE_IMPORTS_END */ -function throwIfEmpty(errorFactory) { - if (errorFactory === void 0) { - errorFactory = defaultErrorFactory; - } - return function (source) { - return source.lift(new ThrowIfEmptyOperator(errorFactory)); +function tap(nextOrObserver, error, complete) { + return function tapOperatorFunction(source) { + return source.lift(new DoOperator(nextOrObserver, error, complete)); }; } -var ThrowIfEmptyOperator = /*@__PURE__*/ (function () { - function ThrowIfEmptyOperator(errorFactory) { - this.errorFactory = errorFactory; +var DoOperator = /*@__PURE__*/ (function () { + function DoOperator(nextOrObserver, error, complete) { + this.nextOrObserver = nextOrObserver; + this.error = error; + this.complete = complete; } - ThrowIfEmptyOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new ThrowIfEmptySubscriber(subscriber, this.errorFactory)); + DoOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete)); }; - return ThrowIfEmptyOperator; + return DoOperator; }()); -var ThrowIfEmptySubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ThrowIfEmptySubscriber, _super); - function ThrowIfEmptySubscriber(destination, errorFactory) { +var TapSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TapSubscriber, _super); + function TapSubscriber(destination, observerOrNext, error, complete) { var _this = _super.call(this, destination) || this; - _this.errorFactory = errorFactory; - _this.hasValue = false; + _this._tapNext = _util_noop__WEBPACK_IMPORTED_MODULE_2__["noop"]; + _this._tapError = _util_noop__WEBPACK_IMPORTED_MODULE_2__["noop"]; + _this._tapComplete = _util_noop__WEBPACK_IMPORTED_MODULE_2__["noop"]; + _this._tapError = error || _util_noop__WEBPACK_IMPORTED_MODULE_2__["noop"]; + _this._tapComplete = complete || _util_noop__WEBPACK_IMPORTED_MODULE_2__["noop"]; + if (Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_3__["isFunction"])(observerOrNext)) { + _this._context = _this; + _this._tapNext = observerOrNext; + } + else if (observerOrNext) { + _this._context = observerOrNext; + _this._tapNext = observerOrNext.next || _util_noop__WEBPACK_IMPORTED_MODULE_2__["noop"]; + _this._tapError = observerOrNext.error || _util_noop__WEBPACK_IMPORTED_MODULE_2__["noop"]; + _this._tapComplete = observerOrNext.complete || _util_noop__WEBPACK_IMPORTED_MODULE_2__["noop"]; + } return _this; } - ThrowIfEmptySubscriber.prototype._next = function (value) { - this.hasValue = true; - this.destination.next(value); - }; - ThrowIfEmptySubscriber.prototype._complete = function () { - if (!this.hasValue) { - var err = void 0; - try { - err = this.errorFactory(); - } - catch (e) { - err = e; - } - this.destination.error(err); + TapSubscriber.prototype._next = function (value) { + try { + this._tapNext.call(this._context, value); } - else { - return this.destination.complete(); + catch (err) { + this.destination.error(err); + return; } + this.destination.next(value); }; - return ThrowIfEmptySubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_2__["Subscriber"])); -function defaultErrorFactory() { - return new _util_EmptyError__WEBPACK_IMPORTED_MODULE_1__["EmptyError"](); -} -//# sourceMappingURL=throwIfEmpty.js.map - - -/***/ }), -/* 297 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "take", function() { return take; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/* harmony import */ var _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(222); -/* harmony import */ var _observable_empty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(203); -/** PURE_IMPORTS_START tslib,_Subscriber,_util_ArgumentOutOfRangeError,_observable_empty PURE_IMPORTS_END */ - - - - -function take(count) { - return function (source) { - if (count === 0) { - return Object(_observable_empty__WEBPACK_IMPORTED_MODULE_3__["empty"])(); + TapSubscriber.prototype._error = function (err) { + try { + this._tapError.call(this._context, err); } - else { - return source.lift(new TakeOperator(count)); + catch (err) { + this.destination.error(err); + return; } + this.destination.error(err); }; -} -var TakeOperator = /*@__PURE__*/ (function () { - function TakeOperator(total) { - this.total = total; - if (this.total < 0) { - throw new _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_2__["ArgumentOutOfRangeError"]; + TapSubscriber.prototype._complete = function () { + try { + this._tapComplete.call(this._context); } - } - TakeOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new TakeSubscriber(subscriber, this.total)); - }; - return TakeOperator; -}()); -var TakeSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TakeSubscriber, _super); - function TakeSubscriber(destination, total) { - var _this = _super.call(this, destination) || this; - _this.total = total; - _this.count = 0; - return _this; - } - TakeSubscriber.prototype._next = function (value) { - var total = this.total; - var count = ++this.count; - if (count <= total) { - this.destination.next(value); - if (count === total) { - this.destination.complete(); - this.unsubscribe(); - } + catch (err) { + this.destination.error(err); + return; } + return this.destination.complete(); }; - return TakeSubscriber; + return TapSubscriber; }(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=take.js.map +//# sourceMappingURL=tap.js.map /***/ }), -/* 298 */ +/* 324 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "endWith", function() { return endWith; }); -/* harmony import */ var _observable_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(239); -/* harmony import */ var _observable_of__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(204); -/** PURE_IMPORTS_START _observable_concat,_observable_of PURE_IMPORTS_END */ - - -function endWith() { - var array = []; - for (var _i = 0; _i < arguments.length; _i++) { - array[_i] = arguments[_i]; - } - return function (source) { return Object(_observable_concat__WEBPACK_IMPORTED_MODULE_0__["concat"])(source, _observable_of__WEBPACK_IMPORTED_MODULE_1__["of"].apply(void 0, array)); }; -} -//# sourceMappingURL=endWith.js.map - - -/***/ }), -/* 299 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultThrottleConfig", function() { return defaultThrottleConfig; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "throttle", function() { return throttle; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "every", function() { return every; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function every(predicate, thisArg) { - return function (source) { return source.lift(new EveryOperator(predicate, thisArg, source)); }; +var defaultThrottleConfig = { + leading: true, + trailing: false +}; +function throttle(durationSelector, config) { + if (config === void 0) { + config = defaultThrottleConfig; + } + return function (source) { return source.lift(new ThrottleOperator(durationSelector, config.leading, config.trailing)); }; } -var EveryOperator = /*@__PURE__*/ (function () { - function EveryOperator(predicate, thisArg, source) { - this.predicate = predicate; - this.thisArg = thisArg; - this.source = source; +var ThrottleOperator = /*@__PURE__*/ (function () { + function ThrottleOperator(durationSelector, leading, trailing) { + this.durationSelector = durationSelector; + this.leading = leading; + this.trailing = trailing; } - EveryOperator.prototype.call = function (observer, source) { - return source.subscribe(new EverySubscriber(observer, this.predicate, this.thisArg, this.source)); + ThrottleOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing)); }; - return EveryOperator; + return ThrottleOperator; }()); -var EverySubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](EverySubscriber, _super); - function EverySubscriber(destination, predicate, thisArg, source) { +var ThrottleSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ThrottleSubscriber, _super); + function ThrottleSubscriber(destination, durationSelector, _leading, _trailing) { var _this = _super.call(this, destination) || this; - _this.predicate = predicate; - _this.thisArg = thisArg; - _this.source = source; - _this.index = 0; - _this.thisArg = thisArg || _this; + _this.destination = destination; + _this.durationSelector = durationSelector; + _this._leading = _leading; + _this._trailing = _trailing; + _this._hasValue = false; return _this; } - EverySubscriber.prototype.notifyComplete = function (everyValueMatch) { - this.destination.next(everyValueMatch); - this.destination.complete(); + ThrottleSubscriber.prototype._next = function (value) { + this._hasValue = true; + this._sendValue = value; + if (!this._throttled) { + if (this._leading) { + this.send(); + } + else { + this.throttle(value); + } + } }; - EverySubscriber.prototype._next = function (value) { - var result = false; + ThrottleSubscriber.prototype.send = function () { + var _a = this, _hasValue = _a._hasValue, _sendValue = _a._sendValue; + if (_hasValue) { + this.destination.next(_sendValue); + this.throttle(_sendValue); + } + this._hasValue = false; + this._sendValue = null; + }; + ThrottleSubscriber.prototype.throttle = function (value) { + var duration = this.tryDurationSelector(value); + if (!!duration) { + this.add(this._throttled = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, duration)); + } + }; + ThrottleSubscriber.prototype.tryDurationSelector = function (value) { try { - result = this.predicate.call(this.thisArg, value, this.index++, this.source); + return this.durationSelector(value); } catch (err) { this.destination.error(err); - return; + return null; } - if (!result) { - this.notifyComplete(false); + }; + ThrottleSubscriber.prototype.throttlingDone = function () { + var _a = this, _throttled = _a._throttled, _trailing = _a._trailing; + if (_throttled) { + _throttled.unsubscribe(); + } + this._throttled = null; + if (_trailing) { + this.send(); } }; - EverySubscriber.prototype._complete = function () { - this.notifyComplete(true); + ThrottleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.throttlingDone(); }; - return EverySubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=every.js.map + ThrottleSubscriber.prototype.notifyComplete = function () { + this.throttlingDone(); + }; + return ThrottleSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); +//# sourceMappingURL=throttle.js.map /***/ }), -/* 300 */ +/* 325 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exhaust", function() { return exhaust; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "throttleTime", function() { return throttleTime; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(186); +/* harmony import */ var _throttle__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(324); +/** PURE_IMPORTS_START tslib,_Subscriber,_scheduler_async,_throttle PURE_IMPORTS_END */ -function exhaust() { - return function (source) { return source.lift(new SwitchFirstOperator()); }; + +function throttleTime(duration, scheduler, config) { + if (scheduler === void 0) { + scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_2__["async"]; + } + if (config === void 0) { + config = _throttle__WEBPACK_IMPORTED_MODULE_3__["defaultThrottleConfig"]; + } + return function (source) { return source.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing)); }; } -var SwitchFirstOperator = /*@__PURE__*/ (function () { - function SwitchFirstOperator() { +var ThrottleTimeOperator = /*@__PURE__*/ (function () { + function ThrottleTimeOperator(duration, scheduler, leading, trailing) { + this.duration = duration; + this.scheduler = scheduler; + this.leading = leading; + this.trailing = trailing; } - SwitchFirstOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new SwitchFirstSubscriber(subscriber)); + ThrottleTimeOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing)); }; - return SwitchFirstOperator; + return ThrottleTimeOperator; }()); -var SwitchFirstSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SwitchFirstSubscriber, _super); - function SwitchFirstSubscriber(destination) { +var ThrottleTimeSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ThrottleTimeSubscriber, _super); + function ThrottleTimeSubscriber(destination, duration, scheduler, leading, trailing) { var _this = _super.call(this, destination) || this; - _this.hasCompleted = false; - _this.hasSubscription = false; + _this.duration = duration; + _this.scheduler = scheduler; + _this.leading = leading; + _this.trailing = trailing; + _this._hasTrailingValue = false; + _this._trailingValue = null; return _this; } - SwitchFirstSubscriber.prototype._next = function (value) { - if (!this.hasSubscription) { - this.hasSubscription = true; - this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, value)); + ThrottleTimeSubscriber.prototype._next = function (value) { + if (this.throttled) { + if (this.trailing) { + this._trailingValue = value; + this._hasTrailingValue = true; + } + } + else { + this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, { subscriber: this })); + if (this.leading) { + this.destination.next(value); + } + else if (this.trailing) { + this._trailingValue = value; + this._hasTrailingValue = true; + } } }; - SwitchFirstSubscriber.prototype._complete = function () { - this.hasCompleted = true; - if (!this.hasSubscription) { + ThrottleTimeSubscriber.prototype._complete = function () { + if (this._hasTrailingValue) { + this.destination.next(this._trailingValue); this.destination.complete(); } - }; - SwitchFirstSubscriber.prototype.notifyComplete = function (innerSub) { - this.remove(innerSub); - this.hasSubscription = false; - if (this.hasCompleted) { + else { this.destination.complete(); } }; - return SwitchFirstSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); -//# sourceMappingURL=exhaust.js.map + ThrottleTimeSubscriber.prototype.clearThrottle = function () { + var throttled = this.throttled; + if (throttled) { + if (this.trailing && this._hasTrailingValue) { + this.destination.next(this._trailingValue); + this._trailingValue = null; + this._hasTrailingValue = false; + } + throttled.unsubscribe(); + this.remove(throttled); + this.throttled = null; + } + }; + return ThrottleTimeSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); +function dispatchNext(arg) { + var subscriber = arg.subscriber; + subscriber.clearThrottle(); +} +//# sourceMappingURL=throttleTime.js.map /***/ }), -/* 301 */ +/* 326 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exhaustMap", function() { return exhaustMap; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(229); -/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(231); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(230); -/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(226); -/* harmony import */ var _observable_from__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(243); -/** PURE_IMPORTS_START tslib,_OuterSubscriber,_InnerSubscriber,_util_subscribeToResult,_map,_observable_from PURE_IMPORTS_END */ - - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timeInterval", function() { return timeInterval; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimeInterval", function() { return TimeInterval; }); +/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(186); +/* harmony import */ var _scan__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(286); +/* harmony import */ var _observable_defer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(221); +/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(197); +/** PURE_IMPORTS_START _scheduler_async,_scan,_observable_defer,_map PURE_IMPORTS_END */ -function exhaustMap(project, resultSelector) { - if (resultSelector) { - return function (source) { return source.pipe(exhaustMap(function (a, i) { return Object(_observable_from__WEBPACK_IMPORTED_MODULE_5__["from"])(project(a, i)).pipe(Object(_map__WEBPACK_IMPORTED_MODULE_4__["map"])(function (b, ii) { return resultSelector(a, b, i, ii); })); })); }; - } - return function (source) { - return source.lift(new ExhaustMapOperator(project)); +function timeInterval(scheduler) { + if (scheduler === void 0) { + scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_0__["async"]; + } + return function (source) { + return Object(_observable_defer__WEBPACK_IMPORTED_MODULE_2__["defer"])(function () { + return source.pipe(Object(_scan__WEBPACK_IMPORTED_MODULE_1__["scan"])(function (_a, value) { + var current = _a.current; + return ({ value: value, current: scheduler.now(), last: current }); + }, { current: scheduler.now(), value: undefined, last: undefined }), Object(_map__WEBPACK_IMPORTED_MODULE_3__["map"])(function (_a) { + var current = _a.current, last = _a.last, value = _a.value; + return new TimeInterval(value, current - last); + })); + }); }; } -var ExhaustMapOperator = /*@__PURE__*/ (function () { - function ExhaustMapOperator(project) { - this.project = project; +var TimeInterval = /*@__PURE__*/ (function () { + function TimeInterval(value, interval) { + this.value = value; + this.interval = interval; } - ExhaustMapOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new ExhaustMapSubscriber(subscriber, this.project)); - }; - return ExhaustMapOperator; + return TimeInterval; }()); -var ExhaustMapSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ExhaustMapSubscriber, _super); - function ExhaustMapSubscriber(destination, project) { - var _this = _super.call(this, destination) || this; - _this.project = project; - _this.hasSubscription = false; - _this.hasCompleted = false; - _this.index = 0; - return _this; - } - ExhaustMapSubscriber.prototype._next = function (value) { - if (!this.hasSubscription) { - this.tryNext(value); - } - }; - ExhaustMapSubscriber.prototype.tryNext = function (value) { - var result; - var index = this.index++; - try { - result = this.project(value, index); - } - catch (err) { - this.destination.error(err); - return; - } - this.hasSubscription = true; - this._innerSub(result, value, index); - }; - ExhaustMapSubscriber.prototype._innerSub = function (result, value, index) { - var innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__["InnerSubscriber"](this, undefined, undefined); - var destination = this.destination; - destination.add(innerSubscriber); - Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(this, result, value, index, innerSubscriber); - }; - ExhaustMapSubscriber.prototype._complete = function () { - this.hasCompleted = true; - if (!this.hasSubscription) { - this.destination.complete(); - } - this.unsubscribe(); - }; - ExhaustMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.destination.next(innerValue); - }; - ExhaustMapSubscriber.prototype.notifyError = function (err) { - this.destination.error(err); - }; - ExhaustMapSubscriber.prototype.notifyComplete = function (innerSub) { - var destination = this.destination; - destination.remove(innerSub); - this.hasSubscription = false; - if (this.hasCompleted) { - this.destination.complete(); - } - }; - return ExhaustMapSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); -//# sourceMappingURL=exhaustMap.js.map + +//# sourceMappingURL=timeInterval.js.map /***/ }), -/* 302 */ +/* 327 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "expand", function() { return expand; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExpandOperator", function() { return ExpandOperator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExpandSubscriber", function() { return ExpandSubscriber; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timeout", function() { return timeout; }); +/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(186); +/* harmony import */ var _util_TimeoutError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(195); +/* harmony import */ var _timeoutWith__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(328); +/* harmony import */ var _observable_throwError__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(180); +/** PURE_IMPORTS_START _scheduler_async,_util_TimeoutError,_timeoutWith,_observable_throwError PURE_IMPORTS_END */ -function expand(project, concurrent, scheduler) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } + +function timeout(due, scheduler) { if (scheduler === void 0) { - scheduler = undefined; + scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_0__["async"]; } - concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent; - return function (source) { return source.lift(new ExpandOperator(project, concurrent, scheduler)); }; + return Object(_timeoutWith__WEBPACK_IMPORTED_MODULE_2__["timeoutWith"])(due, Object(_observable_throwError__WEBPACK_IMPORTED_MODULE_3__["throwError"])(new _util_TimeoutError__WEBPACK_IMPORTED_MODULE_1__["TimeoutError"]()), scheduler); } -var ExpandOperator = /*@__PURE__*/ (function () { - function ExpandOperator(project, concurrent, scheduler) { - this.project = project; - this.concurrent = concurrent; - this.scheduler = scheduler; - } - ExpandOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler)); - }; - return ExpandOperator; -}()); - -var ExpandSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ExpandSubscriber, _super); - function ExpandSubscriber(destination, project, concurrent, scheduler) { - var _this = _super.call(this, destination) || this; - _this.project = project; - _this.concurrent = concurrent; - _this.scheduler = scheduler; - _this.index = 0; - _this.active = 0; - _this.hasCompleted = false; - if (concurrent < Number.POSITIVE_INFINITY) { - _this.buffer = []; - } - return _this; - } - ExpandSubscriber.dispatch = function (arg) { - var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index; - subscriber.subscribeToProjection(result, value, index); - }; - ExpandSubscriber.prototype._next = function (value) { - var destination = this.destination; - if (destination.closed) { - this._complete(); - return; - } - var index = this.index++; - if (this.active < this.concurrent) { - destination.next(value); - try { - var project = this.project; - var result = project(value, index); - if (!this.scheduler) { - this.subscribeToProjection(result, value, index); - } - else { - var state = { subscriber: this, result: result, value: value, index: index }; - var destination_1 = this.destination; - destination_1.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state)); - } - } - catch (e) { - destination.error(e); - } - } - else { - this.buffer.push(value); - } - }; - ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) { - this.active++; - var destination = this.destination; - destination.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, result, value, index)); - }; - ExpandSubscriber.prototype._complete = function () { - this.hasCompleted = true; - if (this.hasCompleted && this.active === 0) { - this.destination.complete(); - } - this.unsubscribe(); - }; - ExpandSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this._next(innerValue); - }; - ExpandSubscriber.prototype.notifyComplete = function (innerSub) { - var buffer = this.buffer; - var destination = this.destination; - destination.remove(innerSub); - this.active--; - if (buffer && buffer.length > 0) { - this._next(buffer.shift()); - } - if (this.hasCompleted && this.active === 0) { - this.destination.complete(); - } - }; - return ExpandSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); - -//# sourceMappingURL=expand.js.map +//# sourceMappingURL=timeout.js.map /***/ }), -/* 303 */ +/* 328 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "finalize", function() { return finalize; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(177); -/** PURE_IMPORTS_START tslib,_Subscriber,_Subscription PURE_IMPORTS_END */ - - - -function finalize(callback) { - return function (source) { return source.lift(new FinallyOperator(callback)); }; -} -var FinallyOperator = /*@__PURE__*/ (function () { - function FinallyOperator(callback) { - this.callback = callback; - } - FinallyOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new FinallySubscriber(subscriber, this.callback)); - }; - return FinallyOperator; -}()); -var FinallySubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FinallySubscriber, _super); - function FinallySubscriber(destination, callback) { - var _this = _super.call(this, destination) || this; - _this.add(new _Subscription__WEBPACK_IMPORTED_MODULE_2__["Subscription"](callback)); - return _this; - } - return FinallySubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=finalize.js.map +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timeoutWith", function() { return timeoutWith; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(186); +/* harmony import */ var _util_isDate__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(260); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_scheduler_async,_util_isDate,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -/***/ }), -/* 304 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "find", function() { return find; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FindValueOperator", function() { return FindValueOperator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FindValueSubscriber", function() { return FindValueSubscriber; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function find(predicate, thisArg) { - if (typeof predicate !== 'function') { - throw new TypeError('predicate is not a function'); +function timeoutWith(due, withObservable, scheduler) { + if (scheduler === void 0) { + scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__["async"]; } - return function (source) { return source.lift(new FindValueOperator(predicate, source, false, thisArg)); }; + return function (source) { + var absoluteTimeout = Object(_util_isDate__WEBPACK_IMPORTED_MODULE_2__["isDate"])(due); + var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due); + return source.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler)); + }; } -var FindValueOperator = /*@__PURE__*/ (function () { - function FindValueOperator(predicate, source, yieldIndex, thisArg) { - this.predicate = predicate; - this.source = source; - this.yieldIndex = yieldIndex; - this.thisArg = thisArg; +var TimeoutWithOperator = /*@__PURE__*/ (function () { + function TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler) { + this.waitFor = waitFor; + this.absoluteTimeout = absoluteTimeout; + this.withObservable = withObservable; + this.scheduler = scheduler; } - FindValueOperator.prototype.call = function (observer, source) { - return source.subscribe(new FindValueSubscriber(observer, this.predicate, this.source, this.yieldIndex, this.thisArg)); + TimeoutWithOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new TimeoutWithSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler)); }; - return FindValueOperator; + return TimeoutWithOperator; }()); - -var FindValueSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FindValueSubscriber, _super); - function FindValueSubscriber(destination, predicate, source, yieldIndex, thisArg) { +var TimeoutWithSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TimeoutWithSubscriber, _super); + function TimeoutWithSubscriber(destination, absoluteTimeout, waitFor, withObservable, scheduler) { var _this = _super.call(this, destination) || this; - _this.predicate = predicate; - _this.source = source; - _this.yieldIndex = yieldIndex; - _this.thisArg = thisArg; - _this.index = 0; + _this.absoluteTimeout = absoluteTimeout; + _this.waitFor = waitFor; + _this.withObservable = withObservable; + _this.scheduler = scheduler; + _this.action = null; + _this.scheduleTimeout(); return _this; } - FindValueSubscriber.prototype.notifyComplete = function (value) { - var destination = this.destination; - destination.next(value); - destination.complete(); - this.unsubscribe(); + TimeoutWithSubscriber.dispatchTimeout = function (subscriber) { + var withObservable = subscriber.withObservable; + subscriber._unsubscribeAndRecycle(); + subscriber.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__["subscribeToResult"])(subscriber, withObservable)); }; - FindValueSubscriber.prototype._next = function (value) { - var _a = this, predicate = _a.predicate, thisArg = _a.thisArg; - var index = this.index++; - try { - var result = predicate.call(thisArg || this, value, index, this.source); - if (result) { - this.notifyComplete(this.yieldIndex ? index : value); - } + TimeoutWithSubscriber.prototype.scheduleTimeout = function () { + var action = this.action; + if (action) { + this.action = action.schedule(this, this.waitFor); } - catch (err) { - this.destination.error(err); + else { + this.add(this.action = this.scheduler.schedule(TimeoutWithSubscriber.dispatchTimeout, this.waitFor, this)); } }; - FindValueSubscriber.prototype._complete = function () { - this.notifyComplete(this.yieldIndex ? -1 : undefined); + TimeoutWithSubscriber.prototype._next = function (value) { + if (!this.absoluteTimeout) { + this.scheduleTimeout(); + } + _super.prototype._next.call(this, value); }; - return FindValueSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); - -//# sourceMappingURL=find.js.map + TimeoutWithSubscriber.prototype._unsubscribe = function () { + this.action = null; + this.scheduler = null; + this.withObservable = null; + }; + return TimeoutWithSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__["OuterSubscriber"])); +//# sourceMappingURL=timeoutWith.js.map /***/ }), -/* 305 */ +/* 329 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findIndex", function() { return findIndex; }); -/* harmony import */ var _operators_find__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(304); -/** PURE_IMPORTS_START _operators_find PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timestamp", function() { return timestamp; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Timestamp", function() { return Timestamp; }); +/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(186); +/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(197); +/** PURE_IMPORTS_START _scheduler_async,_map PURE_IMPORTS_END */ -function findIndex(predicate, thisArg) { - return function (source) { return source.lift(new _operators_find__WEBPACK_IMPORTED_MODULE_0__["FindValueOperator"](predicate, source, true, thisArg)); }; + +function timestamp(scheduler) { + if (scheduler === void 0) { + scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_0__["async"]; + } + return Object(_map__WEBPACK_IMPORTED_MODULE_1__["map"])(function (value) { return new Timestamp(value, scheduler.now()); }); } -//# sourceMappingURL=findIndex.js.map +var Timestamp = /*@__PURE__*/ (function () { + function Timestamp(value, timestamp) { + this.value = value; + this.timestamp = timestamp; + } + return Timestamp; +}()); + +//# sourceMappingURL=timestamp.js.map /***/ }), -/* 306 */ +/* 330 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "first", function() { return first; }); -/* harmony import */ var _util_EmptyError__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(223); -/* harmony import */ var _filter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(264); -/* harmony import */ var _take__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(297); -/* harmony import */ var _defaultIfEmpty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(287); -/* harmony import */ var _throwIfEmpty__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(296); -/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(220); -/** PURE_IMPORTS_START _util_EmptyError,_filter,_take,_defaultIfEmpty,_throwIfEmpty,_util_identity PURE_IMPORTS_END */ - - - - - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toArray", function() { return toArray; }); +/* harmony import */ var _reduce__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(285); +/** PURE_IMPORTS_START _reduce PURE_IMPORTS_END */ -function first(predicate, defaultValue) { - var hasDefaultValue = arguments.length >= 2; - return function (source) { return source.pipe(predicate ? Object(_filter__WEBPACK_IMPORTED_MODULE_1__["filter"])(function (v, i) { return predicate(v, i, source); }) : _util_identity__WEBPACK_IMPORTED_MODULE_5__["identity"], Object(_take__WEBPACK_IMPORTED_MODULE_2__["take"])(1), hasDefaultValue ? Object(_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_3__["defaultIfEmpty"])(defaultValue) : Object(_throwIfEmpty__WEBPACK_IMPORTED_MODULE_4__["throwIfEmpty"])(function () { return new _util_EmptyError__WEBPACK_IMPORTED_MODULE_0__["EmptyError"](); })); }; +function toArrayReducer(arr, item, index) { + if (index === 0) { + return [item]; + } + arr.push(item); + return arr; } -//# sourceMappingURL=first.js.map +function toArray() { + return Object(_reduce__WEBPACK_IMPORTED_MODULE_0__["reduce"])(toArrayReducer, []); +} +//# sourceMappingURL=toArray.js.map /***/ }), -/* 307 */ +/* 331 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ignoreElements", function() { return ignoreElements; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "window", function() { return window; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(158); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_Subject,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function ignoreElements() { - return function ignoreElementsOperatorFunction(source) { - return source.lift(new IgnoreElementsOperator()); + + +function window(windowBoundaries) { + return function windowOperatorFunction(source) { + return source.lift(new WindowOperator(windowBoundaries)); }; } -var IgnoreElementsOperator = /*@__PURE__*/ (function () { - function IgnoreElementsOperator() { +var WindowOperator = /*@__PURE__*/ (function () { + function WindowOperator(windowBoundaries) { + this.windowBoundaries = windowBoundaries; } - IgnoreElementsOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new IgnoreElementsSubscriber(subscriber)); + WindowOperator.prototype.call = function (subscriber, source) { + var windowSubscriber = new WindowSubscriber(subscriber); + var sourceSubscription = source.subscribe(windowSubscriber); + if (!sourceSubscription.closed) { + windowSubscriber.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(windowSubscriber, this.windowBoundaries)); + } + return sourceSubscription; }; - return IgnoreElementsOperator; + return WindowOperator; }()); -var IgnoreElementsSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](IgnoreElementsSubscriber, _super); - function IgnoreElementsSubscriber() { - return _super !== null && _super.apply(this, arguments) || this; +var WindowSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WindowSubscriber, _super); + function WindowSubscriber(destination) { + var _this = _super.call(this, destination) || this; + _this.window = new _Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"](); + destination.next(_this.window); + return _this; } - IgnoreElementsSubscriber.prototype._next = function (unused) { + WindowSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.openWindow(); }; - return IgnoreElementsSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=ignoreElements.js.map - - -/***/ }), -/* 308 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isEmpty", function() { return isEmpty; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ - - -function isEmpty() { - return function (source) { return source.lift(new IsEmptyOperator()); }; -} -var IsEmptyOperator = /*@__PURE__*/ (function () { - function IsEmptyOperator() { - } - IsEmptyOperator.prototype.call = function (observer, source) { - return source.subscribe(new IsEmptySubscriber(observer)); + WindowSubscriber.prototype.notifyError = function (error, innerSub) { + this._error(error); }; - return IsEmptyOperator; -}()); -var IsEmptySubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](IsEmptySubscriber, _super); - function IsEmptySubscriber(destination) { - return _super.call(this, destination) || this; - } - IsEmptySubscriber.prototype.notifyComplete = function (isEmpty) { - var destination = this.destination; - destination.next(isEmpty); - destination.complete(); + WindowSubscriber.prototype.notifyComplete = function (innerSub) { + this._complete(); }; - IsEmptySubscriber.prototype._next = function (value) { - this.notifyComplete(false); + WindowSubscriber.prototype._next = function (value) { + this.window.next(value); }; - IsEmptySubscriber.prototype._complete = function () { - this.notifyComplete(true); + WindowSubscriber.prototype._error = function (err) { + this.window.error(err); + this.destination.error(err); }; - return IsEmptySubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=isEmpty.js.map + WindowSubscriber.prototype._complete = function () { + this.window.complete(); + this.destination.complete(); + }; + WindowSubscriber.prototype._unsubscribe = function () { + this.window = null; + }; + WindowSubscriber.prototype.openWindow = function () { + var prevWindow = this.window; + if (prevWindow) { + prevWindow.complete(); + } + var destination = this.destination; + var newWindow = this.window = new _Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"](); + destination.next(newWindow); + }; + return WindowSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"])); +//# sourceMappingURL=window.js.map /***/ }), -/* 309 */ +/* 332 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "last", function() { return last; }); -/* harmony import */ var _util_EmptyError__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(223); -/* harmony import */ var _filter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(264); -/* harmony import */ var _takeLast__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(310); -/* harmony import */ var _throwIfEmpty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(296); -/* harmony import */ var _defaultIfEmpty__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(287); -/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(220); -/** PURE_IMPORTS_START _util_EmptyError,_filter,_takeLast,_throwIfEmpty,_defaultIfEmpty,_util_identity PURE_IMPORTS_END */ - - - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "windowCount", function() { return windowCount; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(143); +/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(158); +/** PURE_IMPORTS_START tslib,_Subscriber,_Subject PURE_IMPORTS_END */ -function last(predicate, defaultValue) { - var hasDefaultValue = arguments.length >= 2; - return function (source) { return source.pipe(predicate ? Object(_filter__WEBPACK_IMPORTED_MODULE_1__["filter"])(function (v, i) { return predicate(v, i, source); }) : _util_identity__WEBPACK_IMPORTED_MODULE_5__["identity"], Object(_takeLast__WEBPACK_IMPORTED_MODULE_2__["takeLast"])(1), hasDefaultValue ? Object(_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_4__["defaultIfEmpty"])(defaultValue) : Object(_throwIfEmpty__WEBPACK_IMPORTED_MODULE_3__["throwIfEmpty"])(function () { return new _util_EmptyError__WEBPACK_IMPORTED_MODULE_0__["EmptyError"](); })); }; +function windowCount(windowSize, startWindowEvery) { + if (startWindowEvery === void 0) { + startWindowEvery = 0; + } + return function windowCountOperatorFunction(source) { + return source.lift(new WindowCountOperator(windowSize, startWindowEvery)); + }; } -//# sourceMappingURL=last.js.map - - -/***/ }), -/* 310 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "takeLast", function() { return takeLast; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/* harmony import */ var _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(222); -/* harmony import */ var _observable_empty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(203); -/** PURE_IMPORTS_START tslib,_Subscriber,_util_ArgumentOutOfRangeError,_observable_empty PURE_IMPORTS_END */ - - - - -function takeLast(count) { - return function takeLastOperatorFunction(source) { - if (count === 0) { - return Object(_observable_empty__WEBPACK_IMPORTED_MODULE_3__["empty"])(); - } - else { - return source.lift(new TakeLastOperator(count)); - } - }; -} -var TakeLastOperator = /*@__PURE__*/ (function () { - function TakeLastOperator(total) { - this.total = total; - if (this.total < 0) { - throw new _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_2__["ArgumentOutOfRangeError"]; - } +var WindowCountOperator = /*@__PURE__*/ (function () { + function WindowCountOperator(windowSize, startWindowEvery) { + this.windowSize = windowSize; + this.startWindowEvery = startWindowEvery; } - TakeLastOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new TakeLastSubscriber(subscriber, this.total)); + WindowCountOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new WindowCountSubscriber(subscriber, this.windowSize, this.startWindowEvery)); }; - return TakeLastOperator; + return WindowCountOperator; }()); -var TakeLastSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TakeLastSubscriber, _super); - function TakeLastSubscriber(destination, total) { +var WindowCountSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WindowCountSubscriber, _super); + function WindowCountSubscriber(destination, windowSize, startWindowEvery) { var _this = _super.call(this, destination) || this; - _this.total = total; - _this.ring = new Array(); + _this.destination = destination; + _this.windowSize = windowSize; + _this.startWindowEvery = startWindowEvery; + _this.windows = [new _Subject__WEBPACK_IMPORTED_MODULE_2__["Subject"]()]; _this.count = 0; + destination.next(_this.windows[0]); return _this; } - TakeLastSubscriber.prototype._next = function (value) { - var ring = this.ring; - var total = this.total; - var count = this.count++; - if (ring.length < total) { - ring.push(value); + WindowCountSubscriber.prototype._next = function (value) { + var startWindowEvery = (this.startWindowEvery > 0) ? this.startWindowEvery : this.windowSize; + var destination = this.destination; + var windowSize = this.windowSize; + var windows = this.windows; + var len = windows.length; + for (var i = 0; i < len && !this.closed; i++) { + windows[i].next(value); } - else { - var index = count % total; - ring[index] = value; + var c = this.count - windowSize + 1; + if (c >= 0 && c % startWindowEvery === 0 && !this.closed) { + windows.shift().complete(); + } + if (++this.count % startWindowEvery === 0 && !this.closed) { + var window_1 = new _Subject__WEBPACK_IMPORTED_MODULE_2__["Subject"](); + windows.push(window_1); + destination.next(window_1); } }; - TakeLastSubscriber.prototype._complete = function () { - var destination = this.destination; - var count = this.count; - if (count > 0) { - var total = this.count >= this.total ? this.total : this.count; - var ring = this.ring; - for (var i = 0; i < total; i++) { - var idx = (count++) % total; - destination.next(ring[idx]); + WindowCountSubscriber.prototype._error = function (err) { + var windows = this.windows; + if (windows) { + while (windows.length > 0 && !this.closed) { + windows.shift().error(err); } } - destination.complete(); - }; - return TakeLastSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=takeLast.js.map - - -/***/ }), -/* 311 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapTo", function() { return mapTo; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ - - -function mapTo(value) { - return function (source) { return source.lift(new MapToOperator(value)); }; -} -var MapToOperator = /*@__PURE__*/ (function () { - function MapToOperator(value) { - this.value = value; - } - MapToOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new MapToSubscriber(subscriber, this.value)); - }; - return MapToOperator; -}()); -var MapToSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MapToSubscriber, _super); - function MapToSubscriber(destination, value) { - var _this = _super.call(this, destination) || this; - _this.value = value; - return _this; - } - MapToSubscriber.prototype._next = function (x) { - this.destination.next(this.value); - }; - return MapToSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=mapTo.js.map - - -/***/ }), -/* 312 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "materialize", function() { return materialize; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/* harmony import */ var _Notification__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(202); -/** PURE_IMPORTS_START tslib,_Subscriber,_Notification PURE_IMPORTS_END */ - - - -function materialize() { - return function materializeOperatorFunction(source) { - return source.lift(new MaterializeOperator()); - }; -} -var MaterializeOperator = /*@__PURE__*/ (function () { - function MaterializeOperator() { - } - MaterializeOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new MaterializeSubscriber(subscriber)); - }; - return MaterializeOperator; -}()); -var MaterializeSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MaterializeSubscriber, _super); - function MaterializeSubscriber(destination) { - return _super.call(this, destination) || this; - } - MaterializeSubscriber.prototype._next = function (value) { - this.destination.next(_Notification__WEBPACK_IMPORTED_MODULE_2__["Notification"].createNext(value)); + this.destination.error(err); }; - MaterializeSubscriber.prototype._error = function (err) { - var destination = this.destination; - destination.next(_Notification__WEBPACK_IMPORTED_MODULE_2__["Notification"].createError(err)); - destination.complete(); + WindowCountSubscriber.prototype._complete = function () { + var windows = this.windows; + if (windows) { + while (windows.length > 0 && !this.closed) { + windows.shift().complete(); + } + } + this.destination.complete(); }; - MaterializeSubscriber.prototype._complete = function () { - var destination = this.destination; - destination.next(_Notification__WEBPACK_IMPORTED_MODULE_2__["Notification"].createComplete()); - destination.complete(); + WindowCountSubscriber.prototype._unsubscribe = function () { + this.count = 0; + this.windows = null; }; - return MaterializeSubscriber; + return WindowCountSubscriber; }(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=materialize.js.map +//# sourceMappingURL=windowCount.js.map /***/ }), -/* 313 */ +/* 333 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "max", function() { return max; }); -/* harmony import */ var _reduce__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(314); -/** PURE_IMPORTS_START _reduce PURE_IMPORTS_END */ - -function max(comparer) { - var max = (typeof comparer === 'function') - ? function (x, y) { return comparer(x, y) > 0 ? x : y; } - : function (x, y) { return x > y ? x : y; }; - return Object(_reduce__WEBPACK_IMPORTED_MODULE_0__["reduce"])(max); -} -//# sourceMappingURL=max.js.map - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "windowTime", function() { return windowTime; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(158); +/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(186); +/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(143); +/* harmony import */ var _util_isNumeric__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(228); +/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(176); +/** PURE_IMPORTS_START tslib,_Subject,_scheduler_async,_Subscriber,_util_isNumeric,_util_isScheduler PURE_IMPORTS_END */ -/***/ }), -/* 314 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reduce", function() { return reduce; }); -/* harmony import */ var _scan__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(315); -/* harmony import */ var _takeLast__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(310); -/* harmony import */ var _defaultIfEmpty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(287); -/* harmony import */ var _util_pipe__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(184); -/** PURE_IMPORTS_START _scan,_takeLast,_defaultIfEmpty,_util_pipe PURE_IMPORTS_END */ -function reduce(accumulator, seed) { - if (arguments.length >= 2) { - return function reduceOperatorFunctionWithSeed(source) { - return Object(_util_pipe__WEBPACK_IMPORTED_MODULE_3__["pipe"])(Object(_scan__WEBPACK_IMPORTED_MODULE_0__["scan"])(accumulator, seed), Object(_takeLast__WEBPACK_IMPORTED_MODULE_1__["takeLast"])(1), Object(_defaultIfEmpty__WEBPACK_IMPORTED_MODULE_2__["defaultIfEmpty"])(seed))(source); - }; +function windowTime(windowTimeSpan) { + var scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_2__["async"]; + var windowCreationInterval = null; + var maxWindowSize = Number.POSITIVE_INFINITY; + if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_5__["isScheduler"])(arguments[3])) { + scheduler = arguments[3]; } - return function reduceOperatorFunction(source) { - return Object(_util_pipe__WEBPACK_IMPORTED_MODULE_3__["pipe"])(Object(_scan__WEBPACK_IMPORTED_MODULE_0__["scan"])(function (acc, value, index) { return accumulator(acc, value, index + 1); }), Object(_takeLast__WEBPACK_IMPORTED_MODULE_1__["takeLast"])(1))(source); - }; -} -//# sourceMappingURL=reduce.js.map - - -/***/ }), -/* 315 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scan", function() { return scan; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ - - -function scan(accumulator, seed) { - var hasSeed = false; - if (arguments.length >= 2) { - hasSeed = true; + if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_5__["isScheduler"])(arguments[2])) { + scheduler = arguments[2]; } - return function scanOperatorFunction(source) { - return source.lift(new ScanOperator(accumulator, seed, hasSeed)); + else if (Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_4__["isNumeric"])(arguments[2])) { + maxWindowSize = arguments[2]; + } + if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_5__["isScheduler"])(arguments[1])) { + scheduler = arguments[1]; + } + else if (Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_4__["isNumeric"])(arguments[1])) { + windowCreationInterval = arguments[1]; + } + return function windowTimeOperatorFunction(source) { + return source.lift(new WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler)); }; } -var ScanOperator = /*@__PURE__*/ (function () { - function ScanOperator(accumulator, seed, hasSeed) { - if (hasSeed === void 0) { - hasSeed = false; - } - this.accumulator = accumulator; - this.seed = seed; - this.hasSeed = hasSeed; +var WindowTimeOperator = /*@__PURE__*/ (function () { + function WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) { + this.windowTimeSpan = windowTimeSpan; + this.windowCreationInterval = windowCreationInterval; + this.maxWindowSize = maxWindowSize; + this.scheduler = scheduler; } - ScanOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed)); + WindowTimeOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new WindowTimeSubscriber(subscriber, this.windowTimeSpan, this.windowCreationInterval, this.maxWindowSize, this.scheduler)); }; - return ScanOperator; + return WindowTimeOperator; }()); -var ScanSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ScanSubscriber, _super); - function ScanSubscriber(destination, accumulator, _seed, hasSeed) { - var _this = _super.call(this, destination) || this; - _this.accumulator = accumulator; - _this._seed = _seed; - _this.hasSeed = hasSeed; - _this.index = 0; +var CountedSubject = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CountedSubject, _super); + function CountedSubject() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this._numberOfNextedValues = 0; return _this; } - Object.defineProperty(ScanSubscriber.prototype, "seed", { + CountedSubject.prototype.next = function (value) { + this._numberOfNextedValues++; + _super.prototype.next.call(this, value); + }; + Object.defineProperty(CountedSubject.prototype, "numberOfNextedValues", { get: function () { - return this._seed; - }, - set: function (value) { - this.hasSeed = true; - this._seed = value; + return this._numberOfNextedValues; }, enumerable: true, configurable: true }); - ScanSubscriber.prototype._next = function (value) { - if (!this.hasSeed) { - this.seed = value; - this.destination.next(value); + return CountedSubject; +}(_Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"])); +var WindowTimeSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WindowTimeSubscriber, _super); + function WindowTimeSubscriber(destination, windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) { + var _this = _super.call(this, destination) || this; + _this.destination = destination; + _this.windowTimeSpan = windowTimeSpan; + _this.windowCreationInterval = windowCreationInterval; + _this.maxWindowSize = maxWindowSize; + _this.scheduler = scheduler; + _this.windows = []; + var window = _this.openWindow(); + if (windowCreationInterval !== null && windowCreationInterval >= 0) { + var closeState = { subscriber: _this, window: window, context: null }; + var creationState = { windowTimeSpan: windowTimeSpan, windowCreationInterval: windowCreationInterval, subscriber: _this, scheduler: scheduler }; + _this.add(scheduler.schedule(dispatchWindowClose, windowTimeSpan, closeState)); + _this.add(scheduler.schedule(dispatchWindowCreation, windowCreationInterval, creationState)); } else { - return this._tryNext(value); + var timeSpanOnlyState = { subscriber: _this, window: window, windowTimeSpan: windowTimeSpan }; + _this.add(scheduler.schedule(dispatchWindowTimeSpanOnly, windowTimeSpan, timeSpanOnlyState)); + } + return _this; + } + WindowTimeSubscriber.prototype._next = function (value) { + var windows = this.windows; + var len = windows.length; + for (var i = 0; i < len; i++) { + var window_1 = windows[i]; + if (!window_1.closed) { + window_1.next(value); + if (window_1.numberOfNextedValues >= this.maxWindowSize) { + this.closeWindow(window_1); + } + } } }; - ScanSubscriber.prototype._tryNext = function (value) { - var index = this.index++; - var result; - try { - result = this.accumulator(this.seed, value, index); + WindowTimeSubscriber.prototype._error = function (err) { + var windows = this.windows; + while (windows.length > 0) { + windows.shift().error(err); } - catch (err) { - this.destination.error(err); + this.destination.error(err); + }; + WindowTimeSubscriber.prototype._complete = function () { + var windows = this.windows; + while (windows.length > 0) { + var window_2 = windows.shift(); + if (!window_2.closed) { + window_2.complete(); + } } - this.seed = result; - this.destination.next(result); + this.destination.complete(); }; - return ScanSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=scan.js.map - - -/***/ }), -/* 316 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "merge", function() { return merge; }); -/* harmony import */ var _observable_merge__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(258); -/** PURE_IMPORTS_START _observable_merge PURE_IMPORTS_END */ - -function merge() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; + WindowTimeSubscriber.prototype.openWindow = function () { + var window = new CountedSubject(); + this.windows.push(window); + var destination = this.destination; + destination.next(window); + return window; + }; + WindowTimeSubscriber.prototype.closeWindow = function (window) { + window.complete(); + var windows = this.windows; + windows.splice(windows.indexOf(window), 1); + }; + return WindowTimeSubscriber; +}(_Subscriber__WEBPACK_IMPORTED_MODULE_3__["Subscriber"])); +function dispatchWindowTimeSpanOnly(state) { + var subscriber = state.subscriber, windowTimeSpan = state.windowTimeSpan, window = state.window; + if (window) { + subscriber.closeWindow(window); } - return function (source) { return source.lift.call(_observable_merge__WEBPACK_IMPORTED_MODULE_0__["merge"].apply(void 0, [source].concat(observables))); }; + state.window = subscriber.openWindow(); + this.schedule(state, windowTimeSpan); } -//# sourceMappingURL=merge.js.map - - -/***/ }), -/* 317 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeMapTo", function() { return mergeMapTo; }); -/* harmony import */ var _mergeMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(242); -/** PURE_IMPORTS_START _mergeMap PURE_IMPORTS_END */ - -function mergeMapTo(innerObservable, resultSelector, concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - if (typeof resultSelector === 'function') { - return Object(_mergeMap__WEBPACK_IMPORTED_MODULE_0__["mergeMap"])(function () { return innerObservable; }, resultSelector, concurrent); - } - if (typeof resultSelector === 'number') { - concurrent = resultSelector; +function dispatchWindowCreation(state) { + var windowTimeSpan = state.windowTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler, windowCreationInterval = state.windowCreationInterval; + var window = subscriber.openWindow(); + var action = this; + var context = { action: action, subscription: null }; + var timeSpanState = { subscriber: subscriber, window: window, context: context }; + context.subscription = scheduler.schedule(dispatchWindowClose, windowTimeSpan, timeSpanState); + action.add(context.subscription); + action.schedule(state, windowCreationInterval); +} +function dispatchWindowClose(state) { + var subscriber = state.subscriber, window = state.window, context = state.context; + if (context && context.action && context.subscription) { + context.action.remove(context.subscription); } - return Object(_mergeMap__WEBPACK_IMPORTED_MODULE_0__["mergeMap"])(function () { return innerObservable; }, concurrent); + subscriber.closeWindow(window); } -//# sourceMappingURL=mergeMapTo.js.map +//# sourceMappingURL=windowTime.js.map /***/ }), -/* 318 */ +/* 334 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeScan", function() { return mergeScan; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MergeScanOperator", function() { return MergeScanOperator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MergeScanSubscriber", function() { return MergeScanSubscriber; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(230); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(229); -/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(231); -/** PURE_IMPORTS_START tslib,_util_subscribeToResult,_OuterSubscriber,_InnerSubscriber PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "windowToggle", function() { return windowToggle; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(158); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(148); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_Subject,_Subscription,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function mergeScan(accumulator, seed, concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - return function (source) { return source.lift(new MergeScanOperator(accumulator, seed, concurrent)); }; + +function windowToggle(openings, closingSelector) { + return function (source) { return source.lift(new WindowToggleOperator(openings, closingSelector)); }; } -var MergeScanOperator = /*@__PURE__*/ (function () { - function MergeScanOperator(accumulator, seed, concurrent) { - this.accumulator = accumulator; - this.seed = seed; - this.concurrent = concurrent; +var WindowToggleOperator = /*@__PURE__*/ (function () { + function WindowToggleOperator(openings, closingSelector) { + this.openings = openings; + this.closingSelector = closingSelector; } - MergeScanOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new MergeScanSubscriber(subscriber, this.accumulator, this.seed, this.concurrent)); + WindowToggleOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new WindowToggleSubscriber(subscriber, this.openings, this.closingSelector)); }; - return MergeScanOperator; + return WindowToggleOperator; }()); - -var MergeScanSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MergeScanSubscriber, _super); - function MergeScanSubscriber(destination, accumulator, acc, concurrent) { +var WindowToggleSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WindowToggleSubscriber, _super); + function WindowToggleSubscriber(destination, openings, closingSelector) { var _this = _super.call(this, destination) || this; - _this.accumulator = accumulator; - _this.acc = acc; - _this.concurrent = concurrent; - _this.hasValue = false; - _this.hasCompleted = false; - _this.buffer = []; - _this.active = 0; - _this.index = 0; + _this.openings = openings; + _this.closingSelector = closingSelector; + _this.contexts = []; + _this.add(_this.openSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__["subscribeToResult"])(_this, openings, openings)); return _this; } - MergeScanSubscriber.prototype._next = function (value) { - if (this.active < this.concurrent) { - var index = this.index++; - var destination = this.destination; - var ish = void 0; - try { - var accumulator = this.accumulator; - ish = accumulator(this.acc, value, index); + WindowToggleSubscriber.prototype._next = function (value) { + var contexts = this.contexts; + if (contexts) { + var len = contexts.length; + for (var i = 0; i < len; i++) { + contexts[i].window.next(value); } - catch (e) { - return destination.error(e); - } - this.active++; - this._innerSub(ish, value, index); - } - else { - this.buffer.push(value); } }; - MergeScanSubscriber.prototype._innerSub = function (ish, value, index) { - var innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_3__["InnerSubscriber"](this, undefined, undefined); - var destination = this.destination; - destination.add(innerSubscriber); - Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__["subscribeToResult"])(this, ish, value, index, innerSubscriber); - }; - MergeScanSubscriber.prototype._complete = function () { - this.hasCompleted = true; - if (this.active === 0 && this.buffer.length === 0) { - if (this.hasValue === false) { - this.destination.next(this.acc); + WindowToggleSubscriber.prototype._error = function (err) { + var contexts = this.contexts; + this.contexts = null; + if (contexts) { + var len = contexts.length; + var index = -1; + while (++index < len) { + var context_1 = contexts[index]; + context_1.window.error(err); + context_1.subscription.unsubscribe(); } - this.destination.complete(); } - this.unsubscribe(); - }; - MergeScanSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - var destination = this.destination; - this.acc = innerValue; - this.hasValue = true; - destination.next(innerValue); + _super.prototype._error.call(this, err); }; - MergeScanSubscriber.prototype.notifyComplete = function (innerSub) { - var buffer = this.buffer; - var destination = this.destination; - destination.remove(innerSub); - this.active--; - if (buffer.length > 0) { - this._next(buffer.shift()); + WindowToggleSubscriber.prototype._complete = function () { + var contexts = this.contexts; + this.contexts = null; + if (contexts) { + var len = contexts.length; + var index = -1; + while (++index < len) { + var context_2 = contexts[index]; + context_2.window.complete(); + context_2.subscription.unsubscribe(); + } } - else if (this.active === 0 && this.hasCompleted) { - if (this.hasValue === false) { - this.destination.next(this.acc); + _super.prototype._complete.call(this); + }; + WindowToggleSubscriber.prototype._unsubscribe = function () { + var contexts = this.contexts; + this.contexts = null; + if (contexts) { + var len = contexts.length; + var index = -1; + while (++index < len) { + var context_3 = contexts[index]; + context_3.window.unsubscribe(); + context_3.subscription.unsubscribe(); } - this.destination.complete(); } }; - return MergeScanSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"])); - -//# sourceMappingURL=mergeScan.js.map - - -/***/ }), -/* 319 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "min", function() { return min; }); -/* harmony import */ var _reduce__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(314); -/** PURE_IMPORTS_START _reduce PURE_IMPORTS_END */ - -function min(comparer) { - var min = (typeof comparer === 'function') - ? function (x, y) { return comparer(x, y) < 0 ? x : y; } - : function (x, y) { return x < y ? x : y; }; - return Object(_reduce__WEBPACK_IMPORTED_MODULE_0__["reduce"])(min); -} -//# sourceMappingURL=min.js.map - - -/***/ }), -/* 320 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "multicast", function() { return multicast; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MulticastOperator", function() { return MulticastOperator; }); -/* harmony import */ var _observable_ConnectableObservable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(186); -/** PURE_IMPORTS_START _observable_ConnectableObservable PURE_IMPORTS_END */ - -function multicast(subjectOrSubjectFactory, selector) { - return function multicastOperatorFunction(source) { - var subjectFactory; - if (typeof subjectOrSubjectFactory === 'function') { - subjectFactory = subjectOrSubjectFactory; + WindowToggleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + if (outerValue === this.openings) { + var closingNotifier = void 0; + try { + var closingSelector = this.closingSelector; + closingNotifier = closingSelector(innerValue); + } + catch (e) { + return this.error(e); + } + var window_1 = new _Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"](); + var subscription = new _Subscription__WEBPACK_IMPORTED_MODULE_2__["Subscription"](); + var context_4 = { window: window_1, subscription: subscription }; + this.contexts.push(context_4); + var innerSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__["subscribeToResult"])(this, closingNotifier, context_4); + if (innerSubscription.closed) { + this.closeWindow(this.contexts.length - 1); + } + else { + innerSubscription.context = context_4; + subscription.add(innerSubscription); + } + this.destination.next(window_1); } else { - subjectFactory = function subjectFactory() { - return subjectOrSubjectFactory; - }; + this.closeWindow(this.contexts.indexOf(outerValue)); } - if (typeof selector === 'function') { - return source.lift(new MulticastOperator(subjectFactory, selector)); + }; + WindowToggleSubscriber.prototype.notifyError = function (err) { + this.error(err); + }; + WindowToggleSubscriber.prototype.notifyComplete = function (inner) { + if (inner !== this.openSubscription) { + this.closeWindow(this.contexts.indexOf(inner.context)); } - var connectable = Object.create(source, _observable_ConnectableObservable__WEBPACK_IMPORTED_MODULE_0__["connectableObservableDescriptor"]); - connectable.source = source; - connectable.subjectFactory = subjectFactory; - return connectable; }; -} -var MulticastOperator = /*@__PURE__*/ (function () { - function MulticastOperator(subjectFactory, selector) { - this.subjectFactory = subjectFactory; - this.selector = selector; - } - MulticastOperator.prototype.call = function (subscriber, source) { - var selector = this.selector; - var subject = this.subjectFactory(); - var subscription = selector(subject).subscribe(subscriber); - subscription.add(source.subscribe(subject)); - return subscription; + WindowToggleSubscriber.prototype.closeWindow = function (index) { + if (index === -1) { + return; + } + var contexts = this.contexts; + var context = contexts[index]; + var window = context.window, subscription = context.subscription; + contexts.splice(index, 1); + window.complete(); + subscription.unsubscribe(); }; - return MulticastOperator; -}()); - -//# sourceMappingURL=multicast.js.map + return WindowToggleSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__["OuterSubscriber"])); +//# sourceMappingURL=windowToggle.js.map /***/ }), -/* 321 */ +/* 335 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onErrorResumeNext", function() { return onErrorResumeNext; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onErrorResumeNextStatic", function() { return onErrorResumeNextStatic; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _observable_from__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(243); -/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(178); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(229); -/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(231); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_observable_from,_util_isArray,_OuterSubscriber,_InnerSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ - - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "windowWhen", function() { return windowWhen; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(158); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_Subject,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function onErrorResumeNext() { - var nextSources = []; - for (var _i = 0; _i < arguments.length; _i++) { - nextSources[_i] = arguments[_i]; - } - if (nextSources.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_2__["isArray"])(nextSources[0])) { - nextSources = nextSources[0]; - } - return function (source) { return source.lift(new OnErrorResumeNextOperator(nextSources)); }; -} -function onErrorResumeNextStatic() { - var nextSources = []; - for (var _i = 0; _i < arguments.length; _i++) { - nextSources[_i] = arguments[_i]; - } - var source = null; - if (nextSources.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_2__["isArray"])(nextSources[0])) { - nextSources = nextSources[0]; - } - source = nextSources.shift(); - return Object(_observable_from__WEBPACK_IMPORTED_MODULE_1__["from"])(source, null).lift(new OnErrorResumeNextOperator(nextSources)); +function windowWhen(closingSelector) { + return function windowWhenOperatorFunction(source) { + return source.lift(new WindowOperator(closingSelector)); + }; } -var OnErrorResumeNextOperator = /*@__PURE__*/ (function () { - function OnErrorResumeNextOperator(nextSources) { - this.nextSources = nextSources; +var WindowOperator = /*@__PURE__*/ (function () { + function WindowOperator(closingSelector) { + this.closingSelector = closingSelector; } - OnErrorResumeNextOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new OnErrorResumeNextSubscriber(subscriber, this.nextSources)); + WindowOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new WindowSubscriber(subscriber, this.closingSelector)); }; - return OnErrorResumeNextOperator; + return WindowOperator; }()); -var OnErrorResumeNextSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](OnErrorResumeNextSubscriber, _super); - function OnErrorResumeNextSubscriber(destination, nextSources) { +var WindowSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WindowSubscriber, _super); + function WindowSubscriber(destination, closingSelector) { var _this = _super.call(this, destination) || this; _this.destination = destination; - _this.nextSources = nextSources; + _this.closingSelector = closingSelector; + _this.openWindow(); return _this; } - OnErrorResumeNextSubscriber.prototype.notifyError = function (error, innerSub) { - this.subscribeToNextSource(); + WindowSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.openWindow(innerSub); }; - OnErrorResumeNextSubscriber.prototype.notifyComplete = function (innerSub) { - this.subscribeToNextSource(); + WindowSubscriber.prototype.notifyError = function (error, innerSub) { + this._error(error); }; - OnErrorResumeNextSubscriber.prototype._error = function (err) { - this.subscribeToNextSource(); - this.unsubscribe(); + WindowSubscriber.prototype.notifyComplete = function (innerSub) { + this.openWindow(innerSub); }; - OnErrorResumeNextSubscriber.prototype._complete = function () { - this.subscribeToNextSource(); - this.unsubscribe(); + WindowSubscriber.prototype._next = function (value) { + this.window.next(value); }; - OnErrorResumeNextSubscriber.prototype.subscribeToNextSource = function () { - var next = this.nextSources.shift(); - if (!!next) { - var innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_4__["InnerSubscriber"](this, undefined, undefined); - var destination = this.destination; - destination.add(innerSubscriber); - Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_5__["subscribeToResult"])(this, next, undefined, undefined, innerSubscriber); + WindowSubscriber.prototype._error = function (err) { + this.window.error(err); + this.destination.error(err); + this.unsubscribeClosingNotification(); + }; + WindowSubscriber.prototype._complete = function () { + this.window.complete(); + this.destination.complete(); + this.unsubscribeClosingNotification(); + }; + WindowSubscriber.prototype.unsubscribeClosingNotification = function () { + if (this.closingNotification) { + this.closingNotification.unsubscribe(); } - else { - this.destination.complete(); + }; + WindowSubscriber.prototype.openWindow = function (innerSub) { + if (innerSub === void 0) { + innerSub = null; + } + if (innerSub) { + this.remove(innerSub); + innerSub.unsubscribe(); + } + var prevWindow = this.window; + if (prevWindow) { + prevWindow.complete(); + } + var window = this.window = new _Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"](); + this.destination.next(window); + var closingNotifier; + try { + var closingSelector = this.closingSelector; + closingNotifier = closingSelector(); + } + catch (e) { + this.destination.error(e); + this.window.error(e); + return; } + this.add(this.closingNotification = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(this, closingNotifier)); }; - return OnErrorResumeNextSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__["OuterSubscriber"])); -//# sourceMappingURL=onErrorResumeNext.js.map + return WindowSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"])); +//# sourceMappingURL=windowWhen.js.map /***/ }), -/* 322 */ +/* 336 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pairwise", function() { return pairwise; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withLatestFrom", function() { return withLatestFrom; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(200); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(201); +/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function pairwise() { - return function (source) { return source.lift(new PairwiseOperator()); }; + +function withLatestFrom() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return function (source) { + var project; + if (typeof args[args.length - 1] === 'function') { + project = args.pop(); + } + var observables = args; + return source.lift(new WithLatestFromOperator(observables, project)); + }; } -var PairwiseOperator = /*@__PURE__*/ (function () { - function PairwiseOperator() { +var WithLatestFromOperator = /*@__PURE__*/ (function () { + function WithLatestFromOperator(observables, project) { + this.observables = observables; + this.project = project; } - PairwiseOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new PairwiseSubscriber(subscriber)); + WithLatestFromOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project)); }; - return PairwiseOperator; + return WithLatestFromOperator; }()); -var PairwiseSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PairwiseSubscriber, _super); - function PairwiseSubscriber(destination) { +var WithLatestFromSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WithLatestFromSubscriber, _super); + function WithLatestFromSubscriber(destination, observables, project) { var _this = _super.call(this, destination) || this; - _this.hasPrev = false; + _this.observables = observables; + _this.project = project; + _this.toRespond = []; + var len = observables.length; + _this.values = new Array(len); + for (var i = 0; i < len; i++) { + _this.toRespond.push(i); + } + for (var i = 0; i < len; i++) { + var observable = observables[i]; + _this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(_this, observable, observable, i)); + } return _this; } - PairwiseSubscriber.prototype._next = function (value) { - var pair; - if (this.hasPrev) { - pair = [this.prev, value]; - } - else { - this.hasPrev = true; + WithLatestFromSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.values[outerIndex] = innerValue; + var toRespond = this.toRespond; + if (toRespond.length > 0) { + var found = toRespond.indexOf(outerIndex); + if (found !== -1) { + toRespond.splice(found, 1); + } } - this.prev = value; - if (pair) { - this.destination.next(pair); + }; + WithLatestFromSubscriber.prototype.notifyComplete = function () { + }; + WithLatestFromSubscriber.prototype._next = function (value) { + if (this.toRespond.length === 0) { + var args = [value].concat(this.values); + if (this.project) { + this._tryProject(args); + } + else { + this.destination.next(args); + } } }; - return PairwiseSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=pairwise.js.map - - -/***/ }), -/* 323 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "partition", function() { return partition; }); -/* harmony import */ var _util_not__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(263); -/* harmony import */ var _filter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(264); -/** PURE_IMPORTS_START _util_not,_filter PURE_IMPORTS_END */ - - -function partition(predicate, thisArg) { - return function (source) { - return [ - Object(_filter__WEBPACK_IMPORTED_MODULE_1__["filter"])(predicate, thisArg)(source), - Object(_filter__WEBPACK_IMPORTED_MODULE_1__["filter"])(Object(_util_not__WEBPACK_IMPORTED_MODULE_0__["not"])(predicate, thisArg))(source) - ]; + WithLatestFromSubscriber.prototype._tryProject = function (args) { + var result; + try { + result = this.project.apply(this, args); + } + catch (err) { + this.destination.error(err); + return; + } + this.destination.next(result); }; -} -//# sourceMappingURL=partition.js.map + return WithLatestFromSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); +//# sourceMappingURL=withLatestFrom.js.map /***/ }), -/* 324 */ +/* 337 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pluck", function() { return pluck; }); -/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(226); -/** PURE_IMPORTS_START _map PURE_IMPORTS_END */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "zip", function() { return zip; }); +/* harmony import */ var _observable_zip__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(240); +/** PURE_IMPORTS_START _observable_zip PURE_IMPORTS_END */ -function pluck() { - var properties = []; +function zip() { + var observables = []; for (var _i = 0; _i < arguments.length; _i++) { - properties[_i] = arguments[_i]; - } - var length = properties.length; - if (length === 0) { - throw new Error('list of properties cannot be empty.'); + observables[_i] = arguments[_i]; } - return function (source) { return Object(_map__WEBPACK_IMPORTED_MODULE_0__["map"])(plucker(properties, length))(source); }; -} -function plucker(props, length) { - var mapper = function (x) { - var currentProp = x; - for (var i = 0; i < length; i++) { - var p = currentProp[props[i]]; - if (typeof p !== 'undefined') { - currentProp = p; - } - else { - return undefined; - } - } - return currentProp; + return function zipOperatorFunction(source) { + return source.lift.call(_observable_zip__WEBPACK_IMPORTED_MODULE_0__["zip"].apply(void 0, [source].concat(observables))); }; - return mapper; } -//# sourceMappingURL=pluck.js.map +//# sourceMappingURL=zip.js.map /***/ }), -/* 325 */ +/* 338 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "publish", function() { return publish; }); -/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(187); -/* harmony import */ var _multicast__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(320); -/** PURE_IMPORTS_START _Subject,_multicast PURE_IMPORTS_END */ - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "zipAll", function() { return zipAll; }); +/* harmony import */ var _observable_zip__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(240); +/** PURE_IMPORTS_START _observable_zip PURE_IMPORTS_END */ -function publish(selector) { - return selector ? - Object(_multicast__WEBPACK_IMPORTED_MODULE_1__["multicast"])(function () { return new _Subject__WEBPACK_IMPORTED_MODULE_0__["Subject"](); }, selector) : - Object(_multicast__WEBPACK_IMPORTED_MODULE_1__["multicast"])(new _Subject__WEBPACK_IMPORTED_MODULE_0__["Subject"]()); +function zipAll(project) { + return function (source) { return source.lift(new _observable_zip__WEBPACK_IMPORTED_MODULE_0__["ZipOperator"](project)); }; } -//# sourceMappingURL=publish.js.map +//# sourceMappingURL=zipAll.js.map /***/ }), -/* 326 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 339 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "publishBehavior", function() { return publishBehavior; }); -/* harmony import */ var _BehaviorSubject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(192); -/* harmony import */ var _multicast__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(320); -/** PURE_IMPORTS_START _BehaviorSubject,_multicast PURE_IMPORTS_END */ - -function publishBehavior(value) { - return function (source) { return Object(_multicast__WEBPACK_IMPORTED_MODULE_1__["multicast"])(new _BehaviorSubject__WEBPACK_IMPORTED_MODULE_0__["BehaviorSubject"](value))(source); }; -} -//# sourceMappingURL=publishBehavior.js.map +const callbacks = new Set(); +let called = false; -/***/ }), -/* 327 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +function exit(exit, signal) { + if (called) { + return; + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "publishLast", function() { return publishLast; }); -/* harmony import */ var _AsyncSubject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(210); -/* harmony import */ var _multicast__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(320); -/** PURE_IMPORTS_START _AsyncSubject,_multicast PURE_IMPORTS_END */ + called = true; + for (const callback of callbacks) { + callback(); + } -function publishLast() { - return function (source) { return Object(_multicast__WEBPACK_IMPORTED_MODULE_1__["multicast"])(new _AsyncSubject__WEBPACK_IMPORTED_MODULE_0__["AsyncSubject"]())(source); }; + if (exit === true) { + process.exit(128 + signal); // eslint-disable-line unicorn/no-process-exit + } } -//# sourceMappingURL=publishLast.js.map +module.exports = callback => { + callbacks.add(callback); -/***/ }), -/* 328 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "publishReplay", function() { return publishReplay; }); -/* harmony import */ var _ReplaySubject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(193); -/* harmony import */ var _multicast__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(320); -/** PURE_IMPORTS_START _ReplaySubject,_multicast PURE_IMPORTS_END */ + if (callbacks.size === 1) { + process.once('exit', exit); + process.once('SIGINT', exit.bind(null, true, 2)); + process.once('SIGTERM', exit.bind(null, true, 15)); + // PM2 Cluster shutdown message. Caught to support async handlers with pm2, needed because + // explicitly calling process.exit() doesn't trigger the beforeExit event, and the exit + // event cannot support async handlers, since the event loop is never called after it. + process.on('message', message => { + if (message === 'shutdown') { + exit(true, -128); + } + }); + } -function publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler) { - if (selectorOrScheduler && typeof selectorOrScheduler !== 'function') { - scheduler = selectorOrScheduler; - } - var selector = typeof selectorOrScheduler === 'function' ? selectorOrScheduler : undefined; - var subject = new _ReplaySubject__WEBPACK_IMPORTED_MODULE_0__["ReplaySubject"](bufferSize, windowTime, scheduler); - return function (source) { return Object(_multicast__WEBPACK_IMPORTED_MODULE_1__["multicast"])(function () { return subject; }, selector)(source); }; -} -//# sourceMappingURL=publishReplay.js.map + return () => { + callbacks.delete(callback); + }; +}; /***/ }), -/* 329 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 340 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "race", function() { return race; }); -/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(178); -/* harmony import */ var _observable_race__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(265); -/** PURE_IMPORTS_START _util_isArray,_observable_race PURE_IMPORTS_END */ - -function race() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; - } - return function raceOperatorFunction(source) { - if (observables.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_0__["isArray"])(observables[0])) { - observables = observables[0]; - } - return source.lift.call(_observable_race__WEBPACK_IMPORTED_MODULE_1__["race"].apply(void 0, [source].concat(observables))); - }; +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const $isCliError = Symbol('isCliError'); +function createCliError(message) { + const error = new Error(message); + error[$isCliError] = true; + return error; } -//# sourceMappingURL=race.js.map +exports.createCliError = createCliError; +function isCliError(error) { + return error && !!error[$isCliError]; +} +exports.isCliError = isCliError; /***/ }), -/* 330 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 341 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "repeat", function() { return repeat; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/* harmony import */ var _observable_empty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(203); -/** PURE_IMPORTS_START tslib,_Subscriber,_observable_empty PURE_IMPORTS_END */ - - -function repeat(count) { - if (count === void 0) { - count = -1; +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = __webpack_require__(6); +const execa_1 = tslib_1.__importDefault(__webpack_require__(342)); +const fs_1 = __webpack_require__(349); +const Rx = tslib_1.__importStar(__webpack_require__(140)); +const operators_1 = __webpack_require__(241); +const chalk_1 = tslib_1.__importDefault(__webpack_require__(386)); +const tree_kill_1 = tslib_1.__importDefault(__webpack_require__(396)); +const util_1 = __webpack_require__(397); +const treeKillAsync = util_1.promisify((...args) => tree_kill_1.default(...args)); +const observe_lines_1 = __webpack_require__(398); +const errors_1 = __webpack_require__(340); +const SECOND = 1000; +const STOP_TIMEOUT = 30 * SECOND; +async function withTimeout(attempt, ms, onTimeout) { + const TIMEOUT = Symbol('timeout'); + try { + await Promise.race([ + attempt(), + new Promise((_, reject) => setTimeout(() => reject(TIMEOUT), ms)), + ]); } - return function (source) { - if (count === 0) { - return Object(_observable_empty__WEBPACK_IMPORTED_MODULE_2__["empty"])(); - } - else if (count < 0) { - return source.lift(new RepeatOperator(-1, source)); + catch (error) { + if (error === TIMEOUT) { + await onTimeout(); } else { - return source.lift(new RepeatOperator(count - 1, source)); + throw error; } - }; -} -var RepeatOperator = /*@__PURE__*/ (function () { - function RepeatOperator(count, source) { - this.count = count; - this.source = source; } - RepeatOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new RepeatSubscriber(subscriber, this.count, this.source)); - }; - return RepeatOperator; -}()); -var RepeatSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RepeatSubscriber, _super); - function RepeatSubscriber(destination, count, source) { - var _this = _super.call(this, destination) || this; - _this.count = count; - _this.source = source; - return _this; +} +function startProc(name, options, log) { + const { cmd, args, cwd, env, stdin } = options; + log.info('[%s] > %s', name, cmd, args.join(' ')); + // spawn fails with ENOENT when either the + // cmd or cwd don't exist, so we check for the cwd + // ahead of time so that the error is less ambiguous + try { + if (!fs_1.statSync(cwd).isDirectory()) { + throw new Error(`cwd "${cwd}" exists but is not a directory`); + } } - RepeatSubscriber.prototype.complete = function () { - if (!this.isStopped) { - var _a = this, source = _a.source, count = _a.count; - if (count === 0) { - return _super.prototype.complete.call(this); - } - else if (count > -1) { - this.count = count - 1; - } - source.subscribe(this._unsubscribeAndRecycle()); + catch (err) { + if (err.code === 'ENOENT') { + throw new Error(`cwd "${cwd}" does not exist`); } - }; - return RepeatSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=repeat.js.map - - -/***/ }), -/* 331 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "repeatWhen", function() { return repeatWhen; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(187); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_Subject,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ - - - - -function repeatWhen(notifier) { - return function (source) { return source.lift(new RepeatWhenOperator(notifier)); }; -} -var RepeatWhenOperator = /*@__PURE__*/ (function () { - function RepeatWhenOperator(notifier) { - this.notifier = notifier; } - RepeatWhenOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new RepeatWhenSubscriber(subscriber, this.notifier, source)); - }; - return RepeatWhenOperator; -}()); -var RepeatWhenSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RepeatWhenSubscriber, _super); - function RepeatWhenSubscriber(destination, notifier, source) { - var _this = _super.call(this, destination) || this; - _this.notifier = notifier; - _this.source = source; - _this.sourceIsBeingSubscribedTo = true; - return _this; + const childProcess = execa_1.default(cmd, args, { + cwd, + env, + stdio: ['pipe', 'pipe', 'pipe'], + preferLocal: true, + }); + if (stdin) { + childProcess.stdin.end(stdin, 'utf8'); } - RepeatWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.sourceIsBeingSubscribedTo = true; - this.source.subscribe(this); - }; - RepeatWhenSubscriber.prototype.notifyComplete = function (innerSub) { - if (this.sourceIsBeingSubscribedTo === false) { - return _super.prototype.complete.call(this); - } - }; - RepeatWhenSubscriber.prototype.complete = function () { - this.sourceIsBeingSubscribedTo = false; - if (!this.isStopped) { - if (!this.retries) { - this.subscribeToRetries(); - } - if (!this.retriesSubscription || this.retriesSubscription.closed) { - return _super.prototype.complete.call(this); - } - this._unsubscribeAndRecycle(); - this.notifications.next(); - } - }; - RepeatWhenSubscriber.prototype._unsubscribe = function () { - var _a = this, notifications = _a.notifications, retriesSubscription = _a.retriesSubscription; - if (notifications) { - notifications.unsubscribe(); - this.notifications = null; - } - if (retriesSubscription) { - retriesSubscription.unsubscribe(); - this.retriesSubscription = null; + else { + childProcess.stdin.end(); + } + let stopCalled = false; + const outcome$ = Rx.race( + // observe first exit event + Rx.fromEvent(childProcess, 'exit').pipe(operators_1.take(1), operators_1.map(([code]) => { + if (stopCalled) { + return null; } - this.retries = null; - }; - RepeatWhenSubscriber.prototype._unsubscribeAndRecycle = function () { - var _unsubscribe = this._unsubscribe; - this._unsubscribe = null; - _super.prototype._unsubscribeAndRecycle.call(this); - this._unsubscribe = _unsubscribe; - return this; - }; - RepeatWhenSubscriber.prototype.subscribeToRetries = function () { - this.notifications = new _Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"](); - var retries; - try { - var notifier = this.notifier; - retries = notifier(this.notifications); + // JVM exits with 143 on SIGTERM and 130 on SIGINT, dont' treat then as errors + if (code > 0 && !(code === 143 || code === 130)) { + throw errors_1.createCliError(`[${name}] exited with code ${code}`); } - catch (e) { - return _super.prototype.complete.call(this); + return code; + })), + // observe first error event + Rx.fromEvent(childProcess, 'error').pipe(operators_1.take(1), operators_1.mergeMap((err) => Rx.throwError(err)))).pipe(operators_1.share()); + const lines$ = Rx.merge(observe_lines_1.observeLines(childProcess.stdout), observe_lines_1.observeLines(childProcess.stderr)).pipe(operators_1.tap((line) => log.write(` ${chalk_1.default.gray('proc')} [${chalk_1.default.gray(name)}] ${line}`)), operators_1.share()); + const outcomePromise = Rx.merge(lines$.pipe(operators_1.ignoreElements()), outcome$).toPromise(); + async function stop(signal) { + if (stopCalled) { + return; } - this.retries = retries; - this.retriesSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(this, retries); + stopCalled = true; + await withTimeout(async () => { + log.debug(`Sending "${signal}" to proc "${name}"`); + await treeKillAsync(childProcess.pid, signal); + await outcomePromise; + }, STOP_TIMEOUT, async () => { + log.warning(`Proc "${name}" was sent "${signal}" didn't emit the "exit" or "error" events after ${STOP_TIMEOUT} ms, sending SIGKILL`); + await treeKillAsync(childProcess.pid, 'SIGKILL'); + }); + await withTimeout(async () => { + try { + await outcomePromise; + } + catch (error) { + // ignore + } + }, STOP_TIMEOUT, async () => { + throw new Error(`Proc "${name}" was stopped but never emitted either the "exit" or "error" event after ${STOP_TIMEOUT} ms`); + }); + } + return { + name, + lines$, + outcome$, + outcomePromise, + stop, }; - return RepeatWhenSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"])); -//# sourceMappingURL=repeatWhen.js.map +} +exports.startProc = startProc; /***/ }), -/* 332 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 342 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "retry", function() { return retry; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +const path = __webpack_require__(4); +const childProcess = __webpack_require__(343); +const crossSpawn = __webpack_require__(344); +const stripFinalNewline = __webpack_require__(358); +const npmRunPath = __webpack_require__(359); +const onetime = __webpack_require__(360); +const makeError = __webpack_require__(362); +const normalizeStdio = __webpack_require__(368); +const {spawnedKill, spawnedCancel, setupTimeout, setExitHandler} = __webpack_require__(369); +const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = __webpack_require__(374); +const {mergePromise, getSpawnedPromise} = __webpack_require__(384); +const {joinCommand, parseCommand} = __webpack_require__(385); -function retry(count) { - if (count === void 0) { - count = -1; - } - return function (source) { return source.lift(new RetryOperator(count, source)); }; -} -var RetryOperator = /*@__PURE__*/ (function () { - function RetryOperator(count, source) { - this.count = count; - this.source = source; - } - RetryOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new RetrySubscriber(subscriber, this.count, this.source)); - }; - return RetryOperator; -}()); -var RetrySubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RetrySubscriber, _super); - function RetrySubscriber(destination, count, source) { - var _this = _super.call(this, destination) || this; - _this.count = count; - _this.source = source; - return _this; - } - RetrySubscriber.prototype.error = function (err) { - if (!this.isStopped) { - var _a = this, source = _a.source, count = _a.count; - if (count === 0) { - return _super.prototype.error.call(this, err); - } - else if (count > -1) { - this.count = count - 1; - } - source.subscribe(this._unsubscribeAndRecycle()); - } - }; - return RetrySubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=retry.js.map +const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100; +const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => { + const env = extendEnv ? {...process.env, ...envOption} : envOption; -/***/ }), -/* 333 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + if (preferLocal) { + return npmRunPath.env({env, cwd: localDir, execPath}); + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "retryWhen", function() { return retryWhen; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(187); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_Subject,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ + return env; +}; +const handleArgs = (file, args, options = {}) => { + const parsed = crossSpawn._parse(file, args, options); + file = parsed.command; + args = parsed.args; + options = parsed.options; + options = { + maxBuffer: DEFAULT_MAX_BUFFER, + buffer: true, + stripFinalNewline: true, + extendEnv: true, + preferLocal: false, + localDir: options.cwd || process.cwd(), + execPath: process.execPath, + encoding: 'utf8', + reject: true, + cleanup: true, + all: false, + windowsHide: true, + ...options + }; + options.env = getEnv(options); -function retryWhen(notifier) { - return function (source) { return source.lift(new RetryWhenOperator(notifier, source)); }; -} -var RetryWhenOperator = /*@__PURE__*/ (function () { - function RetryWhenOperator(notifier, source) { - this.notifier = notifier; - this.source = source; - } - RetryWhenOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new RetryWhenSubscriber(subscriber, this.notifier, this.source)); - }; - return RetryWhenOperator; -}()); -var RetryWhenSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RetryWhenSubscriber, _super); - function RetryWhenSubscriber(destination, notifier, source) { - var _this = _super.call(this, destination) || this; - _this.notifier = notifier; - _this.source = source; - return _this; - } - RetryWhenSubscriber.prototype.error = function (err) { - if (!this.isStopped) { - var errors = this.errors; - var retries = this.retries; - var retriesSubscription = this.retriesSubscription; - if (!retries) { - errors = new _Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"](); - try { - var notifier = this.notifier; - retries = notifier(errors); - } - catch (e) { - return _super.prototype.error.call(this, e); - } - retriesSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(this, retries); - } - else { - this.errors = null; - this.retriesSubscription = null; - } - this._unsubscribeAndRecycle(); - this.errors = errors; - this.retries = retries; - this.retriesSubscription = retriesSubscription; - errors.next(err); - } - }; - RetryWhenSubscriber.prototype._unsubscribe = function () { - var _a = this, errors = _a.errors, retriesSubscription = _a.retriesSubscription; - if (errors) { - errors.unsubscribe(); - this.errors = null; - } - if (retriesSubscription) { - retriesSubscription.unsubscribe(); - this.retriesSubscription = null; - } - this.retries = null; - }; - RetryWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - var _unsubscribe = this._unsubscribe; - this._unsubscribe = null; - this._unsubscribeAndRecycle(); - this._unsubscribe = _unsubscribe; - this.source.subscribe(this); - }; - return RetryWhenSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"])); -//# sourceMappingURL=retryWhen.js.map + options.stdio = normalizeStdio(options); + if (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') { + // #116 + args.unshift('/q'); + } -/***/ }), -/* 334 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + return {file, args, options, parsed}; +}; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sample", function() { return sample; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ +const handleOutput = (options, value, error) => { + if (typeof value !== 'string' && !Buffer.isBuffer(value)) { + // When `execa.sync()` errors, we normalize it to '' to mimic `execa()` + return error === undefined ? undefined : ''; + } + if (options.stripFinalNewline) { + return stripFinalNewline(value); + } + return value; +}; -function sample(notifier) { - return function (source) { return source.lift(new SampleOperator(notifier)); }; -} -var SampleOperator = /*@__PURE__*/ (function () { - function SampleOperator(notifier) { - this.notifier = notifier; - } - SampleOperator.prototype.call = function (subscriber, source) { - var sampleSubscriber = new SampleSubscriber(subscriber); - var subscription = source.subscribe(sampleSubscriber); - subscription.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(sampleSubscriber, this.notifier)); - return subscription; - }; - return SampleOperator; -}()); -var SampleSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SampleSubscriber, _super); - function SampleSubscriber() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.hasValue = false; - return _this; - } - SampleSubscriber.prototype._next = function (value) { - this.value = value; - this.hasValue = true; - }; - SampleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.emitValue(); - }; - SampleSubscriber.prototype.notifyComplete = function () { - this.emitValue(); - }; - SampleSubscriber.prototype.emitValue = function () { - if (this.hasValue) { - this.hasValue = false; - this.destination.next(this.value); - } - }; - return SampleSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); -//# sourceMappingURL=sample.js.map +const execa = (file, args, options) => { + const parsed = handleArgs(file, args, options); + const command = joinCommand(file, args); + let spawned; + try { + spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options); + } catch (error) { + // Ensure the returned error is always both a promise and a child process + const dummySpawned = new childProcess.ChildProcess(); + const errorPromise = Promise.reject(makeError({ + error, + stdout: '', + stderr: '', + all: '', + command, + parsed, + timedOut: false, + isCanceled: false, + killed: false + })); + return mergePromise(dummySpawned, errorPromise); + } -/***/ }), -/* 335 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + const spawnedPromise = getSpawnedPromise(spawned); + const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise); + const processDone = setExitHandler(spawned, parsed.options, timedPromise); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sampleTime", function() { return sampleTime; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(215); -/** PURE_IMPORTS_START tslib,_Subscriber,_scheduler_async PURE_IMPORTS_END */ + const context = {isCanceled: false}; + spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned)); + spawned.cancel = spawnedCancel.bind(null, spawned, context); + const handlePromise = async () => { + const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone); + const stdout = handleOutput(parsed.options, stdoutResult); + const stderr = handleOutput(parsed.options, stderrResult); + const all = handleOutput(parsed.options, allResult); -function sampleTime(period, scheduler) { - if (scheduler === void 0) { - scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_2__["async"]; - } - return function (source) { return source.lift(new SampleTimeOperator(period, scheduler)); }; -} -var SampleTimeOperator = /*@__PURE__*/ (function () { - function SampleTimeOperator(period, scheduler) { - this.period = period; - this.scheduler = scheduler; - } - SampleTimeOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new SampleTimeSubscriber(subscriber, this.period, this.scheduler)); - }; - return SampleTimeOperator; -}()); -var SampleTimeSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SampleTimeSubscriber, _super); - function SampleTimeSubscriber(destination, period, scheduler) { - var _this = _super.call(this, destination) || this; - _this.period = period; - _this.scheduler = scheduler; - _this.hasValue = false; - _this.add(scheduler.schedule(dispatchNotification, period, { subscriber: _this, period: period })); - return _this; - } - SampleTimeSubscriber.prototype._next = function (value) { - this.lastValue = value; - this.hasValue = true; - }; - SampleTimeSubscriber.prototype.notifyNext = function () { - if (this.hasValue) { - this.hasValue = false; - this.destination.next(this.lastValue); - } - }; - return SampleTimeSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -function dispatchNotification(state) { - var subscriber = state.subscriber, period = state.period; - subscriber.notifyNext(); - this.schedule(state, period); -} -//# sourceMappingURL=sampleTime.js.map + if (error || exitCode !== 0 || signal !== null) { + const returnedError = makeError({ + error, + exitCode, + signal, + stdout, + stderr, + all, + command, + parsed, + timedOut, + isCanceled: context.isCanceled, + killed: spawned.killed + }); + if (!parsed.options.reject) { + return returnedError; + } -/***/ }), -/* 336 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + throw returnedError; + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sequenceEqual", function() { return sequenceEqual; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SequenceEqualOperator", function() { return SequenceEqualOperator; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SequenceEqualSubscriber", function() { return SequenceEqualSubscriber; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ + return { + command, + exitCode: 0, + stdout, + stderr, + all, + failed: false, + timedOut: false, + isCanceled: false, + killed: false + }; + }; + const handlePromiseOnce = onetime(handlePromise); -function sequenceEqual(compareTo, comparator) { - return function (source) { return source.lift(new SequenceEqualOperator(compareTo, comparator)); }; -} -var SequenceEqualOperator = /*@__PURE__*/ (function () { - function SequenceEqualOperator(compareTo, comparator) { - this.compareTo = compareTo; - this.comparator = comparator; - } - SequenceEqualOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new SequenceEqualSubscriber(subscriber, this.compareTo, this.comparator)); - }; - return SequenceEqualOperator; -}()); + crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed); -var SequenceEqualSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SequenceEqualSubscriber, _super); - function SequenceEqualSubscriber(destination, compareTo, comparator) { - var _this = _super.call(this, destination) || this; - _this.compareTo = compareTo; - _this.comparator = comparator; - _this._a = []; - _this._b = []; - _this._oneComplete = false; - _this.destination.add(compareTo.subscribe(new SequenceEqualCompareToSubscriber(destination, _this))); - return _this; - } - SequenceEqualSubscriber.prototype._next = function (value) { - if (this._oneComplete && this._b.length === 0) { - this.emit(false); - } - else { - this._a.push(value); - this.checkValues(); - } - }; - SequenceEqualSubscriber.prototype._complete = function () { - if (this._oneComplete) { - this.emit(this._a.length === 0 && this._b.length === 0); - } - else { - this._oneComplete = true; - } - this.unsubscribe(); - }; - SequenceEqualSubscriber.prototype.checkValues = function () { - var _c = this, _a = _c._a, _b = _c._b, comparator = _c.comparator; - while (_a.length > 0 && _b.length > 0) { - var a = _a.shift(); - var b = _b.shift(); - var areEqual = false; - try { - areEqual = comparator ? comparator(a, b) : a === b; - } - catch (e) { - this.destination.error(e); - } - if (!areEqual) { - this.emit(false); - } - } - }; - SequenceEqualSubscriber.prototype.emit = function (value) { - var destination = this.destination; - destination.next(value); - destination.complete(); - }; - SequenceEqualSubscriber.prototype.nextB = function (value) { - if (this._oneComplete && this._a.length === 0) { - this.emit(false); - } - else { - this._b.push(value); - this.checkValues(); - } - }; - SequenceEqualSubscriber.prototype.completeB = function () { - if (this._oneComplete) { - this.emit(this._a.length === 0 && this._b.length === 0); - } - else { - this._oneComplete = true; - } - }; - return SequenceEqualSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); + handleInput(spawned, parsed.options.input); -var SequenceEqualCompareToSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SequenceEqualCompareToSubscriber, _super); - function SequenceEqualCompareToSubscriber(destination, parent) { - var _this = _super.call(this, destination) || this; - _this.parent = parent; - return _this; - } - SequenceEqualCompareToSubscriber.prototype._next = function (value) { - this.parent.nextB(value); - }; - SequenceEqualCompareToSubscriber.prototype._error = function (err) { - this.parent.error(err); - this.unsubscribe(); - }; - SequenceEqualCompareToSubscriber.prototype._complete = function () { - this.parent.completeB(); - this.unsubscribe(); - }; - return SequenceEqualCompareToSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=sequenceEqual.js.map + spawned.all = makeAllStream(spawned, parsed.options); + return mergePromise(spawned, handlePromiseOnce); +}; -/***/ }), -/* 337 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +module.exports = execa; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "share", function() { return share; }); -/* harmony import */ var _multicast__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(320); -/* harmony import */ var _refCount__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(190); -/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(187); -/** PURE_IMPORTS_START _multicast,_refCount,_Subject PURE_IMPORTS_END */ +module.exports.sync = (file, args, options) => { + const parsed = handleArgs(file, args, options); + const command = joinCommand(file, args); + + validateInputSync(parsed.options); + + let result; + try { + result = childProcess.spawnSync(parsed.file, parsed.args, parsed.options); + } catch (error) { + throw makeError({ + error, + stdout: '', + stderr: '', + all: '', + command, + parsed, + timedOut: false, + isCanceled: false, + killed: false + }); + } + + const stdout = handleOutput(parsed.options, result.stdout, result.error); + const stderr = handleOutput(parsed.options, result.stderr, result.error); + if (result.error || result.status !== 0 || result.signal !== null) { + const error = makeError({ + stdout, + stderr, + error: result.error, + signal: result.signal, + exitCode: result.status, + command, + parsed, + timedOut: result.error && result.error.code === 'ETIMEDOUT', + isCanceled: false, + killed: result.signal !== null + }); + if (!parsed.options.reject) { + return error; + } -function shareSubjectFactory() { - return new _Subject__WEBPACK_IMPORTED_MODULE_2__["Subject"](); -} -function share() { - return function (source) { return Object(_refCount__WEBPACK_IMPORTED_MODULE_1__["refCount"])()(Object(_multicast__WEBPACK_IMPORTED_MODULE_0__["multicast"])(shareSubjectFactory)(source)); }; -} -//# sourceMappingURL=share.js.map + throw error; + } + + return { + command, + exitCode: 0, + stdout, + stderr, + failed: false, + timedOut: false, + isCanceled: false, + killed: false + }; +}; + +module.exports.command = (command, options) => { + const [file, ...args] = parseCommand(command); + return execa(file, args, options); +}; + +module.exports.commandSync = (command, options) => { + const [file, ...args] = parseCommand(command); + return execa.sync(file, args, options); +}; + +module.exports.node = (scriptPath, args, options = {}) => { + if (args && !Array.isArray(args) && typeof args === 'object') { + options = args; + args = []; + } + + const stdio = normalizeStdio.node(options); + + const {nodePath = process.execPath, nodeOptions = process.execArgv} = options; + + return execa( + nodePath, + [ + ...nodeOptions, + scriptPath, + ...(Array.isArray(args) ? args : []) + ], + { + ...options, + stdin: undefined, + stdout: undefined, + stderr: undefined, + stdio, + shell: false + } + ); +}; /***/ }), -/* 338 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 343 */ +/***/ (function(module, exports) { + +module.exports = require("child_process"); + +/***/ }), +/* 344 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "shareReplay", function() { return shareReplay; }); -/* harmony import */ var _ReplaySubject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(193); -/** PURE_IMPORTS_START _ReplaySubject PURE_IMPORTS_END */ -function shareReplay(configOrBufferSize, windowTime, scheduler) { - var config; - if (configOrBufferSize && typeof configOrBufferSize === 'object') { - config = configOrBufferSize; - } - else { - config = { - bufferSize: configOrBufferSize, - windowTime: windowTime, - refCount: false, - scheduler: scheduler - }; - } - return function (source) { return source.lift(shareReplayOperator(config)); }; + +const cp = __webpack_require__(343); +const parse = __webpack_require__(345); +const enoent = __webpack_require__(357); + +function spawn(command, args, options) { + // Parse the arguments + const parsed = parse(command, args, options); + + // Spawn the child process + const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); + + // Hook into child process "exit" event to emit an error if the command + // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + enoent.hookChildProcess(spawned, parsed); + + return spawned; } -function shareReplayOperator(_a) { - var _b = _a.bufferSize, bufferSize = _b === void 0 ? Number.POSITIVE_INFINITY : _b, _c = _a.windowTime, windowTime = _c === void 0 ? Number.POSITIVE_INFINITY : _c, useRefCount = _a.refCount, scheduler = _a.scheduler; - var subject; - var refCount = 0; - var subscription; - var hasError = false; - var isComplete = false; - return function shareReplayOperation(source) { - refCount++; - if (!subject || hasError) { - hasError = false; - subject = new _ReplaySubject__WEBPACK_IMPORTED_MODULE_0__["ReplaySubject"](bufferSize, windowTime, scheduler); - subscription = source.subscribe({ - next: function (value) { subject.next(value); }, - error: function (err) { - hasError = true; - subject.error(err); - }, - complete: function () { - isComplete = true; - subject.complete(); - }, - }); - } - var innerSub = subject.subscribe(this); - this.add(function () { - refCount--; - innerSub.unsubscribe(); - if (subscription && !isComplete && useRefCount && refCount === 0) { - subscription.unsubscribe(); - subscription = undefined; - subject = undefined; - } - }); - }; + +function spawnSync(command, args, options) { + // Parse the arguments + const parsed = parse(command, args, options); + + // Spawn the child process + const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); + + // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); + + return result; } -//# sourceMappingURL=shareReplay.js.map + +module.exports = spawn; +module.exports.spawn = spawn; +module.exports.sync = spawnSync; + +module.exports._parse = parse; +module.exports._enoent = enoent; /***/ }), -/* 339 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 345 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "single", function() { return single; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/* harmony import */ var _util_EmptyError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(223); -/** PURE_IMPORTS_START tslib,_Subscriber,_util_EmptyError PURE_IMPORTS_END */ +const path = __webpack_require__(4); +const resolveCommand = __webpack_require__(346); +const escape = __webpack_require__(353); +const readShebang = __webpack_require__(354); -function single(predicate) { - return function (source) { return source.lift(new SingleOperator(predicate, source)); }; +const isWin = process.platform === 'win32'; +const isExecutableRegExp = /\.(?:com|exe)$/i; +const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; + +function detectShebang(parsed) { + parsed.file = resolveCommand(parsed); + + const shebang = parsed.file && readShebang(parsed.file); + + if (shebang) { + parsed.args.unshift(parsed.file); + parsed.command = shebang; + + return resolveCommand(parsed); + } + + return parsed.file; } -var SingleOperator = /*@__PURE__*/ (function () { - function SingleOperator(predicate, source) { - this.predicate = predicate; - this.source = source; + +function parseNonShell(parsed) { + if (!isWin) { + return parsed; } - SingleOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new SingleSubscriber(subscriber, this.predicate, this.source)); - }; - return SingleOperator; -}()); -var SingleSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SingleSubscriber, _super); - function SingleSubscriber(destination, predicate, source) { - var _this = _super.call(this, destination) || this; - _this.predicate = predicate; - _this.source = source; - _this.seenValue = false; - _this.index = 0; - return _this; - } - SingleSubscriber.prototype.applySingleValue = function (value) { - if (this.seenValue) { - this.destination.error('Sequence contains more than one element'); - } - else { - this.seenValue = true; - this.singleValue = value; - } - }; - SingleSubscriber.prototype._next = function (value) { - var index = this.index++; - if (this.predicate) { - this.tryNext(value, index); - } - else { - this.applySingleValue(value); - } - }; - SingleSubscriber.prototype.tryNext = function (value, index) { - try { - if (this.predicate(value, index, this.source)) { - this.applySingleValue(value); - } - } - catch (err) { - this.destination.error(err); - } - }; - SingleSubscriber.prototype._complete = function () { - var destination = this.destination; - if (this.index > 0) { - destination.next(this.seenValue ? this.singleValue : undefined); - destination.complete(); - } - else { - destination.error(new _util_EmptyError__WEBPACK_IMPORTED_MODULE_2__["EmptyError"]); - } - }; - return SingleSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=single.js.map + // Detect & add support for shebangs + const commandFile = detectShebang(parsed); -/***/ }), -/* 340 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + // We don't need a shell if the command filename is an executable + const needsShell = !isExecutableRegExp.test(commandFile); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "skip", function() { return skip; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ + // If a shell is required, use cmd.exe and take care of escaping everything correctly + // Note that `forceShell` is an hidden option used only in tests + if (parsed.options.forceShell || needsShell) { + // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` + // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument + // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, + // we need to double escape them + const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); + // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) + // This is necessary otherwise it will always fail with ENOENT in those cases + parsed.command = path.normalize(parsed.command); -function skip(count) { - return function (source) { return source.lift(new SkipOperator(count)); }; -} -var SkipOperator = /*@__PURE__*/ (function () { - function SkipOperator(total) { - this.total = total; + // Escape command & arguments + parsed.command = escape.command(parsed.command); + parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); + + const shellCommand = [parsed.command].concat(parsed.args).join(' '); + + parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; + parsed.command = process.env.comspec || 'cmd.exe'; + parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped } - SkipOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new SkipSubscriber(subscriber, this.total)); - }; - return SkipOperator; -}()); -var SkipSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SkipSubscriber, _super); - function SkipSubscriber(destination, total) { - var _this = _super.call(this, destination) || this; - _this.total = total; - _this.count = 0; - return _this; + + return parsed; +} + +function parse(command, args, options) { + // Normalize arguments, similar to nodejs + if (args && !Array.isArray(args)) { + options = args; + args = null; } - SkipSubscriber.prototype._next = function (x) { - if (++this.count > this.total) { - this.destination.next(x); - } + + args = args ? args.slice(0) : []; // Clone array to avoid changing the original + options = Object.assign({}, options); // Clone object to avoid changing the original + + // Build our parsed object + const parsed = { + command, + args, + options, + file: undefined, + original: { + command, + args, + }, }; - return SkipSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=skip.js.map + + // Delegate further parsing to shell or non-shell + return options.shell ? parsed : parseNonShell(parsed); +} + +module.exports = parse; /***/ }), -/* 341 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 346 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "skipLast", function() { return skipLast; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/* harmony import */ var _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(222); -/** PURE_IMPORTS_START tslib,_Subscriber,_util_ArgumentOutOfRangeError PURE_IMPORTS_END */ +const path = __webpack_require__(4); +const which = __webpack_require__(347); +const pathKey = __webpack_require__(352)(); -function skipLast(count) { - return function (source) { return source.lift(new SkipLastOperator(count)); }; -} -var SkipLastOperator = /*@__PURE__*/ (function () { - function SkipLastOperator(_skipCount) { - this._skipCount = _skipCount; - if (this._skipCount < 0) { - throw new _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_2__["ArgumentOutOfRangeError"]; +function resolveCommandAttempt(parsed, withoutPathExt) { + const cwd = process.cwd(); + const hasCustomCwd = parsed.options.cwd != null; + // Worker threads do not have process.chdir() + const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined; + + // If a custom `cwd` was specified, we need to change the process cwd + // because `which` will do stat calls but does not support a custom cwd + if (shouldSwitchCwd) { + try { + process.chdir(parsed.options.cwd); + } catch (err) { + /* Empty */ } } - SkipLastOperator.prototype.call = function (subscriber, source) { - if (this._skipCount === 0) { - return source.subscribe(new _Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"](subscriber)); - } - else { - return source.subscribe(new SkipLastSubscriber(subscriber, this._skipCount)); + + let resolved; + + try { + resolved = which.sync(parsed.command, { + path: (parsed.options.env || process.env)[pathKey], + pathExt: withoutPathExt ? path.delimiter : undefined, + }); + } catch (e) { + /* Empty */ + } finally { + if (shouldSwitchCwd) { + process.chdir(cwd); } - }; - return SkipLastOperator; -}()); -var SkipLastSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SkipLastSubscriber, _super); - function SkipLastSubscriber(destination, _skipCount) { - var _this = _super.call(this, destination) || this; - _this._skipCount = _skipCount; - _this._count = 0; - _this._ring = new Array(_skipCount); - return _this; } - SkipLastSubscriber.prototype._next = function (value) { - var skipCount = this._skipCount; - var count = this._count++; - if (count < skipCount) { - this._ring[count] = value; - } - else { - var currentIndex = count % skipCount; - var ring = this._ring; - var oldValue = ring[currentIndex]; - ring[currentIndex] = value; - this.destination.next(oldValue); - } - }; - return SkipLastSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=skipLast.js.map + // If we successfully resolved, ensure that an absolute path is returned + // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it + if (resolved) { + resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); + } -/***/ }), -/* 342 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + return resolved; +} -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "skipUntil", function() { return skipUntil; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(229); -/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(231); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_OuterSubscriber,_InnerSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ +function resolveCommand(parsed) { + return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); +} +module.exports = resolveCommand; +/***/ }), +/* 347 */ +/***/ (function(module, exports, __webpack_require__) { -function skipUntil(notifier) { - return function (source) { return source.lift(new SkipUntilOperator(notifier)); }; -} -var SkipUntilOperator = /*@__PURE__*/ (function () { - function SkipUntilOperator(notifier) { - this.notifier = notifier; - } - SkipUntilOperator.prototype.call = function (destination, source) { - return source.subscribe(new SkipUntilSubscriber(destination, this.notifier)); - }; - return SkipUntilOperator; -}()); -var SkipUntilSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SkipUntilSubscriber, _super); - function SkipUntilSubscriber(destination, notifier) { - var _this = _super.call(this, destination) || this; - _this.hasValue = false; - var innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__["InnerSubscriber"](_this, undefined, undefined); - _this.add(innerSubscriber); - _this.innerSubscription = innerSubscriber; - Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(_this, notifier, undefined, undefined, innerSubscriber); - return _this; - } - SkipUntilSubscriber.prototype._next = function (value) { - if (this.hasValue) { - _super.prototype._next.call(this, value); - } - }; - SkipUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.hasValue = true; - if (this.innerSubscription) { - this.innerSubscription.unsubscribe(); - } - }; - SkipUntilSubscriber.prototype.notifyComplete = function () { - }; - return SkipUntilSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); -//# sourceMappingURL=skipUntil.js.map +const isWindows = process.platform === 'win32' || + process.env.OSTYPE === 'cygwin' || + process.env.OSTYPE === 'msys' +const path = __webpack_require__(4) +const COLON = isWindows ? ';' : ':' +const isexe = __webpack_require__(348) -/***/ }), -/* 343 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +const getNotFoundError = (cmd) => + Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }) -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "skipWhile", function() { return skipWhile; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +const getPathInfo = (cmd, opt) => { + const colon = opt.colon || COLON + + // If it has a slash, then we don't bother searching the pathenv. + // just check the file itself, and that's it. + const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] + : ( + [ + // windows always checks the cwd first + ...(isWindows ? [process.cwd()] : []), + ...(opt.path || process.env.PATH || + /* istanbul ignore next: very unusual */ '').split(colon), + ] + ) + const pathExtExe = isWindows + ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' + : '' + const pathExt = isWindows ? pathExtExe.split(colon) : [''] + if (isWindows) { + if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') + pathExt.unshift('') + } -function skipWhile(predicate) { - return function (source) { return source.lift(new SkipWhileOperator(predicate)); }; + return { + pathEnv, + pathExt, + pathExtExe, + } } -var SkipWhileOperator = /*@__PURE__*/ (function () { - function SkipWhileOperator(predicate) { - this.predicate = predicate; - } - SkipWhileOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate)); - }; - return SkipWhileOperator; -}()); -var SkipWhileSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SkipWhileSubscriber, _super); - function SkipWhileSubscriber(destination, predicate) { - var _this = _super.call(this, destination) || this; - _this.predicate = predicate; - _this.skipping = true; - _this.index = 0; - return _this; - } - SkipWhileSubscriber.prototype._next = function (value) { - var destination = this.destination; - if (this.skipping) { - this.tryCallPredicate(value); - } - if (!this.skipping) { - destination.next(value); - } - }; - SkipWhileSubscriber.prototype.tryCallPredicate = function (value) { - try { - var result = this.predicate(value, this.index++); - this.skipping = Boolean(result); - } - catch (err) { - this.destination.error(err); - } - }; - return SkipWhileSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=skipWhile.js.map +const which = (cmd, opt, cb) => { + if (typeof opt === 'function') { + cb = opt + opt = {} + } + if (!opt) + opt = {} -/***/ }), -/* 344 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) + const found = [] -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startWith", function() { return startWith; }); -/* harmony import */ var _observable_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(239); -/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(205); -/** PURE_IMPORTS_START _observable_concat,_util_isScheduler PURE_IMPORTS_END */ + const step = i => new Promise((resolve, reject) => { + if (i === pathEnv.length) + return opt.all && found.length ? resolve(found) + : reject(getNotFoundError(cmd)) + const ppRaw = pathEnv[i] + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw -function startWith() { - var array = []; - for (var _i = 0; _i < arguments.length; _i++) { - array[_i] = arguments[_i]; - } - var scheduler = array[array.length - 1]; - if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_1__["isScheduler"])(scheduler)) { - array.pop(); - return function (source) { return Object(_observable_concat__WEBPACK_IMPORTED_MODULE_0__["concat"])(array, source, scheduler); }; - } - else { - return function (source) { return Object(_observable_concat__WEBPACK_IMPORTED_MODULE_0__["concat"])(array, source); }; - } + const pCmd = path.join(pathPart, cmd) + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd + + resolve(subStep(p, i, 0)) + }) + + const subStep = (p, i, ii) => new Promise((resolve, reject) => { + if (ii === pathExt.length) + return resolve(step(i + 1)) + const ext = pathExt[ii] + isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { + if (!er && is) { + if (opt.all) + found.push(p + ext) + else + return resolve(p + ext) + } + return resolve(subStep(p, i, ii + 1)) + }) + }) + + return cb ? step(0).then(res => cb(null, res), cb) : step(0) } -//# sourceMappingURL=startWith.js.map +const whichSync = (cmd, opt) => { + opt = opt || {} -/***/ }), -/* 345 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) + const found = [] -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subscribeOn", function() { return subscribeOn; }); -/* harmony import */ var _observable_SubscribeOnObservable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(346); -/** PURE_IMPORTS_START _observable_SubscribeOnObservable PURE_IMPORTS_END */ + for (let i = 0; i < pathEnv.length; i ++) { + const ppRaw = pathEnv[i] + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw -function subscribeOn(scheduler, delay) { - if (delay === void 0) { - delay = 0; + const pCmd = path.join(pathPart, cmd) + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd + + for (let j = 0; j < pathExt.length; j ++) { + const cur = p + pathExt[j] + try { + const is = isexe.sync(cur, { pathExt: pathExtExe }) + if (is) { + if (opt.all) + found.push(cur) + else + return cur + } + } catch (ex) {} } - return function subscribeOnOperatorFunction(source) { - return source.lift(new SubscribeOnOperator(scheduler, delay)); - }; + } + + if (opt.all && found.length) + return found + + if (opt.nothrow) + return null + + throw getNotFoundError(cmd) } -var SubscribeOnOperator = /*@__PURE__*/ (function () { - function SubscribeOnOperator(scheduler, delay) { - this.scheduler = scheduler; - this.delay = delay; - } - SubscribeOnOperator.prototype.call = function (subscriber, source) { - return new _observable_SubscribeOnObservable__WEBPACK_IMPORTED_MODULE_0__["SubscribeOnObservable"](source, this.delay, this.scheduler).subscribe(subscriber); - }; - return SubscribeOnOperator; -}()); -//# sourceMappingURL=subscribeOn.js.map + +module.exports = which +which.sync = whichSync /***/ }), -/* 346 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 348 */ +/***/ (function(module, exports, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscribeOnObservable", function() { return SubscribeOnObservable; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(170); -/* harmony import */ var _scheduler_asap__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(211); -/* harmony import */ var _util_isNumeric__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(257); -/** PURE_IMPORTS_START tslib,_Observable,_scheduler_asap,_util_isNumeric PURE_IMPORTS_END */ +var fs = __webpack_require__(349) +var core +if (process.platform === 'win32' || global.TESTING_WINDOWS) { + core = __webpack_require__(350) +} else { + core = __webpack_require__(351) +} +module.exports = isexe +isexe.sync = sync +function isexe (path, options, cb) { + if (typeof options === 'function') { + cb = options + options = {} + } + if (!cb) { + if (typeof Promise !== 'function') { + throw new TypeError('callback not provided') + } -var SubscribeOnObservable = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SubscribeOnObservable, _super); - function SubscribeOnObservable(source, delayTime, scheduler) { - if (delayTime === void 0) { - delayTime = 0; - } - if (scheduler === void 0) { - scheduler = _scheduler_asap__WEBPACK_IMPORTED_MODULE_2__["asap"]; - } - var _this = _super.call(this) || this; - _this.source = source; - _this.delayTime = delayTime; - _this.scheduler = scheduler; - if (!Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_3__["isNumeric"])(delayTime) || delayTime < 0) { - _this.delayTime = 0; - } - if (!scheduler || typeof scheduler.schedule !== 'function') { - _this.scheduler = _scheduler_asap__WEBPACK_IMPORTED_MODULE_2__["asap"]; + return new Promise(function (resolve, reject) { + isexe(path, options || {}, function (er, is) { + if (er) { + reject(er) + } else { + resolve(is) } - return _this; - } - SubscribeOnObservable.create = function (source, delay, scheduler) { - if (delay === void 0) { - delay = 0; - } - if (scheduler === void 0) { - scheduler = _scheduler_asap__WEBPACK_IMPORTED_MODULE_2__["asap"]; - } - return new SubscribeOnObservable(source, delay, scheduler); - }; - SubscribeOnObservable.dispatch = function (arg) { - var source = arg.source, subscriber = arg.subscriber; - return this.add(source.subscribe(subscriber)); - }; - SubscribeOnObservable.prototype._subscribe = function (subscriber) { - var delay = this.delayTime; - var source = this.source; - var scheduler = this.scheduler; - return scheduler.schedule(SubscribeOnObservable.dispatch, delay, { - source: source, subscriber: subscriber - }); - }; - return SubscribeOnObservable; -}(_Observable__WEBPACK_IMPORTED_MODULE_1__["Observable"])); + }) + }) + } -//# sourceMappingURL=SubscribeOnObservable.js.map + core(path, options || {}, function (er, is) { + // ignore EACCES because that just means we aren't allowed to run it + if (er) { + if (er.code === 'EACCES' || options && options.ignoreErrors) { + er = null + is = false + } + } + cb(er, is) + }) +} + +function sync (path, options) { + // my kingdom for a filtered catch + try { + return core.sync(path, options || {}) + } catch (er) { + if (options && options.ignoreErrors || er.code === 'EACCES') { + return false + } else { + throw er + } + } +} /***/ }), -/* 347 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 349 */ +/***/ (function(module, exports) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "switchAll", function() { return switchAll; }); -/* harmony import */ var _switchMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(348); -/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(220); -/** PURE_IMPORTS_START _switchMap,_util_identity PURE_IMPORTS_END */ +module.exports = require("fs"); +/***/ }), +/* 350 */ +/***/ (function(module, exports, __webpack_require__) { -function switchAll() { - return Object(_switchMap__WEBPACK_IMPORTED_MODULE_0__["switchMap"])(_util_identity__WEBPACK_IMPORTED_MODULE_1__["identity"]); +module.exports = isexe +isexe.sync = sync + +var fs = __webpack_require__(349) + +function checkPathExt (path, options) { + var pathext = options.pathExt !== undefined ? + options.pathExt : process.env.PATHEXT + + if (!pathext) { + return true + } + + pathext = pathext.split(';') + if (pathext.indexOf('') !== -1) { + return true + } + for (var i = 0; i < pathext.length; i++) { + var p = pathext[i].toLowerCase() + if (p && path.substr(-p.length).toLowerCase() === p) { + return true + } + } + return false +} + +function checkStat (stat, path, options) { + if (!stat.isSymbolicLink() && !stat.isFile()) { + return false + } + return checkPathExt(path, options) +} + +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, path, options)) + }) +} + +function sync (path, options) { + return checkStat(fs.statSync(path), path, options) } -//# sourceMappingURL=switchAll.js.map /***/ }), -/* 348 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 351 */ +/***/ (function(module, exports, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "switchMap", function() { return switchMap; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(229); -/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(231); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(230); -/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(226); -/* harmony import */ var _observable_from__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(243); -/** PURE_IMPORTS_START tslib,_OuterSubscriber,_InnerSubscriber,_util_subscribeToResult,_map,_observable_from PURE_IMPORTS_END */ +module.exports = isexe +isexe.sync = sync + +var fs = __webpack_require__(349) + +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, options)) + }) +} + +function sync (path, options) { + return checkStat(fs.statSync(path), options) +} +function checkStat (stat, options) { + return stat.isFile() && checkMode(stat, options) +} +function checkMode (stat, options) { + var mod = stat.mode + var uid = stat.uid + var gid = stat.gid + var myUid = options.uid !== undefined ? + options.uid : process.getuid && process.getuid() + var myGid = options.gid !== undefined ? + options.gid : process.getgid && process.getgid() + var u = parseInt('100', 8) + var g = parseInt('010', 8) + var o = parseInt('001', 8) + var ug = u | g + var ret = (mod & o) || + (mod & g) && gid === myGid || + (mod & u) && uid === myUid || + (mod & ug) && myUid === 0 -function switchMap(project, resultSelector) { - if (typeof resultSelector === 'function') { - return function (source) { return source.pipe(switchMap(function (a, i) { return Object(_observable_from__WEBPACK_IMPORTED_MODULE_5__["from"])(project(a, i)).pipe(Object(_map__WEBPACK_IMPORTED_MODULE_4__["map"])(function (b, ii) { return resultSelector(a, b, i, ii); })); })); }; - } - return function (source) { return source.lift(new SwitchMapOperator(project)); }; + return ret } -var SwitchMapOperator = /*@__PURE__*/ (function () { - function SwitchMapOperator(project) { - this.project = project; - } - SwitchMapOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new SwitchMapSubscriber(subscriber, this.project)); - }; - return SwitchMapOperator; -}()); -var SwitchMapSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SwitchMapSubscriber, _super); - function SwitchMapSubscriber(destination, project) { - var _this = _super.call(this, destination) || this; - _this.project = project; - _this.index = 0; - return _this; - } - SwitchMapSubscriber.prototype._next = function (value) { - var result; - var index = this.index++; - try { - result = this.project(value, index); - } - catch (error) { - this.destination.error(error); - return; - } - this._innerSub(result, value, index); - }; - SwitchMapSubscriber.prototype._innerSub = function (result, value, index) { - var innerSubscription = this.innerSubscription; - if (innerSubscription) { - innerSubscription.unsubscribe(); - } - var innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_2__["InnerSubscriber"](this, undefined, undefined); - var destination = this.destination; - destination.add(innerSubscriber); - this.innerSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(this, result, value, index, innerSubscriber); - }; - SwitchMapSubscriber.prototype._complete = function () { - var innerSubscription = this.innerSubscription; - if (!innerSubscription || innerSubscription.closed) { - _super.prototype._complete.call(this); - } - this.unsubscribe(); - }; - SwitchMapSubscriber.prototype._unsubscribe = function () { - this.innerSubscription = null; - }; - SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) { - var destination = this.destination; - destination.remove(innerSub); - this.innerSubscription = null; - if (this.isStopped) { - _super.prototype._complete.call(this); - } - }; - SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.destination.next(innerValue); - }; - return SwitchMapSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); -//# sourceMappingURL=switchMap.js.map /***/ }), -/* 349 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 352 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "switchMapTo", function() { return switchMapTo; }); -/* harmony import */ var _switchMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(348); -/** PURE_IMPORTS_START _switchMap PURE_IMPORTS_END */ -function switchMapTo(innerObservable, resultSelector) { - return resultSelector ? Object(_switchMap__WEBPACK_IMPORTED_MODULE_0__["switchMap"])(function () { return innerObservable; }, resultSelector) : Object(_switchMap__WEBPACK_IMPORTED_MODULE_0__["switchMap"])(function () { return innerObservable; }); -} -//# sourceMappingURL=switchMapTo.js.map + +const pathKey = (options = {}) => { + const environment = options.env || process.env; + const platform = options.platform || process.platform; + + if (platform !== 'win32') { + return 'PATH'; + } + + return Object.keys(environment).find(key => key.toUpperCase() === 'PATH') || 'Path'; +}; + +module.exports = pathKey; +// TODO: Remove this for the next major release +module.exports.default = pathKey; /***/ }), -/* 350 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 353 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "takeUntil", function() { return takeUntil; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ +// See http://www.robvanderwoude.com/escapechars.php +const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; -function takeUntil(notifier) { - return function (source) { return source.lift(new TakeUntilOperator(notifier)); }; +function escapeCommand(arg) { + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + return arg; } -var TakeUntilOperator = /*@__PURE__*/ (function () { - function TakeUntilOperator(notifier) { - this.notifier = notifier; - } - TakeUntilOperator.prototype.call = function (subscriber, source) { - var takeUntilSubscriber = new TakeUntilSubscriber(subscriber); - var notifierSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(takeUntilSubscriber, this.notifier); - if (notifierSubscription && !takeUntilSubscriber.seenValue) { - takeUntilSubscriber.add(notifierSubscription); - return source.subscribe(takeUntilSubscriber); - } - return takeUntilSubscriber; - }; - return TakeUntilOperator; -}()); -var TakeUntilSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TakeUntilSubscriber, _super); - function TakeUntilSubscriber(destination) { - var _this = _super.call(this, destination) || this; - _this.seenValue = false; - return _this; - } - TakeUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.seenValue = true; - this.complete(); - }; - TakeUntilSubscriber.prototype.notifyComplete = function () { - }; - return TakeUntilSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); -//# sourceMappingURL=takeUntil.js.map +function escapeArgument(arg, doubleEscapeMetaChars) { + // Convert to string + arg = `${arg}`; -/***/ }), -/* 351 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + // Algorithm below is based on https://qntm.org/cmd -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "takeWhile", function() { return takeWhile; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ + // Sequence of backslashes followed by a double quote: + // double up all the backslashes and escape the double quote + arg = arg.replace(/(\\*)"/g, '$1$1\\"'); + + // Sequence of backslashes followed by the end of the string + // (which will become a double quote later): + // double up all the backslashes + arg = arg.replace(/(\\*)$/, '$1$1'); + // All other backslashes occur literally -function takeWhile(predicate, inclusive) { - if (inclusive === void 0) { - inclusive = false; + // Quote the whole thing: + arg = `"${arg}"`; + + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + // Double escape meta chars if necessary + if (doubleEscapeMetaChars) { + arg = arg.replace(metaCharsRegExp, '^$1'); } - return function (source) { - return source.lift(new TakeWhileOperator(predicate, inclusive)); - }; + + return arg; } -var TakeWhileOperator = /*@__PURE__*/ (function () { - function TakeWhileOperator(predicate, inclusive) { - this.predicate = predicate; - this.inclusive = inclusive; - } - TakeWhileOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new TakeWhileSubscriber(subscriber, this.predicate, this.inclusive)); - }; - return TakeWhileOperator; -}()); -var TakeWhileSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TakeWhileSubscriber, _super); - function TakeWhileSubscriber(destination, predicate, inclusive) { - var _this = _super.call(this, destination) || this; - _this.predicate = predicate; - _this.inclusive = inclusive; - _this.index = 0; - return _this; - } - TakeWhileSubscriber.prototype._next = function (value) { - var destination = this.destination; - var result; - try { - result = this.predicate(value, this.index++); - } - catch (err) { - destination.error(err); - return; - } - this.nextOrComplete(value, result); - }; - TakeWhileSubscriber.prototype.nextOrComplete = function (value, predicateResult) { - var destination = this.destination; - if (Boolean(predicateResult)) { - destination.next(value); - } - else { - if (this.inclusive) { - destination.next(value); - } - destination.complete(); - } - }; - return TakeWhileSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=takeWhile.js.map + +module.exports.command = escapeCommand; +module.exports.argument = escapeArgument; /***/ }), -/* 352 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 354 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tap", function() { return tap; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/* harmony import */ var _util_noop__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(185); -/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(173); -/** PURE_IMPORTS_START tslib,_Subscriber,_util_noop,_util_isFunction PURE_IMPORTS_END */ +const fs = __webpack_require__(349); +const shebangCommand = __webpack_require__(355); + +function readShebang(command) { + // Read the first 150 bytes from the file + const size = 150; + const buffer = Buffer.alloc(size); + + let fd; + try { + fd = fs.openSync(command, 'r'); + fs.readSync(fd, buffer, 0, size, 0); + fs.closeSync(fd); + } catch (e) { /* Empty */ } -function tap(nextOrObserver, error, complete) { - return function tapOperatorFunction(source) { - return source.lift(new DoOperator(nextOrObserver, error, complete)); - }; + // Attempt to extract shebang (null is returned if not a shebang) + return shebangCommand(buffer.toString()); } -var DoOperator = /*@__PURE__*/ (function () { - function DoOperator(nextOrObserver, error, complete) { - this.nextOrObserver = nextOrObserver; - this.error = error; - this.complete = complete; - } - DoOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete)); - }; - return DoOperator; -}()); -var TapSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TapSubscriber, _super); - function TapSubscriber(destination, observerOrNext, error, complete) { - var _this = _super.call(this, destination) || this; - _this._tapNext = _util_noop__WEBPACK_IMPORTED_MODULE_2__["noop"]; - _this._tapError = _util_noop__WEBPACK_IMPORTED_MODULE_2__["noop"]; - _this._tapComplete = _util_noop__WEBPACK_IMPORTED_MODULE_2__["noop"]; - _this._tapError = error || _util_noop__WEBPACK_IMPORTED_MODULE_2__["noop"]; - _this._tapComplete = complete || _util_noop__WEBPACK_IMPORTED_MODULE_2__["noop"]; - if (Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_3__["isFunction"])(observerOrNext)) { - _this._context = _this; - _this._tapNext = observerOrNext; - } - else if (observerOrNext) { - _this._context = observerOrNext; - _this._tapNext = observerOrNext.next || _util_noop__WEBPACK_IMPORTED_MODULE_2__["noop"]; - _this._tapError = observerOrNext.error || _util_noop__WEBPACK_IMPORTED_MODULE_2__["noop"]; - _this._tapComplete = observerOrNext.complete || _util_noop__WEBPACK_IMPORTED_MODULE_2__["noop"]; - } - return _this; - } - TapSubscriber.prototype._next = function (value) { - try { - this._tapNext.call(this._context, value); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.next(value); - }; - TapSubscriber.prototype._error = function (err) { - try { - this._tapError.call(this._context, err); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.error(err); - }; - TapSubscriber.prototype._complete = function () { - try { - this._tapComplete.call(this._context); - } - catch (err) { - this.destination.error(err); - return; - } - return this.destination.complete(); - }; - return TapSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=tap.js.map + +module.exports = readShebang; /***/ }), -/* 353 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 355 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultThrottleConfig", function() { return defaultThrottleConfig; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "throttle", function() { return throttle; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ +const shebangRegex = __webpack_require__(356); +module.exports = (string = '') => { + const match = string.match(shebangRegex); -var defaultThrottleConfig = { - leading: true, - trailing: false + if (!match) { + return null; + } + + const [path, argument] = match[0].replace(/#! ?/, '').split(' '); + const binary = path.split('/').pop(); + + if (binary === 'env') { + return argument; + } + + return argument ? `${binary} ${argument}` : binary; }; -function throttle(durationSelector, config) { - if (config === void 0) { - config = defaultThrottleConfig; - } - return function (source) { return source.lift(new ThrottleOperator(durationSelector, config.leading, config.trailing)); }; -} -var ThrottleOperator = /*@__PURE__*/ (function () { - function ThrottleOperator(durationSelector, leading, trailing) { - this.durationSelector = durationSelector; - this.leading = leading; - this.trailing = trailing; - } - ThrottleOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing)); - }; - return ThrottleOperator; -}()); -var ThrottleSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ThrottleSubscriber, _super); - function ThrottleSubscriber(destination, durationSelector, _leading, _trailing) { - var _this = _super.call(this, destination) || this; - _this.destination = destination; - _this.durationSelector = durationSelector; - _this._leading = _leading; - _this._trailing = _trailing; - _this._hasValue = false; - return _this; - } - ThrottleSubscriber.prototype._next = function (value) { - this._hasValue = true; - this._sendValue = value; - if (!this._throttled) { - if (this._leading) { - this.send(); - } - else { - this.throttle(value); - } - } - }; - ThrottleSubscriber.prototype.send = function () { - var _a = this, _hasValue = _a._hasValue, _sendValue = _a._sendValue; - if (_hasValue) { - this.destination.next(_sendValue); - this.throttle(_sendValue); - } - this._hasValue = false; - this._sendValue = null; - }; - ThrottleSubscriber.prototype.throttle = function (value) { - var duration = this.tryDurationSelector(value); - if (!!duration) { - this.add(this._throttled = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(this, duration)); - } - }; - ThrottleSubscriber.prototype.tryDurationSelector = function (value) { - try { - return this.durationSelector(value); - } - catch (err) { - this.destination.error(err); - return null; - } - }; - ThrottleSubscriber.prototype.throttlingDone = function () { - var _a = this, _throttled = _a._throttled, _trailing = _a._trailing; - if (_throttled) { - _throttled.unsubscribe(); - } - this._throttled = null; - if (_trailing) { - this.send(); - } - }; - ThrottleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.throttlingDone(); - }; - ThrottleSubscriber.prototype.notifyComplete = function () { - this.throttlingDone(); - }; - return ThrottleSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); -//# sourceMappingURL=throttle.js.map /***/ }), -/* 354 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 356 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "throttleTime", function() { return throttleTime; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(215); -/* harmony import */ var _throttle__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(353); -/** PURE_IMPORTS_START tslib,_Subscriber,_scheduler_async,_throttle PURE_IMPORTS_END */ +module.exports = /^#!(.*)/; +/***/ }), +/* 357 */ +/***/ (function(module, exports, __webpack_require__) { -function throttleTime(duration, scheduler, config) { - if (scheduler === void 0) { - scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_2__["async"]; - } - if (config === void 0) { - config = _throttle__WEBPACK_IMPORTED_MODULE_3__["defaultThrottleConfig"]; - } - return function (source) { return source.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing)); }; +"use strict"; + + +const isWin = process.platform === 'win32'; + +function notFoundError(original, syscall) { + return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { + code: 'ENOENT', + errno: 'ENOENT', + syscall: `${syscall} ${original.command}`, + path: original.command, + spawnargs: original.args, + }); } -var ThrottleTimeOperator = /*@__PURE__*/ (function () { - function ThrottleTimeOperator(duration, scheduler, leading, trailing) { - this.duration = duration; - this.scheduler = scheduler; - this.leading = leading; - this.trailing = trailing; - } - ThrottleTimeOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing)); - }; - return ThrottleTimeOperator; -}()); -var ThrottleTimeSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ThrottleTimeSubscriber, _super); - function ThrottleTimeSubscriber(destination, duration, scheduler, leading, trailing) { - var _this = _super.call(this, destination) || this; - _this.duration = duration; - _this.scheduler = scheduler; - _this.leading = leading; - _this.trailing = trailing; - _this._hasTrailingValue = false; - _this._trailingValue = null; - return _this; + +function hookChildProcess(cp, parsed) { + if (!isWin) { + return; } - ThrottleTimeSubscriber.prototype._next = function (value) { - if (this.throttled) { - if (this.trailing) { - this._trailingValue = value; - this._hasTrailingValue = true; - } - } - else { - this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, { subscriber: this })); - if (this.leading) { - this.destination.next(value); - } - else if (this.trailing) { - this._trailingValue = value; - this._hasTrailingValue = true; - } - } - }; - ThrottleTimeSubscriber.prototype._complete = function () { - if (this._hasTrailingValue) { - this.destination.next(this._trailingValue); - this.destination.complete(); - } - else { - this.destination.complete(); - } - }; - ThrottleTimeSubscriber.prototype.clearThrottle = function () { - var throttled = this.throttled; - if (throttled) { - if (this.trailing && this._hasTrailingValue) { - this.destination.next(this._trailingValue); - this._trailingValue = null; - this._hasTrailingValue = false; + + const originalEmit = cp.emit; + + cp.emit = function (name, arg1) { + // If emitting "exit" event and exit code is 1, we need to check if + // the command exists and emit an "error" instead + // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 + if (name === 'exit') { + const err = verifyENOENT(arg1, parsed, 'spawn'); + + if (err) { + return originalEmit.call(cp, 'error', err); } - throttled.unsubscribe(); - this.remove(throttled); - this.throttled = null; } + + return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params }; - return ThrottleTimeSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -function dispatchNext(arg) { - var subscriber = arg.subscriber; - subscriber.clearThrottle(); } -//# sourceMappingURL=throttleTime.js.map + +function verifyENOENT(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawn'); + } + + return null; +} + +function verifyENOENTSync(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawnSync'); + } + + return null; +} + +module.exports = { + hookChildProcess, + verifyENOENT, + verifyENOENTSync, + notFoundError, +}; /***/ }), -/* 355 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 358 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timeInterval", function() { return timeInterval; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimeInterval", function() { return TimeInterval; }); -/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(215); -/* harmony import */ var _scan__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(315); -/* harmony import */ var _observable_defer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(250); -/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(226); -/** PURE_IMPORTS_START _scheduler_async,_scan,_observable_defer,_map PURE_IMPORTS_END */ +module.exports = input => { + const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt(); + const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt(); + if (input[input.length - 1] === LF) { + input = input.slice(0, input.length - 1); + } -function timeInterval(scheduler) { - if (scheduler === void 0) { - scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_0__["async"]; - } - return function (source) { - return Object(_observable_defer__WEBPACK_IMPORTED_MODULE_2__["defer"])(function () { - return source.pipe(Object(_scan__WEBPACK_IMPORTED_MODULE_1__["scan"])(function (_a, value) { - var current = _a.current; - return ({ value: value, current: scheduler.now(), last: current }); - }, { current: scheduler.now(), value: undefined, last: undefined }), Object(_map__WEBPACK_IMPORTED_MODULE_3__["map"])(function (_a) { - var current = _a.current, last = _a.last, value = _a.value; - return new TimeInterval(value, current - last); - })); - }); - }; -} -var TimeInterval = /*@__PURE__*/ (function () { - function TimeInterval(value, interval) { - this.value = value; - this.interval = interval; - } - return TimeInterval; -}()); + if (input[input.length - 1] === CR) { + input = input.slice(0, input.length - 1); + } -//# sourceMappingURL=timeInterval.js.map + return input; +}; /***/ }), -/* 356 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 359 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timeout", function() { return timeout; }); -/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(215); -/* harmony import */ var _util_TimeoutError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(224); -/* harmony import */ var _timeoutWith__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(357); -/* harmony import */ var _observable_throwError__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(209); -/** PURE_IMPORTS_START _scheduler_async,_util_TimeoutError,_timeoutWith,_observable_throwError PURE_IMPORTS_END */ - +const path = __webpack_require__(4); +const pathKey = __webpack_require__(352); +const npmRunPath = options => { + options = { + cwd: process.cwd(), + path: process.env[pathKey()], + execPath: process.execPath, + ...options + }; -function timeout(due, scheduler) { - if (scheduler === void 0) { - scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_0__["async"]; - } - return Object(_timeoutWith__WEBPACK_IMPORTED_MODULE_2__["timeoutWith"])(due, Object(_observable_throwError__WEBPACK_IMPORTED_MODULE_3__["throwError"])(new _util_TimeoutError__WEBPACK_IMPORTED_MODULE_1__["TimeoutError"]()), scheduler); -} -//# sourceMappingURL=timeout.js.map + let previous; + let cwdPath = path.resolve(options.cwd); + const result = []; + while (previous !== cwdPath) { + result.push(path.join(cwdPath, 'node_modules/.bin')); + previous = cwdPath; + cwdPath = path.resolve(cwdPath, '..'); + } -/***/ }), -/* 357 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + // Ensure the running `node` binary is used + const execPathDir = path.resolve(options.cwd, options.execPath, '..'); + result.push(execPathDir); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timeoutWith", function() { return timeoutWith; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(215); -/* harmony import */ var _util_isDate__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(289); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_scheduler_async,_util_isDate,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ + return result.concat(options.path).join(path.delimiter); +}; +module.exports = npmRunPath; +// TODO: Remove this for the next major release +module.exports.default = npmRunPath; +module.exports.env = options => { + options = { + env: process.env, + ...options + }; + const env = {...options.env}; + const path = pathKey({env}); + options.path = env[path]; + env[path] = module.exports(options); -function timeoutWith(due, withObservable, scheduler) { - if (scheduler === void 0) { - scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__["async"]; - } - return function (source) { - var absoluteTimeout = Object(_util_isDate__WEBPACK_IMPORTED_MODULE_2__["isDate"])(due); - var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due); - return source.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler)); - }; -} -var TimeoutWithOperator = /*@__PURE__*/ (function () { - function TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler) { - this.waitFor = waitFor; - this.absoluteTimeout = absoluteTimeout; - this.withObservable = withObservable; - this.scheduler = scheduler; - } - TimeoutWithOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new TimeoutWithSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler)); - }; - return TimeoutWithOperator; -}()); -var TimeoutWithSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TimeoutWithSubscriber, _super); - function TimeoutWithSubscriber(destination, absoluteTimeout, waitFor, withObservable, scheduler) { - var _this = _super.call(this, destination) || this; - _this.absoluteTimeout = absoluteTimeout; - _this.waitFor = waitFor; - _this.withObservable = withObservable; - _this.scheduler = scheduler; - _this.action = null; - _this.scheduleTimeout(); - return _this; - } - TimeoutWithSubscriber.dispatchTimeout = function (subscriber) { - var withObservable = subscriber.withObservable; - subscriber._unsubscribeAndRecycle(); - subscriber.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__["subscribeToResult"])(subscriber, withObservable)); - }; - TimeoutWithSubscriber.prototype.scheduleTimeout = function () { - var action = this.action; - if (action) { - this.action = action.schedule(this, this.waitFor); - } - else { - this.add(this.action = this.scheduler.schedule(TimeoutWithSubscriber.dispatchTimeout, this.waitFor, this)); - } - }; - TimeoutWithSubscriber.prototype._next = function (value) { - if (!this.absoluteTimeout) { - this.scheduleTimeout(); - } - _super.prototype._next.call(this, value); - }; - TimeoutWithSubscriber.prototype._unsubscribe = function () { - this.action = null; - this.scheduler = null; - this.withObservable = null; - }; - return TimeoutWithSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__["OuterSubscriber"])); -//# sourceMappingURL=timeoutWith.js.map + return env; +}; /***/ }), -/* 358 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 360 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timestamp", function() { return timestamp; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Timestamp", function() { return Timestamp; }); -/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(215); -/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(226); -/** PURE_IMPORTS_START _scheduler_async,_map PURE_IMPORTS_END */ +const mimicFn = __webpack_require__(361); -function timestamp(scheduler) { - if (scheduler === void 0) { - scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_0__["async"]; - } - return Object(_map__WEBPACK_IMPORTED_MODULE_1__["map"])(function (value) { return new Timestamp(value, scheduler.now()); }); -} -var Timestamp = /*@__PURE__*/ (function () { - function Timestamp(value, timestamp) { - this.value = value; - this.timestamp = timestamp; - } - return Timestamp; -}()); +const calledFunctions = new WeakMap(); -//# sourceMappingURL=timestamp.js.map +const oneTime = (fn, options = {}) => { + if (typeof fn !== 'function') { + throw new TypeError('Expected a function'); + } + let ret; + let isCalled = false; + let callCount = 0; + const functionName = fn.displayName || fn.name || ''; -/***/ }), -/* 359 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + const onetime = function (...args) { + calledFunctions.set(onetime, ++callCount); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toArray", function() { return toArray; }); -/* harmony import */ var _reduce__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(314); -/** PURE_IMPORTS_START _reduce PURE_IMPORTS_END */ + if (isCalled) { + if (options.throw === true) { + throw new Error(`Function \`${functionName}\` can only be called once`); + } -function toArrayReducer(arr, item, index) { - if (index === 0) { - return [item]; - } - arr.push(item); - return arr; -} -function toArray() { - return Object(_reduce__WEBPACK_IMPORTED_MODULE_0__["reduce"])(toArrayReducer, []); -} -//# sourceMappingURL=toArray.js.map + return ret; + } + isCalled = true; + ret = fn.apply(this, args); + fn = null; -/***/ }), -/* 360 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + return ret; + }; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "window", function() { return window; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(187); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_Subject,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ + mimicFn(onetime, fn); + calledFunctions.set(onetime, callCount); + return onetime; +}; +module.exports = oneTime; +// TODO: Remove this for the next major release +module.exports.default = oneTime; +module.exports.callCount = fn => { + if (!calledFunctions.has(fn)) { + throw new Error(`The given function \`${fn.name}\` is not wrapped by the \`onetime\` package`); + } -function window(windowBoundaries) { - return function windowOperatorFunction(source) { - return source.lift(new WindowOperator(windowBoundaries)); - }; -} -var WindowOperator = /*@__PURE__*/ (function () { - function WindowOperator(windowBoundaries) { - this.windowBoundaries = windowBoundaries; - } - WindowOperator.prototype.call = function (subscriber, source) { - var windowSubscriber = new WindowSubscriber(subscriber); - var sourceSubscription = source.subscribe(windowSubscriber); - if (!sourceSubscription.closed) { - windowSubscriber.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(windowSubscriber, this.windowBoundaries)); - } - return sourceSubscription; - }; - return WindowOperator; -}()); -var WindowSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WindowSubscriber, _super); - function WindowSubscriber(destination) { - var _this = _super.call(this, destination) || this; - _this.window = new _Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"](); - destination.next(_this.window); - return _this; - } - WindowSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.openWindow(); - }; - WindowSubscriber.prototype.notifyError = function (error, innerSub) { - this._error(error); - }; - WindowSubscriber.prototype.notifyComplete = function (innerSub) { - this._complete(); - }; - WindowSubscriber.prototype._next = function (value) { - this.window.next(value); - }; - WindowSubscriber.prototype._error = function (err) { - this.window.error(err); - this.destination.error(err); - }; - WindowSubscriber.prototype._complete = function () { - this.window.complete(); - this.destination.complete(); - }; - WindowSubscriber.prototype._unsubscribe = function () { - this.window = null; - }; - WindowSubscriber.prototype.openWindow = function () { - var prevWindow = this.window; - if (prevWindow) { - prevWindow.complete(); - } - var destination = this.destination; - var newWindow = this.window = new _Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"](); - destination.next(newWindow); - }; - return WindowSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"])); -//# sourceMappingURL=window.js.map + return calledFunctions.get(fn); +}; /***/ }), /* 361 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "windowCount", function() { return windowCount; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(172); -/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(187); -/** PURE_IMPORTS_START tslib,_Subscriber,_Subject PURE_IMPORTS_END */ - -function windowCount(windowSize, startWindowEvery) { - if (startWindowEvery === void 0) { - startWindowEvery = 0; - } - return function windowCountOperatorFunction(source) { - return source.lift(new WindowCountOperator(windowSize, startWindowEvery)); - }; -} -var WindowCountOperator = /*@__PURE__*/ (function () { - function WindowCountOperator(windowSize, startWindowEvery) { - this.windowSize = windowSize; - this.startWindowEvery = startWindowEvery; - } - WindowCountOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new WindowCountSubscriber(subscriber, this.windowSize, this.startWindowEvery)); - }; - return WindowCountOperator; -}()); -var WindowCountSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WindowCountSubscriber, _super); - function WindowCountSubscriber(destination, windowSize, startWindowEvery) { - var _this = _super.call(this, destination) || this; - _this.destination = destination; - _this.windowSize = windowSize; - _this.startWindowEvery = startWindowEvery; - _this.windows = [new _Subject__WEBPACK_IMPORTED_MODULE_2__["Subject"]()]; - _this.count = 0; - destination.next(_this.windows[0]); - return _this; - } - WindowCountSubscriber.prototype._next = function (value) { - var startWindowEvery = (this.startWindowEvery > 0) ? this.startWindowEvery : this.windowSize; - var destination = this.destination; - var windowSize = this.windowSize; - var windows = this.windows; - var len = windows.length; - for (var i = 0; i < len && !this.closed; i++) { - windows[i].next(value); - } - var c = this.count - windowSize + 1; - if (c >= 0 && c % startWindowEvery === 0 && !this.closed) { - windows.shift().complete(); - } - if (++this.count % startWindowEvery === 0 && !this.closed) { - var window_1 = new _Subject__WEBPACK_IMPORTED_MODULE_2__["Subject"](); - windows.push(window_1); - destination.next(window_1); - } - }; - WindowCountSubscriber.prototype._error = function (err) { - var windows = this.windows; - if (windows) { - while (windows.length > 0 && !this.closed) { - windows.shift().error(err); - } - } - this.destination.error(err); - }; - WindowCountSubscriber.prototype._complete = function () { - var windows = this.windows; - if (windows) { - while (windows.length > 0 && !this.closed) { - windows.shift().complete(); - } - } - this.destination.complete(); - }; - WindowCountSubscriber.prototype._unsubscribe = function () { - this.count = 0; - this.windows = null; - }; - return WindowCountSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__["Subscriber"])); -//# sourceMappingURL=windowCount.js.map +const mimicFn = (to, from) => { + for (const prop of Reflect.ownKeys(from)) { + Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); + } + + return to; +}; + +module.exports = mimicFn; +// TODO: Remove this for the next major release +module.exports.default = mimicFn; /***/ }), /* 362 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "windowTime", function() { return windowTime; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(187); -/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(215); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(172); -/* harmony import */ var _util_isNumeric__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(257); -/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(205); -/** PURE_IMPORTS_START tslib,_Subject,_scheduler_async,_Subscriber,_util_isNumeric,_util_isScheduler PURE_IMPORTS_END */ +const {signalsByName} = __webpack_require__(363); +const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => { + if (timedOut) { + return `timed out after ${timeout} milliseconds`; + } + if (isCanceled) { + return 'was canceled'; + } + if (errorCode !== undefined) { + return `failed with ${errorCode}`; + } + if (signal !== undefined) { + return `was killed with ${signal} (${signalDescription})`; + } -function windowTime(windowTimeSpan) { - var scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_2__["async"]; - var windowCreationInterval = null; - var maxWindowSize = Number.POSITIVE_INFINITY; - if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_5__["isScheduler"])(arguments[3])) { - scheduler = arguments[3]; - } - if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_5__["isScheduler"])(arguments[2])) { - scheduler = arguments[2]; - } - else if (Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_4__["isNumeric"])(arguments[2])) { - maxWindowSize = arguments[2]; - } - if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_5__["isScheduler"])(arguments[1])) { - scheduler = arguments[1]; - } - else if (Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_4__["isNumeric"])(arguments[1])) { - windowCreationInterval = arguments[1]; - } - return function windowTimeOperatorFunction(source) { - return source.lift(new WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler)); - }; -} -var WindowTimeOperator = /*@__PURE__*/ (function () { - function WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) { - this.windowTimeSpan = windowTimeSpan; - this.windowCreationInterval = windowCreationInterval; - this.maxWindowSize = maxWindowSize; - this.scheduler = scheduler; - } - WindowTimeOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new WindowTimeSubscriber(subscriber, this.windowTimeSpan, this.windowCreationInterval, this.maxWindowSize, this.scheduler)); - }; - return WindowTimeOperator; -}()); -var CountedSubject = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CountedSubject, _super); - function CountedSubject() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this._numberOfNextedValues = 0; - return _this; - } - CountedSubject.prototype.next = function (value) { - this._numberOfNextedValues++; - _super.prototype.next.call(this, value); - }; - Object.defineProperty(CountedSubject.prototype, "numberOfNextedValues", { - get: function () { - return this._numberOfNextedValues; - }, - enumerable: true, - configurable: true - }); - return CountedSubject; -}(_Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"])); -var WindowTimeSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WindowTimeSubscriber, _super); - function WindowTimeSubscriber(destination, windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) { - var _this = _super.call(this, destination) || this; - _this.destination = destination; - _this.windowTimeSpan = windowTimeSpan; - _this.windowCreationInterval = windowCreationInterval; - _this.maxWindowSize = maxWindowSize; - _this.scheduler = scheduler; - _this.windows = []; - var window = _this.openWindow(); - if (windowCreationInterval !== null && windowCreationInterval >= 0) { - var closeState = { subscriber: _this, window: window, context: null }; - var creationState = { windowTimeSpan: windowTimeSpan, windowCreationInterval: windowCreationInterval, subscriber: _this, scheduler: scheduler }; - _this.add(scheduler.schedule(dispatchWindowClose, windowTimeSpan, closeState)); - _this.add(scheduler.schedule(dispatchWindowCreation, windowCreationInterval, creationState)); - } - else { - var timeSpanOnlyState = { subscriber: _this, window: window, windowTimeSpan: windowTimeSpan }; - _this.add(scheduler.schedule(dispatchWindowTimeSpanOnly, windowTimeSpan, timeSpanOnlyState)); - } - return _this; - } - WindowTimeSubscriber.prototype._next = function (value) { - var windows = this.windows; - var len = windows.length; - for (var i = 0; i < len; i++) { - var window_1 = windows[i]; - if (!window_1.closed) { - window_1.next(value); - if (window_1.numberOfNextedValues >= this.maxWindowSize) { - this.closeWindow(window_1); - } - } - } - }; - WindowTimeSubscriber.prototype._error = function (err) { - var windows = this.windows; - while (windows.length > 0) { - windows.shift().error(err); - } - this.destination.error(err); - }; - WindowTimeSubscriber.prototype._complete = function () { - var windows = this.windows; - while (windows.length > 0) { - var window_2 = windows.shift(); - if (!window_2.closed) { - window_2.complete(); - } - } - this.destination.complete(); - }; - WindowTimeSubscriber.prototype.openWindow = function () { - var window = new CountedSubject(); - this.windows.push(window); - var destination = this.destination; - destination.next(window); - return window; - }; - WindowTimeSubscriber.prototype.closeWindow = function (window) { - window.complete(); - var windows = this.windows; - windows.splice(windows.indexOf(window), 1); - }; - return WindowTimeSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_3__["Subscriber"])); -function dispatchWindowTimeSpanOnly(state) { - var subscriber = state.subscriber, windowTimeSpan = state.windowTimeSpan, window = state.window; - if (window) { - subscriber.closeWindow(window); - } - state.window = subscriber.openWindow(); - this.schedule(state, windowTimeSpan); -} -function dispatchWindowCreation(state) { - var windowTimeSpan = state.windowTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler, windowCreationInterval = state.windowCreationInterval; - var window = subscriber.openWindow(); - var action = this; - var context = { action: action, subscription: null }; - var timeSpanState = { subscriber: subscriber, window: window, context: context }; - context.subscription = scheduler.schedule(dispatchWindowClose, windowTimeSpan, timeSpanState); - action.add(context.subscription); - action.schedule(state, windowCreationInterval); -} -function dispatchWindowClose(state) { - var subscriber = state.subscriber, window = state.window, context = state.context; - if (context && context.action && context.subscription) { - context.action.remove(context.subscription); - } - subscriber.closeWindow(window); -} -//# sourceMappingURL=windowTime.js.map + if (exitCode !== undefined) { + return `failed with exit code ${exitCode}`; + } + + return 'failed'; +}; + +const makeError = ({ + stdout, + stderr, + all, + error, + signal, + exitCode, + command, + timedOut, + isCanceled, + killed, + parsed: {options: {timeout}} +}) => { + // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`. + // We normalize them to `undefined` + exitCode = exitCode === null ? undefined : exitCode; + signal = signal === null ? undefined : signal; + const signalDescription = signal === undefined ? undefined : signalsByName[signal].description; + + const errorCode = error && error.code; + + const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}); + const execaMessage = `Command ${prefix}: ${command}`; + const isError = Object.prototype.toString.call(error) === '[object Error]'; + const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage; + const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n'); + + if (isError) { + error.originalMessage = error.message; + error.message = message; + } else { + error = new Error(message); + } + + error.shortMessage = shortMessage; + error.command = command; + error.exitCode = exitCode; + error.signal = signal; + error.signalDescription = signalDescription; + error.stdout = stdout; + error.stderr = stderr; + + if (all !== undefined) { + error.all = all; + } + + if ('bufferedData' in error) { + delete error.bufferedData; + } + + error.failed = true; + error.timedOut = Boolean(timedOut); + error.isCanceled = isCanceled; + error.killed = killed && !timedOut; + + return error; +}; + +module.exports = makeError; /***/ }), /* 363 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "windowToggle", function() { return windowToggle; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(187); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(177); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_Subject,_Subscription,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ +Object.defineProperty(exports,"__esModule",{value:true});exports.signalsByNumber=exports.signalsByName=void 0;var _os=__webpack_require__(364); +var _signals=__webpack_require__(365); +var _realtime=__webpack_require__(367); +const getSignalsByName=function(){ +const signals=(0,_signals.getSignals)(); +return signals.reduce(getSignalByName,{}); +}; -function windowToggle(openings, closingSelector) { - return function (source) { return source.lift(new WindowToggleOperator(openings, closingSelector)); }; +const getSignalByName=function( +signalByNameMemo, +{name,number,description,supported,action,forced,standard}) +{ +return{ +...signalByNameMemo, +[name]:{name,number,description,supported,action,forced,standard}}; + +}; + +const signalsByName=getSignalsByName();exports.signalsByName=signalsByName; + + + + +const getSignalsByNumber=function(){ +const signals=(0,_signals.getSignals)(); +const length=_realtime.SIGRTMAX+1; +const signalsA=Array.from({length},(value,number)=> +getSignalByNumber(number,signals)); + +return Object.assign({},...signalsA); +}; + +const getSignalByNumber=function(number,signals){ +const signal=findSignalByNumber(number,signals); + +if(signal===undefined){ +return{}; } -var WindowToggleOperator = /*@__PURE__*/ (function () { - function WindowToggleOperator(openings, closingSelector) { - this.openings = openings; - this.closingSelector = closingSelector; - } - WindowToggleOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new WindowToggleSubscriber(subscriber, this.openings, this.closingSelector)); - }; - return WindowToggleOperator; -}()); -var WindowToggleSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WindowToggleSubscriber, _super); - function WindowToggleSubscriber(destination, openings, closingSelector) { - var _this = _super.call(this, destination) || this; - _this.openings = openings; - _this.closingSelector = closingSelector; - _this.contexts = []; - _this.add(_this.openSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__["subscribeToResult"])(_this, openings, openings)); - return _this; - } - WindowToggleSubscriber.prototype._next = function (value) { - var contexts = this.contexts; - if (contexts) { - var len = contexts.length; - for (var i = 0; i < len; i++) { - contexts[i].window.next(value); - } - } - }; - WindowToggleSubscriber.prototype._error = function (err) { - var contexts = this.contexts; - this.contexts = null; - if (contexts) { - var len = contexts.length; - var index = -1; - while (++index < len) { - var context_1 = contexts[index]; - context_1.window.error(err); - context_1.subscription.unsubscribe(); - } - } - _super.prototype._error.call(this, err); - }; - WindowToggleSubscriber.prototype._complete = function () { - var contexts = this.contexts; - this.contexts = null; - if (contexts) { - var len = contexts.length; - var index = -1; - while (++index < len) { - var context_2 = contexts[index]; - context_2.window.complete(); - context_2.subscription.unsubscribe(); - } - } - _super.prototype._complete.call(this); - }; - WindowToggleSubscriber.prototype._unsubscribe = function () { - var contexts = this.contexts; - this.contexts = null; - if (contexts) { - var len = contexts.length; - var index = -1; - while (++index < len) { - var context_3 = contexts[index]; - context_3.window.unsubscribe(); - context_3.subscription.unsubscribe(); - } - } - }; - WindowToggleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - if (outerValue === this.openings) { - var closingNotifier = void 0; - try { - var closingSelector = this.closingSelector; - closingNotifier = closingSelector(innerValue); - } - catch (e) { - return this.error(e); - } - var window_1 = new _Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"](); - var subscription = new _Subscription__WEBPACK_IMPORTED_MODULE_2__["Subscription"](); - var context_4 = { window: window_1, subscription: subscription }; - this.contexts.push(context_4); - var innerSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__["subscribeToResult"])(this, closingNotifier, context_4); - if (innerSubscription.closed) { - this.closeWindow(this.contexts.length - 1); - } - else { - innerSubscription.context = context_4; - subscription.add(innerSubscription); - } - this.destination.next(window_1); - } - else { - this.closeWindow(this.contexts.indexOf(outerValue)); - } - }; - WindowToggleSubscriber.prototype.notifyError = function (err) { - this.error(err); - }; - WindowToggleSubscriber.prototype.notifyComplete = function (inner) { - if (inner !== this.openSubscription) { - this.closeWindow(this.contexts.indexOf(inner.context)); - } - }; - WindowToggleSubscriber.prototype.closeWindow = function (index) { - if (index === -1) { - return; - } - var contexts = this.contexts; - var context = contexts[index]; - var window = context.window, subscription = context.subscription; - contexts.splice(index, 1); - window.complete(); - subscription.unsubscribe(); - }; - return WindowToggleSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__["OuterSubscriber"])); -//# sourceMappingURL=windowToggle.js.map +const{name,description,supported,action,forced,standard}=signal; +return{ +[number]:{ +name, +number, +description, +supported, +action, +forced, +standard}}; -/***/ }), -/* 364 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "windowWhen", function() { return windowWhen; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(187); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_Subject,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ +}; +const findSignalByNumber=function(number,signals){ +const signal=signals.find(({name})=>_os.constants.signals[name]===number); -function windowWhen(closingSelector) { - return function windowWhenOperatorFunction(source) { - return source.lift(new WindowOperator(closingSelector)); - }; +if(signal!==undefined){ +return signal; } -var WindowOperator = /*@__PURE__*/ (function () { - function WindowOperator(closingSelector) { - this.closingSelector = closingSelector; - } - WindowOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new WindowSubscriber(subscriber, this.closingSelector)); - }; - return WindowOperator; -}()); -var WindowSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WindowSubscriber, _super); - function WindowSubscriber(destination, closingSelector) { - var _this = _super.call(this, destination) || this; - _this.destination = destination; - _this.closingSelector = closingSelector; - _this.openWindow(); - return _this; - } - WindowSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.openWindow(innerSub); - }; - WindowSubscriber.prototype.notifyError = function (error, innerSub) { - this._error(error); - }; - WindowSubscriber.prototype.notifyComplete = function (innerSub) { - this.openWindow(innerSub); - }; - WindowSubscriber.prototype._next = function (value) { - this.window.next(value); - }; - WindowSubscriber.prototype._error = function (err) { - this.window.error(err); - this.destination.error(err); - this.unsubscribeClosingNotification(); - }; - WindowSubscriber.prototype._complete = function () { - this.window.complete(); - this.destination.complete(); - this.unsubscribeClosingNotification(); - }; - WindowSubscriber.prototype.unsubscribeClosingNotification = function () { - if (this.closingNotification) { - this.closingNotification.unsubscribe(); - } - }; - WindowSubscriber.prototype.openWindow = function (innerSub) { - if (innerSub === void 0) { - innerSub = null; - } - if (innerSub) { - this.remove(innerSub); - innerSub.unsubscribe(); - } - var prevWindow = this.window; - if (prevWindow) { - prevWindow.complete(); - } - var window = this.window = new _Subject__WEBPACK_IMPORTED_MODULE_1__["Subject"](); - this.destination.next(window); - var closingNotifier; - try { - var closingSelector = this.closingSelector; - closingNotifier = closingSelector(); - } - catch (e) { - this.destination.error(e); - this.window.error(e); - return; - } - this.add(this.closingNotification = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_3__["subscribeToResult"])(this, closingNotifier)); - }; - return WindowSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__["OuterSubscriber"])); -//# sourceMappingURL=windowWhen.js.map - - -/***/ }), -/* 365 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withLatestFrom", function() { return withLatestFrom; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(229); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(230); -/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ - - - -function withLatestFrom() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return function (source) { - var project; - if (typeof args[args.length - 1] === 'function') { - project = args.pop(); - } - var observables = args; - return source.lift(new WithLatestFromOperator(observables, project)); - }; -} -var WithLatestFromOperator = /*@__PURE__*/ (function () { - function WithLatestFromOperator(observables, project) { - this.observables = observables; - this.project = project; - } - WithLatestFromOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project)); - }; - return WithLatestFromOperator; -}()); -var WithLatestFromSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WithLatestFromSubscriber, _super); - function WithLatestFromSubscriber(destination, observables, project) { - var _this = _super.call(this, destination) || this; - _this.observables = observables; - _this.project = project; - _this.toRespond = []; - var len = observables.length; - _this.values = new Array(len); - for (var i = 0; i < len; i++) { - _this.toRespond.push(i); - } - for (var i = 0; i < len; i++) { - var observable = observables[i]; - _this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_2__["subscribeToResult"])(_this, observable, observable, i)); - } - return _this; - } - WithLatestFromSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.values[outerIndex] = innerValue; - var toRespond = this.toRespond; - if (toRespond.length > 0) { - var found = toRespond.indexOf(outerIndex); - if (found !== -1) { - toRespond.splice(found, 1); - } - } - }; - WithLatestFromSubscriber.prototype.notifyComplete = function () { - }; - WithLatestFromSubscriber.prototype._next = function (value) { - if (this.toRespond.length === 0) { - var args = [value].concat(this.values); - if (this.project) { - this._tryProject(args); - } - else { - this.destination.next(args); - } - } - }; - WithLatestFromSubscriber.prototype._tryProject = function (args) { - var result; - try { - result = this.project.apply(this, args); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.next(result); - }; - return WithLatestFromSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_1__["OuterSubscriber"])); -//# sourceMappingURL=withLatestFrom.js.map - - -/***/ }), -/* 366 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "zip", function() { return zip; }); -/* harmony import */ var _observable_zip__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(269); -/** PURE_IMPORTS_START _observable_zip PURE_IMPORTS_END */ -function zip() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; - } - return function zipOperatorFunction(source) { - return source.lift.call(_observable_zip__WEBPACK_IMPORTED_MODULE_0__["zip"].apply(void 0, [source].concat(observables))); - }; -} -//# sourceMappingURL=zip.js.map +return signals.find(signalA=>signalA.number===number); +}; +const signalsByNumber=getSignalsByNumber();exports.signalsByNumber=signalsByNumber; +//# sourceMappingURL=main.js.map /***/ }), -/* 367 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "zipAll", function() { return zipAll; }); -/* harmony import */ var _observable_zip__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(269); -/** PURE_IMPORTS_START _observable_zip PURE_IMPORTS_END */ - -function zipAll(project) { - return function (source) { return source.lift(new _observable_zip__WEBPACK_IMPORTED_MODULE_0__["ZipOperator"](project)); }; -} -//# sourceMappingURL=zipAll.js.map +/* 364 */ +/***/ (function(module, exports) { +module.exports = require("os"); /***/ }), -/* 368 */ +/* 365 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +Object.defineProperty(exports,"__esModule",{value:true});exports.getSignals=void 0;var _os=__webpack_require__(364); +var _core=__webpack_require__(366); +var _realtime=__webpack_require__(367); -const callbacks = new Set(); -let called = false; -function exit(exit, signal) { - if (called) { - return; - } - called = true; +const getSignals=function(){ +const realtimeSignals=(0,_realtime.getRealtimeSignals)(); +const signals=[..._core.SIGNALS,...realtimeSignals].map(normalizeSignal); +return signals; +};exports.getSignals=getSignals; - for (const callback of callbacks) { - callback(); - } - if (exit === true) { - process.exit(128 + signal); // eslint-disable-line unicorn/no-process-exit - } -} -module.exports = callback => { - callbacks.add(callback); - if (callbacks.size === 1) { - process.once('exit', exit); - process.once('SIGINT', exit.bind(null, true, 2)); - process.once('SIGTERM', exit.bind(null, true, 15)); - // PM2 Cluster shutdown message. Caught to support async handlers with pm2, needed because - // explicitly calling process.exit() doesn't trigger the beforeExit event, and the exit - // event cannot support async handlers, since the event loop is never called after it. - process.on('message', message => { - if (message === 'shutdown') { - exit(true, -128); - } - }); - } - return () => { - callbacks.delete(callback); - }; -}; +const normalizeSignal=function({ +name, +number:defaultNumber, +description, +action, +forced=false, +standard}) +{ +const{ +signals:{[name]:constantSignal}}= +_os.constants; +const supported=constantSignal!==undefined; +const number=supported?constantSignal:defaultNumber; +return{name,number,description,supported,action,forced,standard}; +}; +//# sourceMappingURL=signals.js.map /***/ }), -/* 369 */ +/* 366 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +Object.defineProperty(exports,"__esModule",{value:true});exports.SIGNALS=void 0; -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const $isCliError = Symbol('isCliError'); -function createCliError(message) { - const error = new Error(message); - error[$isCliError] = true; - return error; -} -exports.createCliError = createCliError; -function isCliError(error) { - return error && !!error[$isCliError]; -} -exports.isCliError = isCliError; +const SIGNALS=[ +{ +name:"SIGHUP", +number:1, +action:"terminate", +description:"Terminal closed", +standard:"posix"}, +{ +name:"SIGINT", +number:2, +action:"terminate", +description:"User interruption with CTRL-C", +standard:"ansi"}, -/***/ }), -/* 370 */ -/***/ (function(module, exports, __webpack_require__) { +{ +name:"SIGQUIT", +number:3, +action:"core", +description:"User interruption with CTRL-\\", +standard:"posix"}, -"use strict"; +{ +name:"SIGILL", +number:4, +action:"core", +description:"Invalid machine instruction", +standard:"ansi"}, -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(36); -const execa_1 = tslib_1.__importDefault(__webpack_require__(371)); -const fs_1 = __webpack_require__(23); -const Rx = tslib_1.__importStar(__webpack_require__(169)); -const operators_1 = __webpack_require__(270); -const chalk_1 = tslib_1.__importDefault(__webpack_require__(2)); -const tree_kill_1 = tslib_1.__importDefault(__webpack_require__(411)); -const util_1 = __webpack_require__(29); -const treeKillAsync = util_1.promisify((...args) => tree_kill_1.default(...args)); -const observe_lines_1 = __webpack_require__(412); -const errors_1 = __webpack_require__(369); -const SECOND = 1000; -const STOP_TIMEOUT = 30 * SECOND; -async function withTimeout(attempt, ms, onTimeout) { - const TIMEOUT = Symbol('timeout'); - try { - await Promise.race([ - attempt(), - new Promise((_, reject) => setTimeout(() => reject(TIMEOUT), ms)), - ]); - } - catch (error) { - if (error === TIMEOUT) { - await onTimeout(); - } - else { - throw error; - } - } -} -function startProc(name, options, log) { - const { cmd, args, cwd, env, stdin } = options; - log.info('[%s] > %s', name, cmd, args.join(' ')); - // spawn fails with ENOENT when either the - // cmd or cwd don't exist, so we check for the cwd - // ahead of time so that the error is less ambiguous - try { - if (!fs_1.statSync(cwd).isDirectory()) { - throw new Error(`cwd "${cwd}" exists but is not a directory`); - } - } - catch (err) { - if (err.code === 'ENOENT') { - throw new Error(`cwd "${cwd}" does not exist`); - } - } - const childProcess = execa_1.default(cmd, args, { - cwd, - env, - stdio: ['pipe', 'pipe', 'pipe'], - preferLocal: true, - }); - if (stdin) { - childProcess.stdin.end(stdin, 'utf8'); - } - else { - childProcess.stdin.end(); - } - let stopCalled = false; - const outcome$ = Rx.race( - // observe first exit event - Rx.fromEvent(childProcess, 'exit').pipe(operators_1.take(1), operators_1.map(([code]) => { - if (stopCalled) { - return null; - } - // JVM exits with 143 on SIGTERM and 130 on SIGINT, dont' treat then as errors - if (code > 0 && !(code === 143 || code === 130)) { - throw errors_1.createCliError(`[${name}] exited with code ${code}`); - } - return code; - })), - // observe first error event - Rx.fromEvent(childProcess, 'error').pipe(operators_1.take(1), operators_1.mergeMap((err) => Rx.throwError(err)))).pipe(operators_1.share()); - const lines$ = Rx.merge(observe_lines_1.observeLines(childProcess.stdout), observe_lines_1.observeLines(childProcess.stderr)).pipe(operators_1.tap((line) => log.write(` ${chalk_1.default.gray('proc')} [${chalk_1.default.gray(name)}] ${line}`)), operators_1.share()); - const outcomePromise = Rx.merge(lines$.pipe(operators_1.ignoreElements()), outcome$).toPromise(); - async function stop(signal) { - if (stopCalled) { - return; - } - stopCalled = true; - await withTimeout(async () => { - log.debug(`Sending "${signal}" to proc "${name}"`); - await treeKillAsync(childProcess.pid, signal); - await outcomePromise; - }, STOP_TIMEOUT, async () => { - log.warning(`Proc "${name}" was sent "${signal}" didn't emit the "exit" or "error" events after ${STOP_TIMEOUT} ms, sending SIGKILL`); - await treeKillAsync(childProcess.pid, 'SIGKILL'); - }); - await withTimeout(async () => { - try { - await outcomePromise; - } - catch (error) { - // ignore - } - }, STOP_TIMEOUT, async () => { - throw new Error(`Proc "${name}" was stopped but never emitted either the "exit" or "error" event after ${STOP_TIMEOUT} ms`); - }); - } - return { - name, - lines$, - outcome$, - outcomePromise, - stop, - }; -} -exports.startProc = startProc; +{ +name:"SIGTRAP", +number:5, +action:"core", +description:"Debugger breakpoint", +standard:"posix"}, +{ +name:"SIGABRT", +number:6, +action:"core", +description:"Aborted", +standard:"ansi"}, -/***/ }), -/* 371 */ -/***/ (function(module, exports, __webpack_require__) { +{ +name:"SIGIOT", +number:6, +action:"core", +description:"Aborted", +standard:"bsd"}, -"use strict"; +{ +name:"SIGBUS", +number:7, +action:"core", +description: +"Bus error due to misaligned, non-existing address or paging error", +standard:"bsd"}, -const path = __webpack_require__(16); -const childProcess = __webpack_require__(372); -const crossSpawn = __webpack_require__(373); -const stripFinalNewline = __webpack_require__(386); -const npmRunPath = __webpack_require__(387); -const onetime = __webpack_require__(388); -const makeError = __webpack_require__(390); -const normalizeStdio = __webpack_require__(395); -const {spawnedKill, spawnedCancel, setupTimeout, setExitHandler} = __webpack_require__(396); -const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = __webpack_require__(400); -const {mergePromise, getSpawnedPromise} = __webpack_require__(409); -const {joinCommand, parseCommand} = __webpack_require__(410); +{ +name:"SIGEMT", +number:7, +action:"terminate", +description:"Command should be emulated but is not implemented", +standard:"other"}, -const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100; +{ +name:"SIGFPE", +number:8, +action:"core", +description:"Floating point arithmetic error", +standard:"ansi"}, -const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => { - const env = extendEnv ? {...process.env, ...envOption} : envOption; +{ +name:"SIGKILL", +number:9, +action:"terminate", +description:"Forced termination", +standard:"posix", +forced:true}, - if (preferLocal) { - return npmRunPath.env({env, cwd: localDir, execPath}); - } +{ +name:"SIGUSR1", +number:10, +action:"terminate", +description:"Application-specific signal", +standard:"posix"}, - return env; -}; +{ +name:"SIGSEGV", +number:11, +action:"core", +description:"Segmentation fault", +standard:"ansi"}, -const handleArgs = (file, args, options = {}) => { - const parsed = crossSpawn._parse(file, args, options); - file = parsed.command; - args = parsed.args; - options = parsed.options; +{ +name:"SIGUSR2", +number:12, +action:"terminate", +description:"Application-specific signal", +standard:"posix"}, - options = { - maxBuffer: DEFAULT_MAX_BUFFER, - buffer: true, - stripFinalNewline: true, - extendEnv: true, - preferLocal: false, - localDir: options.cwd || process.cwd(), - execPath: process.execPath, - encoding: 'utf8', - reject: true, - cleanup: true, - all: false, - windowsHide: true, - ...options - }; +{ +name:"SIGPIPE", +number:13, +action:"terminate", +description:"Broken pipe or socket", +standard:"posix"}, - options.env = getEnv(options); +{ +name:"SIGALRM", +number:14, +action:"terminate", +description:"Timeout or timer", +standard:"posix"}, - options.stdio = normalizeStdio(options); +{ +name:"SIGTERM", +number:15, +action:"terminate", +description:"Termination", +standard:"ansi"}, - if (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') { - // #116 - args.unshift('/q'); - } +{ +name:"SIGSTKFLT", +number:16, +action:"terminate", +description:"Stack is empty or overflowed", +standard:"other"}, - return {file, args, options, parsed}; -}; +{ +name:"SIGCHLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"posix"}, -const handleOutput = (options, value, error) => { - if (typeof value !== 'string' && !Buffer.isBuffer(value)) { - // When `execa.sync()` errors, we normalize it to '' to mimic `execa()` - return error === undefined ? undefined : ''; - } +{ +name:"SIGCLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"other"}, - if (options.stripFinalNewline) { - return stripFinalNewline(value); - } +{ +name:"SIGCONT", +number:18, +action:"unpause", +description:"Unpaused", +standard:"posix", +forced:true}, - return value; -}; +{ +name:"SIGSTOP", +number:19, +action:"pause", +description:"Paused", +standard:"posix", +forced:true}, -const execa = (file, args, options) => { - const parsed = handleArgs(file, args, options); - const command = joinCommand(file, args); +{ +name:"SIGTSTP", +number:20, +action:"pause", +description:"Paused using CTRL-Z or \"suspend\"", +standard:"posix"}, - let spawned; - try { - spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options); - } catch (error) { - // Ensure the returned error is always both a promise and a child process - const dummySpawned = new childProcess.ChildProcess(); - const errorPromise = Promise.reject(makeError({ - error, - stdout: '', - stderr: '', - all: '', - command, - parsed, - timedOut: false, - isCanceled: false, - killed: false - })); - return mergePromise(dummySpawned, errorPromise); - } +{ +name:"SIGTTIN", +number:21, +action:"pause", +description:"Background process cannot read terminal input", +standard:"posix"}, - const spawnedPromise = getSpawnedPromise(spawned); - const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise); - const processDone = setExitHandler(spawned, parsed.options, timedPromise); +{ +name:"SIGBREAK", +number:21, +action:"terminate", +description:"User interruption with CTRL-BREAK", +standard:"other"}, - const context = {isCanceled: false}; +{ +name:"SIGTTOU", +number:22, +action:"pause", +description:"Background process cannot write to terminal output", +standard:"posix"}, - spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned)); - spawned.cancel = spawnedCancel.bind(null, spawned, context); +{ +name:"SIGURG", +number:23, +action:"ignore", +description:"Socket received out-of-band data", +standard:"bsd"}, - const handlePromise = async () => { - const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone); - const stdout = handleOutput(parsed.options, stdoutResult); - const stderr = handleOutput(parsed.options, stderrResult); - const all = handleOutput(parsed.options, allResult); +{ +name:"SIGXCPU", +number:24, +action:"core", +description:"Process timed out", +standard:"bsd"}, - if (error || exitCode !== 0 || signal !== null) { - const returnedError = makeError({ - error, - exitCode, - signal, - stdout, - stderr, - all, - command, - parsed, - timedOut, - isCanceled: context.isCanceled, - killed: spawned.killed - }); +{ +name:"SIGXFSZ", +number:25, +action:"core", +description:"File too big", +standard:"bsd"}, - if (!parsed.options.reject) { - return returnedError; - } +{ +name:"SIGVTALRM", +number:26, +action:"terminate", +description:"Timeout or timer", +standard:"bsd"}, - throw returnedError; - } +{ +name:"SIGPROF", +number:27, +action:"terminate", +description:"Timeout or timer", +standard:"bsd"}, - return { - command, - exitCode: 0, - stdout, - stderr, - all, - failed: false, - timedOut: false, - isCanceled: false, - killed: false - }; - }; +{ +name:"SIGWINCH", +number:28, +action:"ignore", +description:"Terminal window size changed", +standard:"bsd"}, - const handlePromiseOnce = onetime(handlePromise); +{ +name:"SIGIO", +number:29, +action:"terminate", +description:"I/O is available", +standard:"other"}, - crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed); +{ +name:"SIGPOLL", +number:29, +action:"terminate", +description:"Watched event", +standard:"other"}, - handleInput(spawned, parsed.options.input); +{ +name:"SIGINFO", +number:29, +action:"ignore", +description:"Request for process information", +standard:"other"}, - spawned.all = makeAllStream(spawned, parsed.options); +{ +name:"SIGPWR", +number:30, +action:"terminate", +description:"Device running out of power", +standard:"systemv"}, + +{ +name:"SIGSYS", +number:31, +action:"core", +description:"Invalid system call", +standard:"other"}, + +{ +name:"SIGUNUSED", +number:31, +action:"terminate", +description:"Invalid system call", +standard:"other"}];exports.SIGNALS=SIGNALS; +//# sourceMappingURL=core.js.map + +/***/ }), +/* 367 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +Object.defineProperty(exports,"__esModule",{value:true});exports.SIGRTMAX=exports.getRealtimeSignals=void 0; +const getRealtimeSignals=function(){ +const length=SIGRTMAX-SIGRTMIN+1; +return Array.from({length},getRealtimeSignal); +};exports.getRealtimeSignals=getRealtimeSignals; + +const getRealtimeSignal=function(value,index){ +return{ +name:`SIGRT${index+1}`, +number:SIGRTMIN+index, +action:"terminate", +description:"Application-specific signal (realtime)", +standard:"posix"}; - return mergePromise(spawned, handlePromiseOnce); }; -module.exports = execa; +const SIGRTMIN=34; +const SIGRTMAX=64;exports.SIGRTMAX=SIGRTMAX; +//# sourceMappingURL=realtime.js.map -module.exports.sync = (file, args, options) => { - const parsed = handleArgs(file, args, options); - const command = joinCommand(file, args); +/***/ }), +/* 368 */ +/***/ (function(module, exports, __webpack_require__) { - validateInputSync(parsed.options); +"use strict"; - let result; - try { - result = childProcess.spawnSync(parsed.file, parsed.args, parsed.options); - } catch (error) { - throw makeError({ - error, - stdout: '', - stderr: '', - all: '', - command, - parsed, - timedOut: false, - isCanceled: false, - killed: false - }); +const aliases = ['stdin', 'stdout', 'stderr']; + +const hasAlias = opts => aliases.some(alias => opts[alias] !== undefined); + +const normalizeStdio = opts => { + if (!opts) { + return; } - const stdout = handleOutput(parsed.options, result.stdout, result.error); - const stderr = handleOutput(parsed.options, result.stderr, result.error); + const {stdio} = opts; - if (result.error || result.status !== 0 || result.signal !== null) { - const error = makeError({ - stdout, - stderr, - error: result.error, - signal: result.signal, - exitCode: result.status, - command, - parsed, - timedOut: result.error && result.error.code === 'ETIMEDOUT', - isCanceled: false, - killed: result.signal !== null - }); + if (stdio === undefined) { + return aliases.map(alias => opts[alias]); + } - if (!parsed.options.reject) { - return error; - } + if (hasAlias(opts)) { + throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`); + } - throw error; + if (typeof stdio === 'string') { + return stdio; } - return { - command, - exitCode: 0, - stdout, - stderr, - failed: false, - timedOut: false, - isCanceled: false, - killed: false - }; -}; + if (!Array.isArray(stdio)) { + throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); + } -module.exports.command = (command, options) => { - const [file, ...args] = parseCommand(command); - return execa(file, args, options); + const length = Math.max(stdio.length, aliases.length); + return Array.from({length}, (value, index) => stdio[index]); }; -module.exports.commandSync = (command, options) => { - const [file, ...args] = parseCommand(command); - return execa.sync(file, args, options); -}; +module.exports = normalizeStdio; -module.exports.node = (scriptPath, args, options = {}) => { - if (args && !Array.isArray(args) && typeof args === 'object') { - options = args; - args = []; +// `ipc` is pushed unless it is already present +module.exports.node = opts => { + const stdio = normalizeStdio(opts); + + if (stdio === 'ipc') { + return 'ipc'; } - const stdio = normalizeStdio.node(options); + if (stdio === undefined || typeof stdio === 'string') { + return [stdio, stdio, stdio, 'ipc']; + } - const {nodePath = process.execPath, nodeOptions = process.execArgv} = options; + if (stdio.includes('ipc')) { + return stdio; + } - return execa( - nodePath, - [ - ...nodeOptions, - scriptPath, - ...(Array.isArray(args) ? args : []) - ], - { - ...options, - stdin: undefined, - stdout: undefined, - stderr: undefined, - stdio, - shell: false - } - ); + return [...stdio, 'ipc']; }; /***/ }), -/* 372 */ -/***/ (function(module, exports) { - -module.exports = require("child_process"); - -/***/ }), -/* 373 */ +/* 369 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +const os = __webpack_require__(364); +const onExit = __webpack_require__(370); -const cp = __webpack_require__(372); -const parse = __webpack_require__(374); -const enoent = __webpack_require__(385); +const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5; -function spawn(command, args, options) { - // Parse the arguments - const parsed = parse(command, args, options); +// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior +const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => { + const killResult = kill(signal); + setKillTimeout(kill, signal, options, killResult); + return killResult; +}; - // Spawn the child process - const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); +const setKillTimeout = (kill, signal, options, killResult) => { + if (!shouldForceKill(signal, options, killResult)) { + return; + } - // Hook into child process "exit" event to emit an error if the command - // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - enoent.hookChildProcess(spawned, parsed); + const timeout = getForceKillAfterTimeout(options); + const t = setTimeout(() => { + kill('SIGKILL'); + }, timeout); - return spawned; -} + // Guarded because there's no `.unref()` when `execa` is used in the renderer + // process in Electron. This cannot be tested since we don't run tests in + // Electron. + // istanbul ignore else + if (t.unref) { + t.unref(); + } +}; -function spawnSync(command, args, options) { - // Parse the arguments - const parsed = parse(command, args, options); +const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => { + return isSigterm(signal) && forceKillAfterTimeout !== false && killResult; +}; - // Spawn the child process - const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); +const isSigterm = signal => { + return signal === os.constants.signals.SIGTERM || + (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM'); +}; - // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); +const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => { + if (forceKillAfterTimeout === true) { + return DEFAULT_FORCE_KILL_TIMEOUT; + } - return result; -} + if (!Number.isInteger(forceKillAfterTimeout) || forceKillAfterTimeout < 0) { + throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`); + } -module.exports = spawn; -module.exports.spawn = spawn; -module.exports.sync = spawnSync; + return forceKillAfterTimeout; +}; -module.exports._parse = parse; -module.exports._enoent = enoent; +// `childProcess.cancel()` +const spawnedCancel = (spawned, context) => { + const killResult = spawned.kill(); + if (killResult) { + context.isCanceled = true; + } +}; -/***/ }), -/* 374 */ -/***/ (function(module, exports, __webpack_require__) { +const timeoutKill = (spawned, signal, reject) => { + spawned.kill(signal); + reject(Object.assign(new Error('Timed out'), {timedOut: true, signal})); +}; -"use strict"; +// `timeout` option handling +const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => { + if (timeout === 0 || timeout === undefined) { + return spawnedPromise; + } + if (!Number.isInteger(timeout) || timeout < 0) { + throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`); + } -const path = __webpack_require__(16); -const resolveCommand = __webpack_require__(375); -const escape = __webpack_require__(381); -const readShebang = __webpack_require__(382); + let timeoutId; + const timeoutPromise = new Promise((resolve, reject) => { + timeoutId = setTimeout(() => { + timeoutKill(spawned, killSignal, reject); + }, timeout); + }); -const isWin = process.platform === 'win32'; -const isExecutableRegExp = /\.(?:com|exe)$/i; -const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; + const safeSpawnedPromise = spawnedPromise.finally(() => { + clearTimeout(timeoutId); + }); -function detectShebang(parsed) { - parsed.file = resolveCommand(parsed); + return Promise.race([timeoutPromise, safeSpawnedPromise]); +}; - const shebang = parsed.file && readShebang(parsed.file); +// `cleanup` option handling +const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => { + if (!cleanup || detached) { + return timedPromise; + } - if (shebang) { - parsed.args.unshift(parsed.file); - parsed.command = shebang; + const removeExitHandler = onExit(() => { + spawned.kill(); + }); - return resolveCommand(parsed); - } + return timedPromise.finally(() => { + removeExitHandler(); + }); +}; - return parsed.file; -} +module.exports = { + spawnedKill, + spawnedCancel, + setupTimeout, + setExitHandler +}; -function parseNonShell(parsed) { - if (!isWin) { - return parsed; - } - // Detect & add support for shebangs - const commandFile = detectShebang(parsed); +/***/ }), +/* 370 */ +/***/ (function(module, exports, __webpack_require__) { - // We don't need a shell if the command filename is an executable - const needsShell = !isExecutableRegExp.test(commandFile); +// Note: since nyc uses this module to output coverage, any lines +// that are in the direct sync flow of nyc's outputCoverage are +// ignored, since we can never get coverage for them. +var assert = __webpack_require__(371) +var signals = __webpack_require__(372) - // If a shell is required, use cmd.exe and take care of escaping everything correctly - // Note that `forceShell` is an hidden option used only in tests - if (parsed.options.forceShell || needsShell) { - // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` - // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument - // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, - // we need to double escape them - const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); +var EE = __webpack_require__(373) +/* istanbul ignore if */ +if (typeof EE !== 'function') { + EE = EE.EventEmitter +} - // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) - // This is necessary otherwise it will always fail with ENOENT in those cases - parsed.command = path.normalize(parsed.command); +var emitter +if (process.__signal_exit_emitter__) { + emitter = process.__signal_exit_emitter__ +} else { + emitter = process.__signal_exit_emitter__ = new EE() + emitter.count = 0 + emitter.emitted = {} +} - // Escape command & arguments - parsed.command = escape.command(parsed.command); - parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); +// Because this emitter is a global, we have to check to see if a +// previous version of this library failed to enable infinite listeners. +// I know what you're about to say. But literally everything about +// signal-exit is a compromise with evil. Get used to it. +if (!emitter.infinite) { + emitter.setMaxListeners(Infinity) + emitter.infinite = true +} - const shellCommand = [parsed.command].concat(parsed.args).join(' '); +module.exports = function (cb, opts) { + assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler') - parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; - parsed.command = process.env.comspec || 'cmd.exe'; - parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped - } + if (loaded === false) { + load() + } - return parsed; -} + var ev = 'exit' + if (opts && opts.alwaysLast) { + ev = 'afterexit' + } -function parse(command, args, options) { - // Normalize arguments, similar to nodejs - if (args && !Array.isArray(args)) { - options = args; - args = null; + var remove = function () { + emitter.removeListener(ev, cb) + if (emitter.listeners('exit').length === 0 && + emitter.listeners('afterexit').length === 0) { + unload() } + } + emitter.on(ev, cb) - args = args ? args.slice(0) : []; // Clone array to avoid changing the original - options = Object.assign({}, options); // Clone object to avoid changing the original - - // Build our parsed object - const parsed = { - command, - args, - options, - file: undefined, - original: { - command, - args, - }, - }; - - // Delegate further parsing to shell or non-shell - return options.shell ? parsed : parseNonShell(parsed); + return remove } -module.exports = parse; +module.exports.unload = unload +function unload () { + if (!loaded) { + return + } + loaded = false + signals.forEach(function (sig) { + try { + process.removeListener(sig, sigListeners[sig]) + } catch (er) {} + }) + process.emit = originalProcessEmit + process.reallyExit = originalProcessReallyExit + emitter.count -= 1 +} -/***/ }), -/* 375 */ -/***/ (function(module, exports, __webpack_require__) { +function emit (event, code, signal) { + if (emitter.emitted[event]) { + return + } + emitter.emitted[event] = true + emitter.emit(event, code, signal) +} -"use strict"; +// { : , ... } +var sigListeners = {} +signals.forEach(function (sig) { + sigListeners[sig] = function listener () { + // If there are no other listeners, an exit is coming! + // Simplest way: remove us and then re-send the signal. + // We know that this will kill the process, so we can + // safely emit now. + var listeners = process.listeners(sig) + if (listeners.length === emitter.count) { + unload() + emit('exit', null, sig) + /* istanbul ignore next */ + emit('afterexit', null, sig) + /* istanbul ignore next */ + process.kill(process.pid, sig) + } + } +}) +module.exports.signals = function () { + return signals +} -const path = __webpack_require__(16); -const which = __webpack_require__(376); -const pathKey = __webpack_require__(380)(); +module.exports.load = load -function resolveCommandAttempt(parsed, withoutPathExt) { - const cwd = process.cwd(); - const hasCustomCwd = parsed.options.cwd != null; - // Worker threads do not have process.chdir() - const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined; +var loaded = false - // If a custom `cwd` was specified, we need to change the process cwd - // because `which` will do stat calls but does not support a custom cwd - if (shouldSwitchCwd) { - try { - process.chdir(parsed.options.cwd); - } catch (err) { - /* Empty */ - } - } +function load () { + if (loaded) { + return + } + loaded = true - let resolved; + // This is the number of onSignalExit's that are in play. + // It's important so that we can count the correct number of + // listeners on signals, and don't wait for the other one to + // handle it instead of us. + emitter.count += 1 + signals = signals.filter(function (sig) { try { - resolved = which.sync(parsed.command, { - path: (parsed.options.env || process.env)[pathKey], - pathExt: withoutPathExt ? path.delimiter : undefined, - }); - } catch (e) { - /* Empty */ - } finally { - if (shouldSwitchCwd) { - process.chdir(cwd); - } + process.on(sig, sigListeners[sig]) + return true + } catch (er) { + return false } + }) - // If we successfully resolved, ensure that an absolute path is returned - // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it - if (resolved) { - resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); - } + process.emit = processEmit + process.reallyExit = processReallyExit +} - return resolved; +var originalProcessReallyExit = process.reallyExit +function processReallyExit (code) { + process.exitCode = code || 0 + emit('exit', process.exitCode, null) + /* istanbul ignore next */ + emit('afterexit', process.exitCode, null) + /* istanbul ignore next */ + originalProcessReallyExit.call(process, process.exitCode) } -function resolveCommand(parsed) { - return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); +var originalProcessEmit = process.emit +function processEmit (ev, arg) { + if (ev === 'exit') { + if (arg !== undefined) { + process.exitCode = arg + } + var ret = originalProcessEmit.apply(this, arguments) + emit('exit', process.exitCode, null) + /* istanbul ignore next */ + emit('afterexit', process.exitCode, null) + return ret + } else { + return originalProcessEmit.apply(this, arguments) + } } -module.exports = resolveCommand; +/***/ }), +/* 371 */ +/***/ (function(module, exports) { + +module.exports = require("assert"); /***/ }), -/* 376 */ -/***/ (function(module, exports, __webpack_require__) { +/* 372 */ +/***/ (function(module, exports) { -const isWindows = process.platform === 'win32' || - process.env.OSTYPE === 'cygwin' || - process.env.OSTYPE === 'msys' +// This is not the set of all possible signals. +// +// It IS, however, the set of all signals that trigger +// an exit on either Linux or BSD systems. Linux is a +// superset of the signal names supported on BSD, and +// the unknown signals just fail to register, so we can +// catch that easily enough. +// +// Don't bother with SIGKILL. It's uncatchable, which +// means that we can't fire any callbacks anyway. +// +// If a user does happen to register a handler on a non- +// fatal signal like SIGWINCH or something, and then +// exit, it'll end up firing `process.emit('exit')`, so +// the handler will be fired anyway. +// +// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised +// artificially, inherently leave the process in a +// state from which it is not safe to try and enter JS +// listeners. +module.exports = [ + 'SIGABRT', + 'SIGALRM', + 'SIGHUP', + 'SIGINT', + 'SIGTERM' +] -const path = __webpack_require__(16) -const COLON = isWindows ? ';' : ':' -const isexe = __webpack_require__(377) +if (process.platform !== 'win32') { + module.exports.push( + 'SIGVTALRM', + 'SIGXCPU', + 'SIGXFSZ', + 'SIGUSR2', + 'SIGTRAP', + 'SIGSYS', + 'SIGQUIT', + 'SIGIOT' + // should detect profiler and enable/disable accordingly. + // see #21 + // 'SIGPROF' + ) +} -const getNotFoundError = (cmd) => - Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }) +if (process.platform === 'linux') { + module.exports.push( + 'SIGIO', + 'SIGPOLL', + 'SIGPWR', + 'SIGSTKFLT', + 'SIGUNUSED' + ) +} -const getPathInfo = (cmd, opt) => { - const colon = opt.colon || COLON - // If it has a slash, then we don't bother searching the pathenv. - // just check the file itself, and that's it. - const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] - : ( - [ - // windows always checks the cwd first - ...(isWindows ? [process.cwd()] : []), - ...(opt.path || process.env.PATH || - /* istanbul ignore next: very unusual */ '').split(colon), - ] - ) - const pathExtExe = isWindows - ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' - : '' - const pathExt = isWindows ? pathExtExe.split(colon) : [''] +/***/ }), +/* 373 */ +/***/ (function(module, exports) { - if (isWindows) { - if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') - pathExt.unshift('') - } +module.exports = require("events"); - return { - pathEnv, - pathExt, - pathExtExe, - } -} +/***/ }), +/* 374 */ +/***/ (function(module, exports, __webpack_require__) { -const which = (cmd, opt, cb) => { - if (typeof opt === 'function') { - cb = opt - opt = {} - } - if (!opt) - opt = {} +"use strict"; - const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) - const found = [] +const isStream = __webpack_require__(375); +const getStream = __webpack_require__(376); +const mergeStream = __webpack_require__(383); - const step = i => new Promise((resolve, reject) => { - if (i === pathEnv.length) - return opt.all && found.length ? resolve(found) - : reject(getNotFoundError(cmd)) +// `input` option +const handleInput = (spawned, input) => { + // Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852 + // TODO: Remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0 + if (input === undefined || spawned.stdin === undefined) { + return; + } - const ppRaw = pathEnv[i] - const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw + if (isStream(input)) { + input.pipe(spawned.stdin); + } else { + spawned.stdin.end(input); + } +}; - const pCmd = path.join(pathPart, cmd) - const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd - : pCmd +// `all` interleaves `stdout` and `stderr` +const makeAllStream = (spawned, {all}) => { + if (!all || (!spawned.stdout && !spawned.stderr)) { + return; + } - resolve(subStep(p, i, 0)) - }) + const mixed = mergeStream(); - const subStep = (p, i, ii) => new Promise((resolve, reject) => { - if (ii === pathExt.length) - return resolve(step(i + 1)) - const ext = pathExt[ii] - isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { - if (!er && is) { - if (opt.all) - found.push(p + ext) - else - return resolve(p + ext) - } - return resolve(subStep(p, i, ii + 1)) - }) - }) + if (spawned.stdout) { + mixed.add(spawned.stdout); + } - return cb ? step(0).then(res => cb(null, res), cb) : step(0) -} + if (spawned.stderr) { + mixed.add(spawned.stderr); + } -const whichSync = (cmd, opt) => { - opt = opt || {} + return mixed; +}; - const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) - const found = [] +// On failure, `result.stdout|stderr|all` should contain the currently buffered stream +const getBufferedData = async (stream, streamPromise) => { + if (!stream) { + return; + } - for (let i = 0; i < pathEnv.length; i ++) { - const ppRaw = pathEnv[i] - const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw + stream.destroy(); - const pCmd = path.join(pathPart, cmd) - const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd - : pCmd + try { + return await streamPromise; + } catch (error) { + return error.bufferedData; + } +}; - for (let j = 0; j < pathExt.length; j ++) { - const cur = p + pathExt[j] - try { - const is = isexe.sync(cur, { pathExt: pathExtExe }) - if (is) { - if (opt.all) - found.push(cur) - else - return cur - } - } catch (ex) {} - } - } +const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => { + if (!stream || !buffer) { + return; + } - if (opt.all && found.length) - return found + if (encoding) { + return getStream(stream, {encoding, maxBuffer}); + } - if (opt.nothrow) - return null + return getStream.buffer(stream, {maxBuffer}); +}; - throw getNotFoundError(cmd) -} +// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all) +const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => { + const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer}); + const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer}); + const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2}); + + try { + return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]); + } catch (error) { + return Promise.all([ + {error, signal: error.signal, timedOut: error.timedOut}, + getBufferedData(stdout, stdoutPromise), + getBufferedData(stderr, stderrPromise), + getBufferedData(all, allPromise) + ]); + } +}; + +const validateInputSync = ({input}) => { + if (isStream(input)) { + throw new TypeError('The `input` option cannot be a stream in sync mode'); + } +}; + +module.exports = { + handleInput, + makeAllStream, + getSpawnedResult, + validateInputSync +}; -module.exports = which -which.sync = whichSync /***/ }), -/* 377 */ +/* 375 */ /***/ (function(module, exports, __webpack_require__) { -var fs = __webpack_require__(23) -var core -if (process.platform === 'win32' || global.TESTING_WINDOWS) { - core = __webpack_require__(378) -} else { - core = __webpack_require__(379) -} +"use strict"; -module.exports = isexe -isexe.sync = sync -function isexe (path, options, cb) { - if (typeof options === 'function') { - cb = options - options = {} - } +const isStream = stream => + stream !== null && + typeof stream === 'object' && + typeof stream.pipe === 'function'; - if (!cb) { - if (typeof Promise !== 'function') { - throw new TypeError('callback not provided') - } +isStream.writable = stream => + isStream(stream) && + stream.writable !== false && + typeof stream._write === 'function' && + typeof stream._writableState === 'object'; - return new Promise(function (resolve, reject) { - isexe(path, options || {}, function (er, is) { - if (er) { - reject(er) - } else { - resolve(is) - } - }) - }) - } +isStream.readable = stream => + isStream(stream) && + stream.readable !== false && + typeof stream._read === 'function' && + typeof stream._readableState === 'object'; - core(path, options || {}, function (er, is) { - // ignore EACCES because that just means we aren't allowed to run it - if (er) { - if (er.code === 'EACCES' || options && options.ignoreErrors) { - er = null - is = false - } - } - cb(er, is) - }) -} +isStream.duplex = stream => + isStream.writable(stream) && + isStream.readable(stream); -function sync (path, options) { - // my kingdom for a filtered catch - try { - return core.sync(path, options || {}) - } catch (er) { - if (options && options.ignoreErrors || er.code === 'EACCES') { - return false - } else { - throw er - } - } -} +isStream.transform = stream => + isStream.duplex(stream) && + typeof stream._transform === 'function' && + typeof stream._transformState === 'object'; + +module.exports = isStream; /***/ }), -/* 378 */ +/* 376 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = isexe -isexe.sync = sync +"use strict"; -var fs = __webpack_require__(23) +const pump = __webpack_require__(377); +const bufferStream = __webpack_require__(381); -function checkPathExt (path, options) { - var pathext = options.pathExt !== undefined ? - options.pathExt : process.env.PATHEXT +class MaxBufferError extends Error { + constructor() { + super('maxBuffer exceeded'); + this.name = 'MaxBufferError'; + } +} - if (!pathext) { - return true - } +async function getStream(inputStream, options) { + if (!inputStream) { + return Promise.reject(new Error('Expected a stream')); + } - pathext = pathext.split(';') - if (pathext.indexOf('') !== -1) { - return true - } - for (var i = 0; i < pathext.length; i++) { - var p = pathext[i].toLowerCase() - if (p && path.substr(-p.length).toLowerCase() === p) { - return true - } - } - return false -} + options = { + maxBuffer: Infinity, + ...options + }; -function checkStat (stat, path, options) { - if (!stat.isSymbolicLink() && !stat.isFile()) { - return false - } - return checkPathExt(path, options) -} + const {maxBuffer} = options; -function isexe (path, options, cb) { - fs.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, path, options)) - }) -} + let stream; + await new Promise((resolve, reject) => { + const rejectPromise = error => { + if (error) { // A null check + error.bufferedData = stream.getBufferedValue(); + } -function sync (path, options) { - return checkStat(fs.statSync(path), path, options) + reject(error); + }; + + stream = pump(inputStream, bufferStream(options), error => { + if (error) { + rejectPromise(error); + return; + } + + resolve(); + }); + + stream.on('data', () => { + if (stream.getBufferedLength() > maxBuffer) { + rejectPromise(new MaxBufferError()); + } + }); + }); + + return stream.getBufferedValue(); } +module.exports = getStream; +// TODO: Remove this for the next major release +module.exports.default = getStream; +module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); +module.exports.array = (stream, options) => getStream(stream, {...options, array: true}); +module.exports.MaxBufferError = MaxBufferError; + /***/ }), -/* 379 */ +/* 377 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = isexe -isexe.sync = sync +var once = __webpack_require__(378) +var eos = __webpack_require__(380) +var fs = __webpack_require__(349) // we only need fs to get the ReadStream and WriteStream prototypes -var fs = __webpack_require__(23) +var noop = function () {} +var ancient = /^v?\.0/.test(process.version) -function isexe (path, options, cb) { - fs.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, options)) - }) +var isFn = function (fn) { + return typeof fn === 'function' } -function sync (path, options) { - return checkStat(fs.statSync(path), options) +var isFS = function (stream) { + if (!ancient) return false // newer node version do not need to care about fs is a special way + if (!fs) return false // browser + return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) } -function checkStat (stat, options) { - return stat.isFile() && checkMode(stat, options) +var isRequest = function (stream) { + return stream.setHeader && isFn(stream.abort) } -function checkMode (stat, options) { - var mod = stat.mode - var uid = stat.uid - var gid = stat.gid +var destroyer = function (stream, reading, writing, callback) { + callback = once(callback) - var myUid = options.uid !== undefined ? - options.uid : process.getuid && process.getuid() - var myGid = options.gid !== undefined ? - options.gid : process.getgid && process.getgid() + var closed = false + stream.on('close', function () { + closed = true + }) - var u = parseInt('100', 8) - var g = parseInt('010', 8) - var o = parseInt('001', 8) - var ug = u | g + eos(stream, {readable: reading, writable: writing}, function (err) { + if (err) return callback(err) + closed = true + callback() + }) - var ret = (mod & o) || - (mod & g) && gid === myGid || - (mod & u) && uid === myUid || - (mod & ug) && myUid === 0 + var destroyed = false + return function (err) { + if (closed) return + if (destroyed) return + destroyed = true - return ret -} + if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks + if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want + if (isFn(stream.destroy)) return stream.destroy() -/***/ }), -/* 380 */ -/***/ (function(module, exports, __webpack_require__) { + callback(err || new Error('stream was destroyed')) + } +} -"use strict"; +var call = function (fn) { + fn() +} +var pipe = function (from, to) { + return from.pipe(to) +} -const pathKey = (options = {}) => { - const environment = options.env || process.env; - const platform = options.platform || process.platform; +var pump = function () { + var streams = Array.prototype.slice.call(arguments) + var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop - if (platform !== 'win32') { - return 'PATH'; - } + if (Array.isArray(streams[0])) streams = streams[0] + if (streams.length < 2) throw new Error('pump requires two streams per minimum') - return Object.keys(environment).find(key => key.toUpperCase() === 'PATH') || 'Path'; -}; + var error + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1 + var writing = i > 0 + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err + if (err) destroys.forEach(call) + if (reading) return + destroys.forEach(call) + callback(error) + }) + }) -module.exports = pathKey; -// TODO: Remove this for the next major release -module.exports.default = pathKey; + return streams.reduce(pipe) +} + +module.exports = pump /***/ }), -/* 381 */ +/* 378 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - +var wrappy = __webpack_require__(379) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) -// See http://www.robvanderwoude.com/escapechars.php -const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) -function escapeCommand(arg) { - // Escape meta chars - arg = arg.replace(metaCharsRegExp, '^$1'); + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) - return arg; +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f } -function escapeArgument(arg, doubleEscapeMetaChars) { - // Convert to string - arg = `${arg}`; +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} - // Algorithm below is based on https://qntm.org/cmd - // Sequence of backslashes followed by a double quote: - // double up all the backslashes and escape the double quote - arg = arg.replace(/(\\*)"/g, '$1$1\\"'); +/***/ }), +/* 379 */ +/***/ (function(module, exports) { - // Sequence of backslashes followed by the end of the string - // (which will become a double quote later): - // double up all the backslashes - arg = arg.replace(/(\\*)$/, '$1$1'); +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) - // All other backslashes occur literally + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') - // Quote the whole thing: - arg = `"${arg}"`; + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) - // Escape meta chars - arg = arg.replace(metaCharsRegExp, '^$1'); + return wrapper - // Double escape meta chars if necessary - if (doubleEscapeMetaChars) { - arg = arg.replace(metaCharsRegExp, '^$1'); + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] } - - return arg; + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) + } + return ret + } } -module.exports.command = escapeCommand; -module.exports.argument = escapeArgument; - /***/ }), -/* 382 */ +/* 380 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +var once = __webpack_require__(378); +var noop = function() {}; -const fs = __webpack_require__(23); -const shebangCommand = __webpack_require__(383); +var isRequest = function(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +}; -function readShebang(command) { - // Read the first 150 bytes from the file - const size = 150; - const buffer = Buffer.alloc(size); +var isChildProcess = function(stream) { + return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 +}; - let fd; +var eos = function(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; - try { - fd = fs.openSync(command, 'r'); - fs.readSync(fd, buffer, 0, size, 0); - fs.closeSync(fd); - } catch (e) { /* Empty */ } + callback = once(callback || noop); - // Attempt to extract shebang (null is returned if not a shebang) - return shebangCommand(buffer.toString()); -} + var ws = stream._writableState; + var rs = stream._readableState; + var readable = opts.readable || (opts.readable !== false && stream.readable); + var writable = opts.writable || (opts.writable !== false && stream.writable); -module.exports = readShebang; + var onlegacyfinish = function() { + if (!stream.writable) onfinish(); + }; + var onfinish = function() { + writable = false; + if (!readable) callback.call(stream); + }; -/***/ }), -/* 383 */ -/***/ (function(module, exports, __webpack_require__) { + var onend = function() { + readable = false; + if (!writable) callback.call(stream); + }; -"use strict"; + var onexit = function(exitCode) { + callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); + }; -const shebangRegex = __webpack_require__(384); + var onerror = function(err) { + callback.call(stream, err); + }; -module.exports = (string = '') => { - const match = string.match(shebangRegex); + var onclose = function() { + if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close')); + if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close')); + }; - if (!match) { - return null; + var onrequest = function() { + stream.req.on('finish', onfinish); + }; + + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest(); + else stream.on('request', onrequest); + } else if (writable && !ws) { // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); } - const [path, argument] = match[0].replace(/#! ?/, '').split(' '); - const binary = path.split('/').pop(); + if (isChildProcess(stream)) stream.on('exit', onexit); - if (binary === 'env') { - return argument; - } + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); - return argument ? `${binary} ${argument}` : binary; + return function() { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('exit', onexit); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; }; +module.exports = eos; + /***/ }), -/* 384 */ +/* 381 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = /^#!(.*)/; +const {PassThrough: PassThroughStream} = __webpack_require__(382); +module.exports = options => { + options = {...options}; -/***/ }), -/* 385 */ -/***/ (function(module, exports, __webpack_require__) { + const {array} = options; + let {encoding} = options; + const isBuffer = encoding === 'buffer'; + let objectMode = false; -"use strict"; + if (array) { + objectMode = !(encoding || isBuffer); + } else { + encoding = encoding || 'utf8'; + } + if (isBuffer) { + encoding = null; + } -const isWin = process.platform === 'win32'; + const stream = new PassThroughStream({objectMode}); -function notFoundError(original, syscall) { - return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { - code: 'ENOENT', - errno: 'ENOENT', - syscall: `${syscall} ${original.command}`, - path: original.command, - spawnargs: original.args, - }); -} + if (encoding) { + stream.setEncoding(encoding); + } -function hookChildProcess(cp, parsed) { - if (!isWin) { - return; - } + let length = 0; + const chunks = []; - const originalEmit = cp.emit; + stream.on('data', chunk => { + chunks.push(chunk); - cp.emit = function (name, arg1) { - // If emitting "exit" event and exit code is 1, we need to check if - // the command exists and emit an "error" instead - // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 - if (name === 'exit') { - const err = verifyENOENT(arg1, parsed, 'spawn'); + if (objectMode) { + length = chunks.length; + } else { + length += chunk.length; + } + }); - if (err) { - return originalEmit.call(cp, 'error', err); - } - } + stream.getBufferedValue = () => { + if (array) { + return chunks; + } - return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params - }; -} + return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); + }; -function verifyENOENT(status, parsed) { - if (isWin && status === 1 && !parsed.file) { - return notFoundError(parsed.original, 'spawn'); - } + stream.getBufferedLength = () => length; - return null; -} + return stream; +}; -function verifyENOENTSync(status, parsed) { - if (isWin && status === 1 && !parsed.file) { - return notFoundError(parsed.original, 'spawnSync'); - } - return null; -} - -module.exports = { - hookChildProcess, - verifyENOENT, - verifyENOENTSync, - notFoundError, -}; +/***/ }), +/* 382 */ +/***/ (function(module, exports) { +module.exports = require("stream"); /***/ }), -/* 386 */ +/* 383 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = input => { - const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt(); - const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt(); +const { PassThrough } = __webpack_require__(382); - if (input[input.length - 1] === LF) { - input = input.slice(0, input.length - 1); - } +module.exports = function (/*streams...*/) { + var sources = [] + var output = new PassThrough({objectMode: true}) - if (input[input.length - 1] === CR) { - input = input.slice(0, input.length - 1); - } + output.setMaxListeners(0) - return input; -}; + output.add = add + output.isEmpty = isEmpty + + output.on('unpipe', remove) + + Array.prototype.slice.call(arguments).forEach(add) + + return output + + function add (source) { + if (Array.isArray(source)) { + source.forEach(add) + return this + } + + sources.push(source); + source.once('end', remove.bind(null, source)) + source.once('error', output.emit.bind(output, 'error')) + source.pipe(output, {end: false}) + return this + } + + function isEmpty () { + return sources.length == 0; + } + + function remove (source) { + sources = sources.filter(function (it) { return it !== source }) + if (!sources.length && output.readable) { output.end() } + } +} /***/ }), -/* 387 */ +/* 384 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const path = __webpack_require__(16); -const pathKey = __webpack_require__(380); -const npmRunPath = options => { - options = { - cwd: process.cwd(), - path: process.env[pathKey()], - execPath: process.execPath, - ...options - }; +const nativePromisePrototype = (async () => {})().constructor.prototype; +const descriptors = ['then', 'catch', 'finally'].map(property => [ + property, + Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property) +]); - let previous; - let cwdPath = path.resolve(options.cwd); - const result = []; +// The return value is a mixin of `childProcess` and `Promise` +const mergePromise = (spawned, promise) => { + for (const [property, descriptor] of descriptors) { + // Starting the main `promise` is deferred to avoid consuming streams + const value = typeof promise === 'function' ? + (...args) => Reflect.apply(descriptor.value, promise(), args) : + descriptor.value.bind(promise); - while (previous !== cwdPath) { - result.push(path.join(cwdPath, 'node_modules/.bin')); - previous = cwdPath; - cwdPath = path.resolve(cwdPath, '..'); + Reflect.defineProperty(spawned, property, {...descriptor, value}); } - // Ensure the running `node` binary is used - const execPathDir = path.resolve(options.cwd, options.execPath, '..'); - result.push(execPathDir); - - return result.concat(options.path).join(path.delimiter); + return spawned; }; -module.exports = npmRunPath; -// TODO: Remove this for the next major release -module.exports.default = npmRunPath; - -module.exports.env = options => { - options = { - env: process.env, - ...options - }; +// Use promises instead of `child_process` events +const getSpawnedPromise = spawned => { + return new Promise((resolve, reject) => { + spawned.on('exit', (exitCode, signal) => { + resolve({exitCode, signal}); + }); - const env = {...options.env}; - const path = pathKey({env}); + spawned.on('error', error => { + reject(error); + }); - options.path = env[path]; - env[path] = module.exports(options); + if (spawned.stdin) { + spawned.stdin.on('error', error => { + reject(error); + }); + } + }); +}; - return env; +module.exports = { + mergePromise, + getSpawnedPromise }; + /***/ }), -/* 388 */ +/* 385 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const mimicFn = __webpack_require__(389); - -const calledFunctions = new WeakMap(); +const SPACES_REGEXP = / +/g; -const oneTime = (fn, options = {}) => { - if (typeof fn !== 'function') { - throw new TypeError('Expected a function'); +const joinCommand = (file, args = []) => { + if (!Array.isArray(args)) { + return file; } - let ret; - let isCalled = false; - let callCount = 0; - const functionName = fn.displayName || fn.name || ''; - - const onetime = function (...args) { - calledFunctions.set(onetime, ++callCount); - - if (isCalled) { - if (options.throw === true) { - throw new Error(`Function \`${functionName}\` can only be called once`); - } - - return ret; - } + return [file, ...args].join(' '); +}; - isCalled = true; - ret = fn.apply(this, args); - fn = null; +// Allow spaces to be escaped by a backslash if not meant as a delimiter +const handleEscaping = (tokens, token, index) => { + if (index === 0) { + return [token]; + } - return ret; - }; + const previousToken = tokens[tokens.length - 1]; - mimicFn(onetime, fn); - calledFunctions.set(onetime, callCount); + if (previousToken.endsWith('\\')) { + return [...tokens.slice(0, -1), `${previousToken.slice(0, -1)} ${token}`]; + } - return onetime; + return [...tokens, token]; }; -module.exports = oneTime; -// TODO: Remove this for the next major release -module.exports.default = oneTime; - -module.exports.callCount = fn => { - if (!calledFunctions.has(fn)) { - throw new Error(`The given function \`${fn.name}\` is not wrapped by the \`onetime\` package`); - } +// Handle `execa.command()` +const parseCommand = command => { + return command + .trim() + .split(SPACES_REGEXP) + .reduce(handleEscaping, []); +}; - return calledFunctions.get(fn); +module.exports = { + joinCommand, + parseCommand }; /***/ }), -/* 389 */ +/* 386 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +const escapeStringRegexp = __webpack_require__(387); +const ansiStyles = __webpack_require__(388); +const stdoutColor = __webpack_require__(393).stdout; -const mimicFn = (to, from) => { - for (const prop of Reflect.ownKeys(from)) { - Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); - } +const template = __webpack_require__(395); - return to; -}; +const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); -module.exports = mimicFn; -// TODO: Remove this for the next major release -module.exports.default = mimicFn; +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; +// `color-convert` models to exclude from the Chalk API due to conflicts and such +const skipModels = new Set(['gray']); -/***/ }), -/* 390 */ -/***/ (function(module, exports, __webpack_require__) { +const styles = Object.create(null); -"use strict"; +function applyOptions(obj, options) { + options = options || {}; -const {signalsByName} = __webpack_require__(391); + // Detect level if not set manually + const scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; +} -const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => { - if (timedOut) { - return `timed out after ${timeout} milliseconds`; - } +function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + const chalk = {}; + applyOptions(chalk, options); - if (isCanceled) { - return 'was canceled'; - } + chalk.template = function () { + const args = [].slice.call(arguments); + return chalkTag.apply(null, [chalk.template].concat(args)); + }; - if (errorCode !== undefined) { - return `failed with ${errorCode}`; - } + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); - if (signal !== undefined) { - return `was killed with ${signal} (${signalDescription})`; - } + chalk.template.constructor = Chalk; - if (exitCode !== undefined) { - return `failed with exit code ${exitCode}`; + return chalk.template; } - return 'failed'; -}; + applyOptions(this, options); +} -const makeError = ({ - stdout, - stderr, - all, - error, - signal, - exitCode, - command, - timedOut, - isCanceled, - killed, - parsed: {options: {timeout}} -}) => { - // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`. - // We normalize them to `undefined` - exitCode = exitCode === null ? undefined : exitCode; - signal = signal === null ? undefined : signal; - const signalDescription = signal === undefined ? undefined : signalsByName[signal].description; +// Use bright blue on Windows as the normal blue color is illegible +if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001B[94m'; +} - const errorCode = error && error.code; +for (const key of Object.keys(ansiStyles)) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); - const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}); - const execaMessage = `Command ${prefix}: ${command}`; - const isError = Object.prototype.toString.call(error) === '[object Error]'; - const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage; - const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n'); + styles[key] = { + get() { + const codes = ansiStyles[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + }; +} - if (isError) { - error.originalMessage = error.message; - error.message = message; - } else { - error = new Error(message); +styles.visible = { + get() { + return build.call(this, this._styles || [], true, 'visible'); } +}; - error.shortMessage = shortMessage; - error.command = command; - error.exitCode = exitCode; - error.signal = signal; - error.signalDescription = signalDescription; - error.stdout = stdout; - error.stderr = stderr; - - if (all !== undefined) { - error.all = all; +ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); +for (const model of Object.keys(ansiStyles.color.ansi)) { + if (skipModels.has(model)) { + continue; } - if ('bufferedData' in error) { - delete error.bufferedData; - } + styles[model] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.color.close, + closeRe: ansiStyles.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} - error.failed = true; - error.timedOut = Boolean(timedOut); - error.isCanceled = isCanceled; - error.killed = killed && !timedOut; +ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); +for (const model of Object.keys(ansiStyles.bgColor.ansi)) { + if (skipModels.has(model)) { + continue; + } - return error; -}; + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.bgColor.close, + closeRe: ansiStyles.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} -module.exports = makeError; +const proto = Object.defineProperties(() => {}, styles); +function build(_styles, _empty, key) { + const builder = function () { + return applyStyle.apply(builder, arguments); + }; -/***/ }), -/* 391 */ -/***/ (function(module, exports, __webpack_require__) { + builder._styles = _styles; + builder._empty = _empty; -"use strict"; -Object.defineProperty(exports,"__esModule",{value:true});exports.signalsByNumber=exports.signalsByName=void 0;var _os=__webpack_require__(11); + const self = this; -var _signals=__webpack_require__(392); -var _realtime=__webpack_require__(394); + Object.defineProperty(builder, 'level', { + enumerable: true, + get() { + return self.level; + }, + set(level) { + self.level = level; + } + }); + Object.defineProperty(builder, 'enabled', { + enumerable: true, + get() { + return self.enabled; + }, + set(enabled) { + self.enabled = enabled; + } + }); + // See below for fix regarding invisible grey/dim combination on Windows + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; -const getSignalsByName=function(){ -const signals=(0,_signals.getSignals)(); -return signals.reduce(getSignalByName,{}); -}; + // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + builder.__proto__ = proto; // eslint-disable-line no-proto -const getSignalByName=function( -signalByNameMemo, -{name,number,description,supported,action,forced,standard}) -{ -return{ -...signalByNameMemo, -[name]:{name,number,description,supported,action,forced,standard}}; + return builder; +} -}; +function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + const args = arguments; + const argsLen = args.length; + let str = String(arguments[0]); -const signalsByName=getSignalsByName();exports.signalsByName=signalsByName; + if (argsLen === 0) { + return ''; + } + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (let a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } + // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + const originalDim = ansiStyles.dim.open; + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles.dim.open = ''; + } -const getSignalsByNumber=function(){ -const signals=(0,_signals.getSignals)(); -const length=_realtime.SIGRTMAX+1; -const signalsA=Array.from({length},(value,number)=> -getSignalByNumber(number,signals)); + for (const code of this._styles.slice().reverse()) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; -return Object.assign({},...signalsA); -}; + // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); + } -const getSignalByNumber=function(number,signals){ -const signal=findSignalByNumber(number,signals); + // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + ansiStyles.dim.open = originalDim; -if(signal===undefined){ -return{}; + return str; } -const{name,description,supported,action,forced,standard}=signal; -return{ -[number]:{ -name, -number, -description, -supported, -action, -forced, -standard}}; - - -}; - +function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + const args = [].slice.call(arguments, 2); + const parts = [strings.raw[0]]; -const findSignalByNumber=function(number,signals){ -const signal=signals.find(({name})=>_os.constants.signals[name]===number); + for (let i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } -if(signal!==undefined){ -return signal; + return template(chalk, parts.join('')); } -return signals.find(signalA=>signalA.number===number); -}; +Object.defineProperties(Chalk.prototype, styles); + +module.exports = Chalk(); // eslint-disable-line new-cap +module.exports.supportsColor = stdoutColor; +module.exports.default = module.exports; // For TypeScript -const signalsByNumber=getSignalsByNumber();exports.signalsByNumber=signalsByNumber; -//# sourceMappingURL=main.js.map /***/ }), -/* 392 */ +/* 387 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports,"__esModule",{value:true});exports.getSignals=void 0;var _os=__webpack_require__(11); -var _core=__webpack_require__(393); -var _realtime=__webpack_require__(394); +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; +module.exports = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } -const getSignals=function(){ -const realtimeSignals=(0,_realtime.getRealtimeSignals)(); -const signals=[..._core.SIGNALS,...realtimeSignals].map(normalizeSignal); -return signals; -};exports.getSignals=getSignals; + return str.replace(matchOperatorsRe, '\\$&'); +}; - - - - - -const normalizeSignal=function({ -name, -number:defaultNumber, -description, -action, -forced=false, -standard}) -{ -const{ -signals:{[name]:constantSignal}}= -_os.constants; -const supported=constantSignal!==undefined; -const number=supported?constantSignal:defaultNumber; -return{name,number,description,supported,action,forced,standard}; -}; -//# sourceMappingURL=signals.js.map - /***/ }), -/* 393 */ +/* 388 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports,"__esModule",{value:true});exports.SIGNALS=void 0; +/* WEBPACK VAR INJECTION */(function(module) { +const colorConvert = __webpack_require__(389); -const SIGNALS=[ -{ -name:"SIGHUP", -number:1, -action:"terminate", -description:"Terminal closed", -standard:"posix"}, +const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${code + offset}m`; +}; -{ -name:"SIGINT", -number:2, -action:"terminate", -description:"User interruption with CTRL-C", -standard:"ansi"}, +const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};5;${code}m`; +}; -{ -name:"SIGQUIT", -number:3, -action:"core", -description:"User interruption with CTRL-\\", -standard:"posix"}, +const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; -{ -name:"SIGILL", -number:4, -action:"core", -description:"Invalid machine instruction", -standard:"ansi"}, +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], -{ -name:"SIGTRAP", -number:5, -action:"core", -description:"Debugger breakpoint", -standard:"posix"}, + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], -{ -name:"SIGABRT", -number:6, -action:"core", -description:"Aborted", -standard:"ansi"}, + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; -{ -name:"SIGIOT", -number:6, -action:"core", -description:"Aborted", -standard:"bsd"}, + // Fix humans + styles.color.grey = styles.color.gray; -{ -name:"SIGBUS", -number:7, -action:"core", -description: -"Bus error due to misaligned, non-existing address or paging error", -standard:"bsd"}, + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; -{ -name:"SIGEMT", -number:7, -action:"terminate", -description:"Command should be emulated but is not implemented", -standard:"other"}, + for (const styleName of Object.keys(group)) { + const style = group[styleName]; -{ -name:"SIGFPE", -number:8, -action:"core", -description:"Floating point arithmetic error", -standard:"ansi"}, + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; -{ -name:"SIGKILL", -number:9, -action:"terminate", -description:"Forced termination", -standard:"posix", -forced:true}, + group[styleName] = styles[styleName]; -{ -name:"SIGUSR1", -number:10, -action:"terminate", -description:"Application-specific signal", -standard:"posix"}, + codes.set(style[0], style[1]); + } -{ -name:"SIGSEGV", -number:11, -action:"core", -description:"Segmentation fault", -standard:"ansi"}, + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); -{ -name:"SIGUSR2", -number:12, -action:"terminate", -description:"Application-specific signal", -standard:"posix"}, + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } -{ -name:"SIGPIPE", -number:13, -action:"terminate", -description:"Broken pipe or socket", -standard:"posix"}, + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; -{ -name:"SIGALRM", -number:14, -action:"terminate", -description:"Timeout or timer", -standard:"posix"}, + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; -{ -name:"SIGTERM", -number:15, -action:"terminate", -description:"Termination", -standard:"ansi"}, + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; -{ -name:"SIGSTKFLT", -number:16, -action:"terminate", -description:"Stack is empty or overflowed", -standard:"other"}, + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; -{ -name:"SIGCHLD", -number:17, -action:"ignore", -description:"Child process terminated, paused or unpaused", -standard:"posix"}, + for (let key of Object.keys(colorConvert)) { + if (typeof colorConvert[key] !== 'object') { + continue; + } -{ -name:"SIGCLD", -number:17, -action:"ignore", -description:"Child process terminated, paused or unpaused", -standard:"other"}, + const suite = colorConvert[key]; -{ -name:"SIGCONT", -number:18, -action:"unpause", -description:"Unpaused", -standard:"posix", -forced:true}, + if (key === 'ansi16') { + key = 'ansi'; + } -{ -name:"SIGSTOP", -number:19, -action:"pause", -description:"Paused", -standard:"posix", -forced:true}, + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } -{ -name:"SIGTSTP", -number:20, -action:"pause", -description:"Paused using CTRL-Z or \"suspend\"", -standard:"posix"}, + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } -{ -name:"SIGTTIN", -number:21, -action:"pause", -description:"Background process cannot read terminal input", -standard:"posix"}, + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } -{ -name:"SIGBREAK", -number:21, -action:"terminate", -description:"User interruption with CTRL-BREAK", -standard:"other"}, + return styles; +} -{ -name:"SIGTTOU", -number:22, -action:"pause", -description:"Background process cannot write to terminal output", -standard:"posix"}, +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); -{ -name:"SIGURG", -number:23, -action:"ignore", -description:"Socket received out-of-band data", -standard:"bsd"}, +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(11)(module))) -{ -name:"SIGXCPU", -number:24, -action:"core", -description:"Process timed out", -standard:"bsd"}, +/***/ }), +/* 389 */ +/***/ (function(module, exports, __webpack_require__) { -{ -name:"SIGXFSZ", -number:25, -action:"core", -description:"File too big", -standard:"bsd"}, +var conversions = __webpack_require__(390); +var route = __webpack_require__(392); -{ -name:"SIGVTALRM", -number:26, -action:"terminate", -description:"Timeout or timer", -standard:"bsd"}, +var convert = {}; -{ -name:"SIGPROF", -number:27, -action:"terminate", -description:"Timeout or timer", -standard:"bsd"}, +var models = Object.keys(conversions); -{ -name:"SIGWINCH", -number:28, -action:"ignore", -description:"Terminal window size changed", -standard:"bsd"}, +function wrapRaw(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } -{ -name:"SIGIO", -number:29, -action:"terminate", -description:"I/O is available", -standard:"other"}, + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } -{ -name:"SIGPOLL", -number:29, -action:"terminate", -description:"Watched event", -standard:"other"}, + return fn(args); + }; -{ -name:"SIGINFO", -number:29, -action:"ignore", -description:"Request for process information", -standard:"other"}, + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } -{ -name:"SIGPWR", -number:30, -action:"terminate", -description:"Device running out of power", -standard:"systemv"}, + return wrappedFn; +} -{ -name:"SIGSYS", -number:31, -action:"core", -description:"Invalid system call", -standard:"other"}, +function wrapRounded(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } -{ -name:"SIGUNUSED", -number:31, -action:"terminate", -description:"Invalid system call", -standard:"other"}];exports.SIGNALS=SIGNALS; -//# sourceMappingURL=core.js.map + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } -/***/ }), -/* 394 */ -/***/ (function(module, exports, __webpack_require__) { + var result = fn(args); -"use strict"; -Object.defineProperty(exports,"__esModule",{value:true});exports.SIGRTMAX=exports.getRealtimeSignals=void 0; -const getRealtimeSignals=function(){ -const length=SIGRTMAX-SIGRTMIN+1; -return Array.from({length},getRealtimeSignal); -};exports.getRealtimeSignals=getRealtimeSignals; + // we're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } -const getRealtimeSignal=function(value,index){ -return{ -name:`SIGRT${index+1}`, -number:SIGRTMIN+index, -action:"terminate", -description:"Application-specific signal (realtime)", -standard:"posix"}; + return result; + }; -}; + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } -const SIGRTMIN=34; -const SIGRTMAX=64;exports.SIGRTMAX=SIGRTMAX; -//# sourceMappingURL=realtime.js.map + return wrappedFn; +} -/***/ }), -/* 395 */ -/***/ (function(module, exports, __webpack_require__) { +models.forEach(function (fromModel) { + convert[fromModel] = {}; -"use strict"; + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); -const aliases = ['stdin', 'stdout', 'stderr']; + var routes = route(fromModel); + var routeModels = Object.keys(routes); -const hasAlias = opts => aliases.some(alias => opts[alias] !== undefined); + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; -const normalizeStdio = opts => { - if (!opts) { - return; - } + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); +}); - const {stdio} = opts; +module.exports = convert; - if (stdio === undefined) { - return aliases.map(alias => opts[alias]); - } - if (hasAlias(opts)) { - throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`); - } +/***/ }), +/* 390 */ +/***/ (function(module, exports, __webpack_require__) { - if (typeof stdio === 'string') { - return stdio; - } +/* MIT license */ +var cssKeywords = __webpack_require__(391); - if (!Array.isArray(stdio)) { - throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); +// NOTE: conversions should only return primitive values (i.e. arrays, or +// values that give correct `typeof` results). +// do not use box values types (i.e. Number(), String(), etc.) + +var reverseKeywords = {}; +for (var key in cssKeywords) { + if (cssKeywords.hasOwnProperty(key)) { + reverseKeywords[cssKeywords[key]] = key; } +} - const length = Math.max(stdio.length, aliases.length); - return Array.from({length}, (value, index) => stdio[index]); +var convert = module.exports = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} }; -module.exports = normalizeStdio; +// hide .channels and .labels properties +for (var model in convert) { + if (convert.hasOwnProperty(model)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } -// `ipc` is pushed unless it is already present -module.exports.node = opts => { - const stdio = normalizeStdio(opts); + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } - if (stdio === 'ipc') { - return 'ipc'; - } + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } - if (stdio === undefined || typeof stdio === 'string') { - return [stdio, stdio, stdio, 'ipc']; + var channels = convert[model].channels; + var labels = convert[model].labels; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); } +} - if (stdio.includes('ipc')) { - return stdio; +convert.rgb.hsl = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; } - return [...stdio, 'ipc']; -}; + h = Math.min(h * 60, 360); + if (h < 0) { + h += 360; + } -/***/ }), -/* 396 */ -/***/ (function(module, exports, __webpack_require__) { + l = (min + max) / 2; -"use strict"; + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } -const os = __webpack_require__(11); -const onExit = __webpack_require__(397); + return [h, s * 100, l * 100]; +}; -const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5; +convert.rgb.hsv = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var v; -// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior -const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => { - const killResult = kill(signal); - setKillTimeout(kill, signal, options, killResult); - return killResult; -}; + if (max === 0) { + s = 0; + } else { + s = (delta / max * 1000) / 10; + } -const setKillTimeout = (kill, signal, options, killResult) => { - if (!shouldForceKill(signal, options, killResult)) { - return; + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; } - const timeout = getForceKillAfterTimeout(options); - const t = setTimeout(() => { - kill('SIGKILL'); - }, timeout); + h = Math.min(h * 60, 360); - // Guarded because there's no `.unref()` when `execa` is used in the renderer - // process in Electron. This cannot be tested since we don't run tests in - // Electron. - // istanbul ignore else - if (t.unref) { - t.unref(); + if (h < 0) { + h += 360; } -}; -const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => { - return isSigterm(signal) && forceKillAfterTimeout !== false && killResult; -}; + v = ((max / 255) * 1000) / 10; -const isSigterm = signal => { - return signal === os.constants.signals.SIGTERM || - (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM'); + return [h, s, v]; }; -const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => { - if (forceKillAfterTimeout === true) { - return DEFAULT_FORCE_KILL_TIMEOUT; - } +convert.rgb.hwb = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var w = 1 / 255 * Math.min(r, Math.min(g, b)); - if (!Number.isInteger(forceKillAfterTimeout) || forceKillAfterTimeout < 0) { - throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`); - } + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); - return forceKillAfterTimeout; + return [h, w * 100, b * 100]; }; -// `childProcess.cancel()` -const spawnedCancel = (spawned, context) => { - const killResult = spawned.kill(); +convert.rgb.cmyk = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; - if (killResult) { - context.isCanceled = true; - } -}; + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; -const timeoutKill = (spawned, signal, reject) => { - spawned.kill(signal); - reject(Object.assign(new Error('Timed out'), {timedOut: true, signal})); + return [c * 100, m * 100, y * 100, k * 100]; }; -// `timeout` option handling -const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => { - if (timeout === 0 || timeout === undefined) { - return spawnedPromise; - } +/** + * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + * */ +function comparativeDistance(x, y) { + return ( + Math.pow(x[0] - y[0], 2) + + Math.pow(x[1] - y[1], 2) + + Math.pow(x[2] - y[2], 2) + ); +} - if (!Number.isInteger(timeout) || timeout < 0) { - throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`); +convert.rgb.keyword = function (rgb) { + var reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; } - let timeoutId; - const timeoutPromise = new Promise((resolve, reject) => { - timeoutId = setTimeout(() => { - timeoutKill(spawned, killSignal, reject); - }, timeout); - }); + var currentClosestDistance = Infinity; + var currentClosestKeyword; - const safeSpawnedPromise = spawnedPromise.finally(() => { - clearTimeout(timeoutId); - }); + for (var keyword in cssKeywords) { + if (cssKeywords.hasOwnProperty(keyword)) { + var value = cssKeywords[keyword]; - return Promise.race([timeoutPromise, safeSpawnedPromise]); -}; + // Compute comparative distance + var distance = comparativeDistance(rgb, value); -// `cleanup` option handling -const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => { - if (!cleanup || detached) { - return timedPromise; + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } } - const removeExitHandler = onExit(() => { - spawned.kill(); - }); - - return timedPromise.finally(() => { - removeExitHandler(); - }); + return currentClosestKeyword; }; -module.exports = { - spawnedKill, - spawnedCancel, - setupTimeout, - setExitHandler +convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; }; +convert.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; -/***/ }), -/* 397 */ -/***/ (function(module, exports, __webpack_require__) { + // assume sRGB + r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); + g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); + b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); -// Note: since nyc uses this module to output coverage, any lines -// that are in the direct sync flow of nyc's outputCoverage are -// ignored, since we can never get coverage for them. -var assert = __webpack_require__(30) -var signals = __webpack_require__(398) + var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); -var EE = __webpack_require__(399) -/* istanbul ignore if */ -if (typeof EE !== 'function') { - EE = EE.EventEmitter -} + return [x * 100, y * 100, z * 100]; +}; -var emitter -if (process.__signal_exit_emitter__) { - emitter = process.__signal_exit_emitter__ -} else { - emitter = process.__signal_exit_emitter__ = new EE() - emitter.count = 0 - emitter.emitted = {} -} +convert.rgb.lab = function (rgb) { + var xyz = convert.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; -// Because this emitter is a global, we have to check to see if a -// previous version of this library failed to enable infinite listeners. -// I know what you're about to say. But literally everything about -// signal-exit is a compromise with evil. Get used to it. -if (!emitter.infinite) { - emitter.setMaxListeners(Infinity) - emitter.infinite = true -} + x /= 95.047; + y /= 100; + z /= 108.883; -module.exports = function (cb, opts) { - assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler') + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); - if (loaded === false) { - load() - } + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); - var ev = 'exit' - if (opts && opts.alwaysLast) { - ev = 'afterexit' - } + return [l, a, b]; +}; - var remove = function () { - emitter.removeListener(ev, cb) - if (emitter.listeners('exit').length === 0 && - emitter.listeners('afterexit').length === 0) { - unload() - } - } - emitter.on(ev, cb) +convert.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; - return remove -} + if (s === 0) { + val = l * 255; + return [val, val, val]; + } -module.exports.unload = unload -function unload () { - if (!loaded) { - return - } - loaded = false + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } - signals.forEach(function (sig) { - try { - process.removeListener(sig, sigListeners[sig]) - } catch (er) {} - }) - process.emit = originalProcessEmit - process.reallyExit = originalProcessReallyExit - emitter.count -= 1 -} + t1 = 2 * l - t2; -function emit (event, code, signal) { - if (emitter.emitted[event]) { - return - } - emitter.emitted[event] = true - emitter.emit(event, code, signal) -} + rgb = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + if (t3 > 1) { + t3--; + } -// { : , ... } -var sigListeners = {} -signals.forEach(function (sig) { - sigListeners[sig] = function listener () { - // If there are no other listeners, an exit is coming! - // Simplest way: remove us and then re-send the signal. - // We know that this will kill the process, so we can - // safely emit now. - var listeners = process.listeners(sig) - if (listeners.length === emitter.count) { - unload() - emit('exit', null, sig) - /* istanbul ignore next */ - emit('afterexit', null, sig) - /* istanbul ignore next */ - process.kill(process.pid, sig) - } - } -}) + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } -module.exports.signals = function () { - return signals -} + rgb[i] = val * 255; + } -module.exports.load = load + return rgb; +}; -var loaded = false +convert.hsl.hsv = function (hsl) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; -function load () { - if (loaded) { - return - } - loaded = true + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); - // This is the number of onSignalExit's that are in play. - // It's important so that we can count the correct number of - // listeners on signals, and don't wait for the other one to - // handle it instead of us. - emitter.count += 1 + return [h, sv * 100, v * 100]; +}; - signals = signals.filter(function (sig) { - try { - process.on(sig, sigListeners[sig]) - return true - } catch (er) { - return false - } - }) +convert.hsv.rgb = function (hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi = Math.floor(h) % 6; - process.emit = processEmit - process.reallyExit = processReallyExit -} + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q = 255 * v * (1 - (s * f)); + var t = 255 * v * (1 - (s * (1 - f))); + v *= 255; -var originalProcessReallyExit = process.reallyExit -function processReallyExit (code) { - process.exitCode = code || 0 - emit('exit', process.exitCode, null) - /* istanbul ignore next */ - emit('afterexit', process.exitCode, null) - /* istanbul ignore next */ - originalProcessReallyExit.call(process, process.exitCode) -} + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } +}; -var originalProcessEmit = process.emit -function processEmit (ev, arg) { - if (ev === 'exit') { - if (arg !== undefined) { - process.exitCode = arg - } - var ret = originalProcessEmit.apply(this, arguments) - emit('exit', process.exitCode, null) - /* istanbul ignore next */ - emit('afterexit', process.exitCode, null) - return ret - } else { - return originalProcessEmit.apply(this, arguments) - } -} +convert.hsv.hsl = function (hsv) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl; + var l; + l = (2 - s) * v; + lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; -/***/ }), -/* 398 */ -/***/ (function(module, exports) { + return [h, sl * 100, l * 100]; +}; -// This is not the set of all possible signals. -// -// It IS, however, the set of all signals that trigger -// an exit on either Linux or BSD systems. Linux is a -// superset of the signal names supported on BSD, and -// the unknown signals just fail to register, so we can -// catch that easily enough. -// -// Don't bother with SIGKILL. It's uncatchable, which -// means that we can't fire any callbacks anyway. -// -// If a user does happen to register a handler on a non- -// fatal signal like SIGWINCH or something, and then -// exit, it'll end up firing `process.emit('exit')`, so -// the handler will be fired anyway. -// -// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised -// artificially, inherently leave the process in a -// state from which it is not safe to try and enter JS -// listeners. -module.exports = [ - 'SIGABRT', - 'SIGALRM', - 'SIGHUP', - 'SIGINT', - 'SIGTERM' -] - -if (process.platform !== 'win32') { - module.exports.push( - 'SIGVTALRM', - 'SIGXCPU', - 'SIGXFSZ', - 'SIGUSR2', - 'SIGTRAP', - 'SIGSYS', - 'SIGQUIT', - 'SIGIOT' - // should detect profiler and enable/disable accordingly. - // see #21 - // 'SIGPROF' - ) -} - -if (process.platform === 'linux') { - module.exports.push( - 'SIGIO', - 'SIGPOLL', - 'SIGPWR', - 'SIGSTKFLT', - 'SIGUNUSED' - ) -} - - -/***/ }), -/* 399 */ -/***/ (function(module, exports) { - -module.exports = require("events"); - -/***/ }), -/* 400 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const isStream = __webpack_require__(401); -const getStream = __webpack_require__(402); -const mergeStream = __webpack_require__(408); +// http://dev.w3.org/csswg/css-color/#hwb-to-rgb +convert.hwb.rgb = function (hwb) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl = hwb[2] / 100; + var ratio = wh + bl; + var i; + var v; + var f; + var n; -// `input` option -const handleInput = (spawned, input) => { - // Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852 - // TODO: Remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0 - if (input === undefined || spawned.stdin === undefined) { - return; + // wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; } - if (isStream(input)) { - input.pipe(spawned.stdin); - } else { - spawned.stdin.end(input); - } -}; + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; -// `all` interleaves `stdout` and `stderr` -const makeAllStream = (spawned, {all}) => { - if (!all || (!spawned.stdout && !spawned.stderr)) { - return; + if ((i & 0x01) !== 0) { + f = 1 - f; } - const mixed = mergeStream(); - - if (spawned.stdout) { - mixed.add(spawned.stdout); - } + n = wh + f * (v - wh); // linear interpolation - if (spawned.stderr) { - mixed.add(spawned.stderr); + var r; + var g; + var b; + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; } - return mixed; + return [r * 255, g * 255, b * 255]; }; -// On failure, `result.stdout|stderr|all` should contain the currently buffered stream -const getBufferedData = async (stream, streamPromise) => { - if (!stream) { - return; - } +convert.cmyk.rgb = function (cmyk) { + var c = cmyk[0] / 100; + var m = cmyk[1] / 100; + var y = cmyk[2] / 100; + var k = cmyk[3] / 100; + var r; + var g; + var b; - stream.destroy(); + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); - try { - return await streamPromise; - } catch (error) { - return error.bufferedData; - } + return [r * 255, g * 255, b * 255]; }; -const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => { - if (!stream || !buffer) { - return; - } +convert.xyz.rgb = function (xyz) { + var x = xyz[0] / 100; + var y = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var b; - if (encoding) { - return getStream(stream, {encoding, maxBuffer}); - } + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); - return getStream.buffer(stream, {maxBuffer}); -}; + // assume sRGB + r = r > 0.0031308 + ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) + : r * 12.92; -// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all) -const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => { - const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer}); - const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer}); - const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2}); + g = g > 0.0031308 + ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) + : g * 12.92; - try { - return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]); - } catch (error) { - return Promise.all([ - {error, signal: error.signal, timedOut: error.timedOut}, - getBufferedData(stdout, stdoutPromise), - getBufferedData(stderr, stderrPromise), - getBufferedData(all, allPromise) - ]); - } -}; + b = b > 0.0031308 + ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) + : b * 12.92; -const validateInputSync = ({input}) => { - if (isStream(input)) { - throw new TypeError('The `input` option cannot be a stream in sync mode'); - } -}; + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); -module.exports = { - handleInput, - makeAllStream, - getSpawnedResult, - validateInputSync + return [r * 255, g * 255, b * 255]; }; +convert.xyz.lab = function (xyz) { + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + x /= 95.047; + y /= 100; + z /= 108.883; -/***/ }), -/* 401 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const isStream = stream => - stream !== null && - typeof stream === 'object' && - typeof stream.pipe === 'function'; + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); -isStream.writable = stream => - isStream(stream) && - stream.writable !== false && - typeof stream._write === 'function' && - typeof stream._writableState === 'object'; + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); -isStream.readable = stream => - isStream(stream) && - stream.readable !== false && - typeof stream._read === 'function' && - typeof stream._readableState === 'object'; + return [l, a, b]; +}; -isStream.duplex = stream => - isStream.writable(stream) && - isStream.readable(stream); +convert.lab.xyz = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var x; + var y; + var z; -isStream.transform = stream => - isStream.duplex(stream) && - typeof stream._transform === 'function' && - typeof stream._transformState === 'object'; + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; -module.exports = isStream; + var y2 = Math.pow(y, 3); + var x2 = Math.pow(x, 3); + var z2 = Math.pow(z, 3); + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + x *= 95.047; + y *= 100; + z *= 108.883; -/***/ }), -/* 402 */ -/***/ (function(module, exports, __webpack_require__) { + return [x, y, z]; +}; -"use strict"; +convert.lab.lch = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var hr; + var h; + var c; -const pump = __webpack_require__(403); -const bufferStream = __webpack_require__(407); + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; -class MaxBufferError extends Error { - constructor() { - super('maxBuffer exceeded'); - this.name = 'MaxBufferError'; + if (h < 0) { + h += 360; } -} -async function getStream(inputStream, options) { - if (!inputStream) { - return Promise.reject(new Error('Expected a stream')); - } + c = Math.sqrt(a * a + b * b); - options = { - maxBuffer: Infinity, - ...options - }; + return [l, c, h]; +}; - const {maxBuffer} = options; +convert.lch.lab = function (lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b; + var hr; - let stream; - await new Promise((resolve, reject) => { - const rejectPromise = error => { - if (error) { // A null check - error.bufferedData = stream.getBufferedValue(); - } + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); - reject(error); - }; + return [l, a, b]; +}; - stream = pump(inputStream, bufferStream(options), error => { - if (error) { - rejectPromise(error); - return; - } +convert.rgb.ansi16 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization - resolve(); - }); + value = Math.round(value / 50); - stream.on('data', () => { - if (stream.getBufferedLength() > maxBuffer) { - rejectPromise(new MaxBufferError()); - } - }); - }); + if (value === 0) { + return 30; + } - return stream.getBufferedValue(); -} + var ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); -module.exports = getStream; -// TODO: Remove this for the next major release -module.exports.default = getStream; -module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); -module.exports.array = (stream, options) => getStream(stream, {...options, array: true}); -module.exports.MaxBufferError = MaxBufferError; + if (value === 2) { + ansi += 60; + } + return ansi; +}; -/***/ }), -/* 403 */ -/***/ (function(module, exports, __webpack_require__) { +convert.hsv.ansi16 = function (args) { + // optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); +}; -var once = __webpack_require__(404) -var eos = __webpack_require__(406) -var fs = __webpack_require__(23) // we only need fs to get the ReadStream and WriteStream prototypes +convert.rgb.ansi256 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; -var noop = function () {} -var ancient = /^v?\.0/.test(process.version) + // we use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } -var isFn = function (fn) { - return typeof fn === 'function' -} + if (r > 248) { + return 231; + } -var isFS = function (stream) { - if (!ancient) return false // newer node version do not need to care about fs is a special way - if (!fs) return false // browser - return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) -} + return Math.round(((r - 8) / 247) * 24) + 232; + } -var isRequest = function (stream) { - return stream.setHeader && isFn(stream.abort) -} + var ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); -var destroyer = function (stream, reading, writing, callback) { - callback = once(callback) + return ansi; +}; - var closed = false - stream.on('close', function () { - closed = true - }) +convert.ansi16.rgb = function (args) { + var color = args % 10; - eos(stream, {readable: reading, writable: writing}, function (err) { - if (err) return callback(err) - closed = true - callback() - }) + // handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } - var destroyed = false - return function (err) { - if (closed) return - if (destroyed) return - destroyed = true + color = color / 10.5 * 255; - if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks - if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want + return [color, color, color]; + } - if (isFn(stream.destroy)) return stream.destroy() + var mult = (~~(args > 50) + 1) * 0.5; + var r = ((color & 1) * mult) * 255; + var g = (((color >> 1) & 1) * mult) * 255; + var b = (((color >> 2) & 1) * mult) * 255; - callback(err || new Error('stream was destroyed')) - } -} + return [r, g, b]; +}; -var call = function (fn) { - fn() -} +convert.ansi256.rgb = function (args) { + // handle greyscale + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } -var pipe = function (from, to) { - return from.pipe(to) -} + args -= 16; -var pump = function () { - var streams = Array.prototype.slice.call(arguments) - var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b = (rem % 6) / 5 * 255; - if (Array.isArray(streams[0])) streams = streams[0] - if (streams.length < 2) throw new Error('pump requires two streams per minimum') + return [r, g, b]; +}; - var error - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1 - var writing = i > 0 - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err - if (err) destroys.forEach(call) - if (reading) return - destroys.forEach(call) - callback(error) - }) - }) +convert.rgb.hex = function (args) { + var integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); - return streams.reduce(pipe) -} + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; -module.exports = pump +convert.hex.rgb = function (args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + var colorString = match[0]; -/***/ }), -/* 404 */ -/***/ (function(module, exports, __webpack_require__) { + if (match[0].length === 3) { + colorString = colorString.split('').map(function (char) { + return char + char; + }).join(''); + } -var wrappy = __webpack_require__(405) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) + var integer = parseInt(colorString, 16); + var r = (integer >> 16) & 0xFF; + var g = (integer >> 8) & 0xFF; + var b = integer & 0xFF; -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) - - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }) -}) - -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) - } - f.called = false - return f -} - -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) - } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f -} - - -/***/ }), -/* 405 */ -/***/ (function(module, exports) { - -// Returns a wrapper function that returns a wrapped callback -// The wrapper function should do some stuff, and return a -// presumably different callback function. -// This makes sure that own properties are retained, so that -// decorations and such are not lost along the way. -module.exports = wrappy -function wrappy (fn, cb) { - if (fn && cb) return wrappy(fn)(cb) - - if (typeof fn !== 'function') - throw new TypeError('need wrapper function') - - Object.keys(fn).forEach(function (k) { - wrapper[k] = fn[k] - }) - - return wrapper - - function wrapper() { - var args = new Array(arguments.length) - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] - } - var ret = fn.apply(this, args) - var cb = args[args.length-1] - if (typeof ret === 'function' && ret !== cb) { - Object.keys(cb).forEach(function (k) { - ret[k] = cb[k] - }) - } - return ret - } -} - - -/***/ }), -/* 406 */ -/***/ (function(module, exports, __webpack_require__) { - -var once = __webpack_require__(404); - -var noop = function() {}; - -var isRequest = function(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -}; - -var isChildProcess = function(stream) { - return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 + return [r, g, b]; }; -var eos = function(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - - callback = once(callback || noop); - - var ws = stream._writableState; - var rs = stream._readableState; - var readable = opts.readable || (opts.readable !== false && stream.readable); - var writable = opts.writable || (opts.writable !== false && stream.writable); - - var onlegacyfinish = function() { - if (!stream.writable) onfinish(); - }; - - var onfinish = function() { - writable = false; - if (!readable) callback.call(stream); - }; - - var onend = function() { - readable = false; - if (!writable) callback.call(stream); - }; - - var onexit = function(exitCode) { - callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); - }; - - var onerror = function(err) { - callback.call(stream, err); - }; - - var onclose = function() { - if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close')); - if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close')); - }; - - var onrequest = function() { - stream.req.on('finish', onfinish); - }; +convert.rgb.hcg = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b); + var min = Math.min(Math.min(r, g), b); + var chroma = (max - min); + var grayscale; + var hue; - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest(); - else stream.on('request', onrequest); - } else if (writable && !ws) { // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; } - if (isChildProcess(stream)) stream.on('exit', onexit); + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma + 4; + } - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); + hue /= 6; + hue %= 1; - return function() { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('exit', onexit); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; + return [hue * 360, chroma * 100, grayscale * 100]; }; -module.exports = eos; - - -/***/ }), -/* 407 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const {PassThrough: PassThroughStream} = __webpack_require__(27); - -module.exports = options => { - options = {...options}; - - const {array} = options; - let {encoding} = options; - const isBuffer = encoding === 'buffer'; - let objectMode = false; +convert.hsl.hcg = function (hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; - if (array) { - objectMode = !(encoding || isBuffer); + if (l < 0.5) { + c = 2.0 * s * l; } else { - encoding = encoding || 'utf8'; - } - - if (isBuffer) { - encoding = null; + c = 2.0 * s * (1.0 - l); } - const stream = new PassThroughStream({objectMode}); - - if (encoding) { - stream.setEncoding(encoding); + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); } - let length = 0; - const chunks = []; - - stream.on('data', chunk => { - chunks.push(chunk); - - if (objectMode) { - length = chunks.length; - } else { - length += chunk.length; - } - }); - - stream.getBufferedValue = () => { - if (array) { - return chunks; - } - - return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); - }; - - stream.getBufferedLength = () => length; - - return stream; + return [hsl[0], c * 100, f * 100]; }; +convert.hsv.hcg = function (hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; -/***/ }), -/* 408 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; + var c = s * v; + var f = 0; + if (c < 1.0) { + f = (v - c) / (1 - c); + } -const { PassThrough } = __webpack_require__(27); + return [hsv[0], c * 100, f * 100]; +}; -module.exports = function (/*streams...*/) { - var sources = [] - var output = new PassThrough({objectMode: true}) +convert.hcg.rgb = function (hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; - output.setMaxListeners(0) + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } - output.add = add - output.isEmpty = isEmpty + var pure = [0, 0, 0]; + var hi = (h % 1) * 6; + var v = hi % 1; + var w = 1 - v; + var mg = 0; - output.on('unpipe', remove) + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } - Array.prototype.slice.call(arguments).forEach(add) + mg = (1.0 - c) * g; - return output + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; +}; - function add (source) { - if (Array.isArray(source)) { - source.forEach(add) - return this - } +convert.hcg.hsv = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; - sources.push(source); - source.once('end', remove.bind(null, source)) - source.once('error', output.emit.bind(output, 'error')) - source.pipe(output, {end: false}) - return this - } + var v = c + g * (1.0 - c); + var f = 0; - function isEmpty () { - return sources.length == 0; - } + if (v > 0.0) { + f = c / v; + } - function remove (source) { - sources = sources.filter(function (it) { return it !== source }) - if (!sources.length && output.readable) { output.end() } - } -} + return [hcg[0], f * 100, v * 100]; +}; +convert.hcg.hsl = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; -/***/ }), -/* 409 */ -/***/ (function(module, exports, __webpack_require__) { + var l = g * (1.0 - c) + 0.5 * c; + var s = 0; -"use strict"; + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + return [hcg[0], s * 100, l * 100]; +}; -const nativePromisePrototype = (async () => {})().constructor.prototype; -const descriptors = ['then', 'catch', 'finally'].map(property => [ - property, - Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property) -]); +convert.hcg.hwb = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; +}; -// The return value is a mixin of `childProcess` and `Promise` -const mergePromise = (spawned, promise) => { - for (const [property, descriptor] of descriptors) { - // Starting the main `promise` is deferred to avoid consuming streams - const value = typeof promise === 'function' ? - (...args) => Reflect.apply(descriptor.value, promise(), args) : - descriptor.value.bind(promise); +convert.hwb.hcg = function (hwb) { + var w = hwb[1] / 100; + var b = hwb[2] / 100; + var v = 1 - b; + var c = v - w; + var g = 0; - Reflect.defineProperty(spawned, property, {...descriptor, value}); + if (c < 1) { + g = (v - c) / (1 - c); } - return spawned; + return [hwb[0], c * 100, g * 100]; }; -// Use promises instead of `child_process` events -const getSpawnedPromise = spawned => { - return new Promise((resolve, reject) => { - spawned.on('exit', (exitCode, signal) => { - resolve({exitCode, signal}); - }); - - spawned.on('error', error => { - reject(error); - }); - - if (spawned.stdin) { - spawned.stdin.on('error', error => { - reject(error); - }); - } - }); +convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; }; -module.exports = { - mergePromise, - getSpawnedPromise +convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; }; - - -/***/ }), -/* 410 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const SPACES_REGEXP = / +/g; - -const joinCommand = (file, args = []) => { - if (!Array.isArray(args)) { - return file; - } - - return [file, ...args].join(' '); +convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; }; -// Allow spaces to be escaped by a backslash if not meant as a delimiter -const handleEscaping = (tokens, token, index) => { - if (index === 0) { - return [token]; - } +convert.gray.hsl = convert.gray.hsv = function (args) { + return [0, 0, args[0]]; +}; - const previousToken = tokens[tokens.length - 1]; +convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; +}; - if (previousToken.endsWith('\\')) { - return [...tokens.slice(0, -1), `${previousToken.slice(0, -1)} ${token}`]; - } +convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; +}; - return [...tokens, token]; +convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; }; -// Handle `execa.command()` -const parseCommand = command => { - return command - .trim() - .split(SPACES_REGEXP) - .reduce(handleEscaping, []); +convert.gray.hex = function (gray) { + var val = Math.round(gray[0] / 100 * 255) & 0xFF; + var integer = (val << 16) + (val << 8) + val; + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; }; -module.exports = { - joinCommand, - parseCommand +convert.rgb.gray = function (rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; }; /***/ }), -/* 411 */ +/* 391 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; + + +module.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; -var childProcess = __webpack_require__(372); -var spawn = childProcess.spawn; -var exec = childProcess.exec; - -module.exports = function (pid, signal, callback) { - if (typeof signal === 'function' && callback === undefined) { - callback = signal; - signal = undefined; - } - - pid = parseInt(pid); - if (Number.isNaN(pid)) { - if (callback) { - return callback(new Error("pid must be a number")); - } else { - throw new Error("pid must be a number"); - } - } - - var tree = {}; - var pidsToProcess = {}; - tree[pid] = []; - pidsToProcess[pid] = 1; - - switch (process.platform) { - case 'win32': - exec('taskkill /pid ' + pid + ' /T /F', callback); - break; - case 'darwin': - buildProcessTree(pid, tree, pidsToProcess, function (parentPid) { - return spawn('pgrep', ['-P', parentPid]); - }, function () { - killAll(tree, signal, callback); - }); - break; - // case 'sunos': - // buildProcessTreeSunOS(pid, tree, pidsToProcess, function () { - // killAll(tree, signal, callback); - // }); - // break; - default: // Linux - buildProcessTree(pid, tree, pidsToProcess, function (parentPid) { - return spawn('ps', ['-o', 'pid', '--no-headers', '--ppid', parentPid]); - }, function () { - killAll(tree, signal, callback); - }); - break; - } -}; - -function killAll (tree, signal, callback) { - var killed = {}; - try { - Object.keys(tree).forEach(function (pid) { - tree[pid].forEach(function (pidpid) { - if (!killed[pidpid]) { - killPid(pidpid, signal); - killed[pidpid] = 1; - } - }); - if (!killed[pid]) { - killPid(pid, signal); - killed[pid] = 1; - } - }); - } catch (err) { - if (callback) { - return callback(err); - } else { - throw err; - } - } - if (callback) { - return callback(); - } -} - -function killPid(pid, signal) { - try { - process.kill(parseInt(pid, 10), signal); - } - catch (err) { - if (err.code !== 'ESRCH') throw err; - } -} +/***/ }), +/* 392 */ +/***/ (function(module, exports, __webpack_require__) { -function buildProcessTree (parentPid, tree, pidsToProcess, spawnChildProcessesList, cb) { - var ps = spawnChildProcessesList(parentPid); - var allData = ''; - ps.stdout.on('data', function (data) { - var data = data.toString('ascii'); - allData += data; - }); +var conversions = __webpack_require__(390); - var onClose = function (code) { - delete pidsToProcess[parentPid]; +/* + this function routes a model to all other models. - if (code != 0) { - // no more parent processes - if (Object.keys(pidsToProcess).length == 0) { - cb(); - } - return; - } + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). - allData.match(/\d+/g).forEach(function (pid) { - pid = parseInt(pid, 10); - tree[parentPid].push(pid); - tree[pid] = []; - pidsToProcess[pid] = 1; - buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb); - }); - }; + conversions that are not possible simply are not included. +*/ - ps.on('close', onClose); +function buildGraph() { + var graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + var models = Object.keys(conversions); + + for (var len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; } +// https://en.wikipedia.org/wiki/Breadth-first_search +function deriveBFS(fromModel) { + var graph = buildGraph(); + var queue = [fromModel]; // unshift -> queue -> pop -/***/ }), -/* 412 */ -/***/ (function(module, exports, __webpack_require__) { + graph[fromModel].distance = 0; -"use strict"; + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions[current]); -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(36); -const Rx = tslib_1.__importStar(__webpack_require__(169)); -const operators_1 = __webpack_require__(270); -const SEP = /\r?\n/; -const observe_readable_1 = __webpack_require__(413); -/** - * Creates an Observable from a Readable Stream that: - * - splits data from `readable` into lines - * - completes when `readable` emits "end" - * - fails if `readable` emits "errors" - * - * @param {ReadableStream} readable - * @return {Rx.Observable} - */ -function observeLines(readable) { - const done$ = observe_readable_1.observeReadable(readable).pipe(operators_1.share()); - const scan$ = Rx.fromEvent(readable, 'data').pipe(operators_1.scan(({ buffer }, chunk) => { - buffer += chunk; - const lines = []; - while (true) { - const match = buffer.match(SEP); - if (!match || match.index === undefined) { - break; - } - lines.push(buffer.slice(0, match.index)); - buffer = buffer.slice(match.index + match[0].length); - } - return { buffer, lines }; - }, { buffer: '' }), - // stop if done completes or errors - operators_1.takeUntil(done$.pipe(operators_1.materialize())), operators_1.share()); - return Rx.merge( - // use done$ to provide completion/errors - done$, - // merge in the "lines" from each step - scan$.pipe(operators_1.mergeMap(({ lines }) => lines || [])), - // inject the "unsplit" data at the end - scan$.pipe(operators_1.last(), operators_1.mergeMap(({ buffer }) => (buffer ? [buffer] : [])), - // if there were no lines, last() will error, so catch and complete - operators_1.catchError(() => Rx.empty()))); + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; } -exports.observeLines = observeLines; +function link(from, to) { + return function (args) { + return to(from(args)); + }; +} -/***/ }), -/* 413 */ -/***/ (function(module, exports, __webpack_require__) { +function wrapConversion(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions[graph[toModel].parent][toModel]; -"use strict"; + var cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(36); -const Rx = tslib_1.__importStar(__webpack_require__(169)); -const operators_1 = __webpack_require__(270); -/** - * Produces an Observable from a ReadableSteam that: - * - completes on the first "end" event - * - fails on the first "error" event - */ -function observeReadable(readable) { - return Rx.race(Rx.fromEvent(readable, 'end').pipe(operators_1.first(), operators_1.ignoreElements()), Rx.fromEvent(readable, 'error').pipe(operators_1.first(), operators_1.mergeMap((err) => Rx.throwError(err)))); + fn.conversion = path; + return fn; } -exports.observeReadable = observeReadable; +module.exports = function (fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; -/***/ }), -/* 414 */ -/***/ (function(module, exports, __webpack_require__) { + var models = Object.keys(graph); + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; -"use strict"; + if (node.parent === null) { + // no possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; +}; -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -var tooling_log_1 = __webpack_require__(415); -exports.ToolingLog = tooling_log_1.ToolingLog; -var tooling_log_text_writer_1 = __webpack_require__(416); -exports.ToolingLogTextWriter = tooling_log_text_writer_1.ToolingLogTextWriter; -var log_levels_1 = __webpack_require__(417); -exports.pickLevelFromFlags = log_levels_1.pickLevelFromFlags; -exports.parseLogLevel = log_levels_1.parseLogLevel; -var tooling_log_collecting_writer_1 = __webpack_require__(418); -exports.ToolingLogCollectingWriter = tooling_log_collecting_writer_1.ToolingLogCollectingWriter; /***/ }), -/* 415 */ +/* 393 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(36); -const Rx = tslib_1.__importStar(__webpack_require__(169)); -const tooling_log_text_writer_1 = __webpack_require__(416); -class ToolingLog { - constructor(writerConfig) { - this.identWidth = 0; - this.writers = writerConfig ? [new tooling_log_text_writer_1.ToolingLogTextWriter(writerConfig)] : []; - this.written$ = new Rx.Subject(); - } - indent(delta = 0) { - this.identWidth = Math.max(this.identWidth + delta, 0); - return this.identWidth; - } - verbose(...args) { - this.sendToWriters('verbose', args); - } - debug(...args) { - this.sendToWriters('debug', args); - } - info(...args) { - this.sendToWriters('info', args); - } - success(...args) { - this.sendToWriters('success', args); - } - warning(...args) { - this.sendToWriters('warning', args); - } - error(error) { - this.sendToWriters('error', [error]); - } - write(...args) { - this.sendToWriters('write', args); - } - getWriters() { - return this.writers.slice(0); - } - setWriters(writers) { - this.writers = [...writers]; - } - getWritten$() { - return this.written$.asObservable(); - } - sendToWriters(type, args) { - const msg = { - type, - indent: this.identWidth, - args, - }; - let written = false; - for (const writer of this.writers) { - if (writer.write(msg)) { - written = true; - } - } - if (written) { - this.written$.next(msg); - } - } -} -exports.ToolingLog = ToolingLog; - +const os = __webpack_require__(364); +const hasFlag = __webpack_require__(394); -/***/ }), -/* 416 */ -/***/ (function(module, exports, __webpack_require__) { +const env = process.env; -"use strict"; +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; +} -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(36); -const util_1 = __webpack_require__(29); -const chalk_1 = tslib_1.__importDefault(__webpack_require__(2)); -const log_levels_1 = __webpack_require__(417); -const { magentaBright, yellow, red, blue, green, dim } = chalk_1.default; -const PREFIX_INDENT = ' '.repeat(6); -const MSG_PREFIXES = { - verbose: ` ${magentaBright('sill')} `, - debug: ` ${dim('debg')} `, - info: ` ${blue('info')} `, - success: ` ${green('succ')} `, - warning: ` ${yellow('warn')} `, - error: `${red('ERROR')} `, -}; -const has = (obj, key) => obj.hasOwnProperty(key); -function shouldWriteType(level, type) { - if (type === 'write') { - return true; - } - return Boolean(level.flags[type === 'success' ? 'info' : type]); -} -function stringifyError(error) { - if (typeof error !== 'string' && !(error instanceof Error)) { - error = new Error(`"${error}" thrown`); - } - if (typeof error === 'string') { - return error; - } - return error.stack || error.message || error; -} -class ToolingLogTextWriter { - constructor(config) { - this.level = log_levels_1.parseLogLevel(config.level); - this.writeTo = config.writeTo; - if (!this.writeTo || typeof this.writeTo.write !== 'function') { - throw new Error('ToolingLogTextWriter requires the `writeTo` option be set to a stream (like process.stdout)'); - } - } - write(msg) { - if (!shouldWriteType(this.level, msg.type)) { - return false; - } - const prefix = has(MSG_PREFIXES, msg.type) ? MSG_PREFIXES[msg.type] : ''; - ToolingLogTextWriter.write(this.writeTo, prefix, msg); - return true; - } - static write(writeTo, prefix, msg) { - const txt = msg.type === 'error' - ? stringifyError(msg.args[0]) - : util_1.format(msg.args[0], ...msg.args.slice(1)); - (prefix + txt).split('\n').forEach((line, i) => { - let lineIndent = ''; - if (msg.indent > 0) { - // if we are indenting write some spaces followed by a symbol - lineIndent += ' '.repeat(msg.indent - 1); - lineIndent += line.startsWith('-') ? '└' : '│'; - } - if (line && prefix && i > 0) { - // apply additional indentation to lines after - // the first if this message gets a prefix - lineIndent += PREFIX_INDENT; - } - writeTo.write(`${lineIndent}${line}\n`); - }); - } +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; } -exports.ToolingLogTextWriter = ToolingLogTextWriter; +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } -/***/ }), -/* 417 */ -/***/ (function(module, exports, __webpack_require__) { + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } -"use strict"; + if (hasFlag('color=256')) { + return 2; + } -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const LEVELS = ['silent', 'error', 'warning', 'info', 'debug', 'verbose']; -function pickLevelFromFlags(flags, options = {}) { - if (flags.verbose) - return 'verbose'; - if (flags.debug) - return 'debug'; - if (flags.quiet) - return 'error'; - if (flags.silent) - return 'silent'; - return options.default || 'info'; -} -exports.pickLevelFromFlags = pickLevelFromFlags; -function parseLogLevel(name) { - const i = LEVELS.indexOf(name); - if (i === -1) { - const msg = `Invalid log level "${name}" ` + `(expected one of ${LEVELS.join(',')})`; - throw new Error(msg); - } - const flags = {}; - LEVELS.forEach((level, levelI) => { - flags[level] = levelI <= i; - }); - return { - name, - flags: flags, - }; -} -exports.parseLogLevel = parseLogLevel; + if (stream && !stream.isTTY && forceColor !== true) { + // VS code debugger doesn't have isTTY set + if (env.VSCODE_PID) { + return 1; + } + return 0; + } + const min = forceColor ? 1 : 0; -/***/ }), -/* 418 */ -/***/ (function(module, exports, __webpack_require__) { + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(process.versions.node.split('.')[0]) >= 8 && + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } -"use strict"; + return 1; + } -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const tooling_log_text_writer_1 = __webpack_require__(416); -class ToolingLogCollectingWriter extends tooling_log_text_writer_1.ToolingLogTextWriter { - constructor() { - super({ - level: 'verbose', - writeTo: { - write: (msg) => { - // trim trailing new line - this.messages.push(msg.slice(0, -1)); - }, - }, - }); - this.messages = []; - } -} -exports.ToolingLogCollectingWriter = ToolingLogCollectingWriter; + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + return min; + } -/***/ }), -/* 419 */ -/***/ (function(module, exports, __webpack_require__) { + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } -"use strict"; + if (env.COLORTERM === 'truecolor') { + return 3; + } -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -var absolute_path_serializer_1 = __webpack_require__(420); -exports.createAbsolutePathSerializer = absolute_path_serializer_1.createAbsolutePathSerializer; + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } -/***/ }), -/* 420 */ -/***/ (function(module, exports, __webpack_require__) { + if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } -"use strict"; + if ('COLORTERM' in env) { + return 1; + } -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const repo_root_1 = __webpack_require__(421); -function createAbsolutePathSerializer(rootPath = repo_root_1.REPO_ROOT) { - return { - print: (value) => value.replace(rootPath, '').replace(/\\/g, '/'), - test: (value) => typeof value === 'string' && value.startsWith(rootPath), - }; + if (env.TERM === 'dumb') { + return min; + } + + return min; } -exports.createAbsolutePathSerializer = createAbsolutePathSerializer; + +function getSupportLevel(stream) { + const level = supportsColor(stream); + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) +}; /***/ }), -/* 421 */ +/* 394 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(36); -const path_1 = tslib_1.__importDefault(__webpack_require__(16)); -const fs_1 = tslib_1.__importDefault(__webpack_require__(23)); -const load_json_file_1 = tslib_1.__importDefault(__webpack_require__(422)); -const isKibanaDir = (dir) => { - try { - const path = path_1.default.resolve(dir, 'package.json'); - const json = load_json_file_1.default.sync(path); - if (json && typeof json === 'object' && 'name' in json && json.name === 'kibana') { - return true; - } - } - catch (error) { - if (error && error.code === 'ENOENT') { - return false; - } - throw error; - } +module.exports = (flag, argv) => { + argv = argv || process.argv; + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const pos = argv.indexOf(prefix + flag); + const terminatorPos = argv.indexOf('--'); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); }; -// search for the kibana directory, since this file is moved around it might -// not be where we think but should always be a relatively close parent -// of this directory -const startDir = fs_1.default.realpathSync(__dirname); -const { root: rootDir } = path_1.default.parse(startDir); -let cursor = startDir; -while (true) { - if (isKibanaDir(cursor)) { - break; - } - const parent = path_1.default.dirname(cursor); - if (parent === rootDir) { - throw new Error(`unable to find kibana directory from ${startDir}`); - } - cursor = parent; -} -exports.REPO_ROOT = cursor; /***/ }), -/* 422 */ +/* 395 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const path = __webpack_require__(16); -const {promisify} = __webpack_require__(29); -const fs = __webpack_require__(423); -const stripBom = __webpack_require__(427); -const parseJson = __webpack_require__(428); +const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; +const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; +const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; +const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; -const parse = (data, filePath, options = {}) => { - data = stripBom(data); +const ESCAPES = new Map([ + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['b', '\b'], + ['f', '\f'], + ['v', '\v'], + ['0', '\0'], + ['\\', '\\'], + ['e', '\u001B'], + ['a', '\u0007'] +]); - if (typeof options.beforeParse === 'function') { - data = options.beforeParse(data); +function unescape(c) { + if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { + return String.fromCharCode(parseInt(c.slice(1), 16)); } - return parseJson(data, options.reviver, path.relative(process.cwd(), filePath)); -}; - -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); + return ESCAPES.get(c) || c; +} +function parseArguments(name, args) { + const results = []; + const chunks = args.trim().split(/\s*,\s*/g); + let matches; -/***/ }), -/* 423 */ -/***/ (function(module, exports, __webpack_require__) { + for (const chunk of chunks) { + if (!isNaN(chunk)) { + results.push(Number(chunk)); + } else if ((matches = chunk.match(STRING_REGEX))) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } -var fs = __webpack_require__(23) -var polyfills = __webpack_require__(424) -var legacy = __webpack_require__(425) -var clone = __webpack_require__(426) + return results; +} -var queue = [] +function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; -var util = __webpack_require__(29) + const results = []; + let matches; -function noop () {} + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; -var debug = noop -if (util.debuglog) - debug = util.debuglog('gfs4') -else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) - debug = function() { - var m = util.format.apply(util, arguments) - m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') - console.error(m) - } + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } -if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug(queue) - __webpack_require__(30).equal(queue.length, 0) - }) + return results; } -module.exports = patch(clone(fs)) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { - module.exports = patch(fs) - fs.__patched = true; -} +function buildStyle(chalk, styles) { + const enabled = {}; -// Always patch fs.close/closeSync, because we want to -// retry() whenever a close happens *anywhere* in the program. -// This is essential when multiple graceful-fs instances are -// in play at the same time. -module.exports.close = (function (fs$close) { return function (fd, cb) { - return fs$close.call(fs, fd, function (err) { - if (!err) - retry() + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } - if (typeof cb === 'function') - cb.apply(this, arguments) - }) -}})(fs.close) + let current = chalk; + for (const styleName of Object.keys(enabled)) { + if (Array.isArray(enabled[styleName])) { + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } -module.exports.closeSync = (function (fs$closeSync) { return function (fd) { - // Note that graceful-fs also retries when fs.closeSync() fails. - // Looks like a bug to me, although it's probably a harmless one. - var rval = fs$closeSync.apply(fs, arguments) - retry() - return rval -}})(fs.closeSync) + if (enabled[styleName].length > 0) { + current = current[styleName].apply(current, enabled[styleName]); + } else { + current = current[styleName]; + } + } + } -// Only patch fs once, otherwise we'll run into a memory leak if -// graceful-fs is loaded multiple times, such as in test environments that -// reset the loaded modules between tests. -// We look for the string `graceful-fs` from the comment above. This -// way we are not adding any extra properties and it will detect if older -// versions of graceful-fs are installed. -if (!/\bgraceful-fs\b/.test(fs.closeSync.toString())) { - fs.closeSync = module.exports.closeSync; - fs.close = module.exports.close; + return current; } -function patch (fs) { - // Everything that references the open() function needs to be in here - polyfills(fs) - fs.gracefulify = patch - fs.FileReadStream = ReadStream; // Legacy name. - fs.FileWriteStream = WriteStream; // Legacy name. - fs.createReadStream = createReadStream - fs.createWriteStream = createWriteStream - var fs$readFile = fs.readFile - fs.readFile = readFile - function readFile (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null - - return go$readFile(path, options, cb) +module.exports = (chalk, tmp) => { + const styles = []; + const chunks = []; + let chunk = []; - function go$readFile (path, options, cb) { - return fs$readFile(path, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readFile, [path, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } + // eslint-disable-next-line max-params + tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { + if (escapeChar) { + chunk.push(unescape(escapeChar)); + } else if (style) { + const str = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); + styles.push({inverse, styles: parseStyle(style)}); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } - var fs$writeFile = fs.writeFile - fs.writeFile = writeFile - function writeFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(chr); + } + }); - return go$writeFile(path, data, options, cb) + chunks.push(chunk.join('')); - function go$writeFile (path, data, options, cb) { - return fs$writeFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$writeFile, [path, data, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } + if (styles.length > 0) { + const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMsg); + } - var fs$appendFile = fs.appendFile - if (fs$appendFile) - fs.appendFile = appendFile - function appendFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null + return chunks.join(''); +}; - return go$appendFile(path, data, options, cb) - function go$appendFile (path, data, options, cb) { - return fs$appendFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$appendFile, [path, data, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } +/***/ }), +/* 396 */ +/***/ (function(module, exports, __webpack_require__) { - var fs$readdir = fs.readdir - fs.readdir = readdir - function readdir (path, options, cb) { - var args = [path] - if (typeof options !== 'function') { - args.push(options) - } else { - cb = options - } - args.push(go$readdir$cb) +"use strict"; - return go$readdir(args) - function go$readdir$cb (err, files) { - if (files && files.sort) - files.sort() +var childProcess = __webpack_require__(343); +var spawn = childProcess.spawn; +var exec = childProcess.exec; - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readdir, [args]]) +module.exports = function (pid, signal, callback) { + if (typeof signal === 'function' && callback === undefined) { + callback = signal; + signal = undefined; + } - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } + pid = parseInt(pid); + if (Number.isNaN(pid)) { + if (callback) { + return callback(new Error("pid must be a number")); + } else { + throw new Error("pid must be a number"); + } } - } - function go$readdir (args) { - return fs$readdir.apply(fs, args) - } + var tree = {}; + var pidsToProcess = {}; + tree[pid] = []; + pidsToProcess[pid] = 1; - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs) - ReadStream = legStreams.ReadStream - WriteStream = legStreams.WriteStream - } + switch (process.platform) { + case 'win32': + exec('taskkill /pid ' + pid + ' /T /F', callback); + break; + case 'darwin': + buildProcessTree(pid, tree, pidsToProcess, function (parentPid) { + return spawn('pgrep', ['-P', parentPid]); + }, function () { + killAll(tree, signal, callback); + }); + break; + // case 'sunos': + // buildProcessTreeSunOS(pid, tree, pidsToProcess, function () { + // killAll(tree, signal, callback); + // }); + // break; + default: // Linux + buildProcessTree(pid, tree, pidsToProcess, function (parentPid) { + return spawn('ps', ['-o', 'pid', '--no-headers', '--ppid', parentPid]); + }, function () { + killAll(tree, signal, callback); + }); + break; + } +}; - var fs$ReadStream = fs.ReadStream - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open - } +function killAll (tree, signal, callback) { + var killed = {}; + try { + Object.keys(tree).forEach(function (pid) { + tree[pid].forEach(function (pidpid) { + if (!killed[pidpid]) { + killPid(pidpid, signal); + killed[pidpid] = 1; + } + }); + if (!killed[pid]) { + killPid(pid, signal); + killed[pid] = 1; + } + }); + } catch (err) { + if (callback) { + return callback(err); + } else { + throw err; + } + } + if (callback) { + return callback(); + } +} - var fs$WriteStream = fs.WriteStream - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype) - WriteStream.prototype.open = WriteStream$open - } +function killPid(pid, signal) { + try { + process.kill(parseInt(pid, 10), signal); + } + catch (err) { + if (err.code !== 'ESRCH') throw err; + } +} - fs.ReadStream = ReadStream - fs.WriteStream = WriteStream +function buildProcessTree (parentPid, tree, pidsToProcess, spawnChildProcessesList, cb) { + var ps = spawnChildProcessesList(parentPid); + var allData = ''; + ps.stdout.on('data', function (data) { + var data = data.toString('ascii'); + allData += data; + }); - function ReadStream (path, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments) - } + var onClose = function (code) { + delete pidsToProcess[parentPid]; - function ReadStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - if (that.autoClose) - that.destroy() + if (code != 0) { + // no more parent processes + if (Object.keys(pidsToProcess).length == 0) { + cb(); + } + return; + } - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - that.read() - } - }) - } + allData.match(/\d+/g).forEach(function (pid) { + pid = parseInt(pid, 10); + tree[parentPid].push(pid); + tree[pid] = []; + pidsToProcess[pid] = 1; + buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb); + }); + }; - function WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } + ps.on('close', onClose); +} - function WriteStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - that.destroy() - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - } - }) - } - function createReadStream (path, options) { - return new ReadStream(path, options) - } +/***/ }), +/* 397 */ +/***/ (function(module, exports) { - function createWriteStream (path, options) { - return new WriteStream(path, options) - } +module.exports = require("util"); - var fs$open = fs.open - fs.open = open - function open (path, flags, mode, cb) { - if (typeof mode === 'function') - cb = mode, mode = null +/***/ }), +/* 398 */ +/***/ (function(module, exports, __webpack_require__) { - return go$open(path, flags, mode, cb) +"use strict"; - function go$open (path, flags, mode, cb) { - return fs$open(path, flags, mode, function (err, fd) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$open, [path, flags, mode, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = __webpack_require__(6); +const Rx = tslib_1.__importStar(__webpack_require__(140)); +const operators_1 = __webpack_require__(241); +const SEP = /\r?\n/; +const observe_readable_1 = __webpack_require__(399); +/** + * Creates an Observable from a Readable Stream that: + * - splits data from `readable` into lines + * - completes when `readable` emits "end" + * - fails if `readable` emits "errors" + * + * @param {ReadableStream} readable + * @return {Rx.Observable} + */ +function observeLines(readable) { + const done$ = observe_readable_1.observeReadable(readable).pipe(operators_1.share()); + const scan$ = Rx.fromEvent(readable, 'data').pipe(operators_1.scan(({ buffer }, chunk) => { + buffer += chunk; + const lines = []; + while (true) { + const match = buffer.match(SEP); + if (!match || match.index === undefined) { + break; + } + lines.push(buffer.slice(0, match.index)); + buffer = buffer.slice(match.index + match[0].length); } - }) - } - } - - return fs -} - -function enqueue (elem) { - debug('ENQUEUE', elem[0].name, elem[1]) - queue.push(elem) -} - -function retry () { - var elem = queue.shift() - if (elem) { - debug('RETRY', elem[0].name, elem[1]) - elem[0].apply(null, elem[1]) - } + return { buffer, lines }; + }, { buffer: '' }), + // stop if done completes or errors + operators_1.takeUntil(done$.pipe(operators_1.materialize())), operators_1.share()); + return Rx.merge( + // use done$ to provide completion/errors + done$, + // merge in the "lines" from each step + scan$.pipe(operators_1.mergeMap(({ lines }) => lines || [])), + // inject the "unsplit" data at the end + scan$.pipe(operators_1.last(), operators_1.mergeMap(({ buffer }) => (buffer ? [buffer] : [])), + // if there were no lines, last() will error, so catch and complete + operators_1.catchError(() => Rx.empty()))); } +exports.observeLines = observeLines; /***/ }), -/* 424 */ +/* 399 */ /***/ (function(module, exports, __webpack_require__) { -var constants = __webpack_require__(25) - -var origCwd = process.cwd -var cwd = null - -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform - -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd -} -try { - process.cwd() -} catch (er) {} +"use strict"; -var chdir = process.chdir -process.chdir = function(d) { - cwd = null - chdir.call(process, d) +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = __webpack_require__(6); +const Rx = tslib_1.__importStar(__webpack_require__(140)); +const operators_1 = __webpack_require__(241); +/** + * Produces an Observable from a ReadableSteam that: + * - completes on the first "end" event + * - fails on the first "error" event + */ +function observeReadable(readable) { + return Rx.race(Rx.fromEvent(readable, 'end').pipe(operators_1.first(), operators_1.ignoreElements()), Rx.fromEvent(readable, 'error').pipe(operators_1.first(), operators_1.mergeMap((err) => Rx.throwError(err)))); } +exports.observeReadable = observeReadable; -module.exports = patch - -function patch (fs) { - // (re-)implement some things that are known busted or missing. - - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs) - } - - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) - } - - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. - - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) +/***/ }), +/* 400 */ +/***/ (function(module, exports, __webpack_require__) { - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) +"use strict"; - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +var tooling_log_1 = __webpack_require__(401); +exports.ToolingLog = tooling_log_1.ToolingLog; +var tooling_log_text_writer_1 = __webpack_require__(402); +exports.ToolingLogTextWriter = tooling_log_text_writer_1.ToolingLogTextWriter; +var log_levels_1 = __webpack_require__(403); +exports.pickLevelFromFlags = log_levels_1.pickLevelFromFlags; +exports.parseLogLevel = log_levels_1.parseLogLevel; +var tooling_log_collecting_writer_1 = __webpack_require__(404); +exports.ToolingLogCollectingWriter = tooling_log_collecting_writer_1.ToolingLogCollectingWriter; - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) +/***/ }), +/* 401 */ +/***/ (function(module, exports, __webpack_require__) { - // if lchmod/lchown do not exist, then make them no-ops - if (!fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb) - } - fs.lchmodSync = function () {} - } - if (!fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) - } - fs.lchownSync = function () {} - } +"use strict"; - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. - - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform === "win32") { - fs.rename = (function (fs$rename) { return function (from, to, cb) { - var start = Date.now() - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er) - }) - }, backoff) - if (backoff < 100) - backoff += 10; - return; - } - if (cb) cb(er) - }) - }})(fs.rename) - } - - // if read() returns EAGAIN, then just try it again. - fs.read = (function (fs$read) { return function (fd, buffer, offset, length, position, callback_) { - var callback - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0 - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - callback_.apply(this, arguments) - } +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = __webpack_require__(6); +const Rx = tslib_1.__importStar(__webpack_require__(140)); +const tooling_log_text_writer_1 = __webpack_require__(402); +class ToolingLog { + constructor(writerConfig) { + this.identWidth = 0; + this.writers = writerConfig ? [new tooling_log_text_writer_1.ToolingLogTextWriter(writerConfig)] : []; + this.written$ = new Rx.Subject(); } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - }})(fs.read) - - fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0 - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - continue - } - throw er - } + indent(delta = 0) { + this.identWidth = Math.max(this.identWidth + delta, 0); + return this.identWidth; } - }})(fs.readSync) - - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return - } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) + verbose(...args) { + this.sendToWriters('verbose', args); } - - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) - - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) + debug(...args) { + this.sendToWriters('debug', args); + } + info(...args) { + this.sendToWriters('info', args); + } + success(...args) { + this.sendToWriters('success', args); + } + warning(...args) { + this.sendToWriters('warning', args); + } + error(error) { + this.sendToWriters('error', [error]); + } + write(...args) { + this.sendToWriters('write', args); + } + getWriters() { + return this.writers.slice(0); + } + setWriters(writers) { + this.writers = [...writers]; + } + getWritten$() { + return this.written$.asObservable(); + } + sendToWriters(type, args) { + const msg = { + type, + indent: this.identWidth, + args, + }; + let written = false; + for (const writer of this.writers) { + if (writer.write(msg)) { + written = true; + } + } + if (written) { + this.written$.next(msg); } - } - return ret } - } +} +exports.ToolingLog = ToolingLog; - function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK")) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) - }) - }) - }) - } - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret - var threw = true - try { - ret = fs.futimesSync(fd, at, mt) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } +/***/ }), +/* 402 */ +/***/ (function(module, exports, __webpack_require__) { - } else { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} - } - } +"use strict"; - function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = __webpack_require__(6); +const util_1 = __webpack_require__(397); +const chalk_1 = tslib_1.__importDefault(__webpack_require__(386)); +const log_levels_1 = __webpack_require__(403); +const { magentaBright, yellow, red, blue, green, dim } = chalk_1.default; +const PREFIX_INDENT = ' '.repeat(6); +const MSG_PREFIXES = { + verbose: ` ${magentaBright('sill')} `, + debug: ` ${dim('debg')} `, + info: ` ${blue('info')} `, + success: ` ${green('succ')} `, + warning: ` ${yellow('warn')} `, + error: `${red('ERROR')} `, +}; +const has = (obj, key) => obj.hasOwnProperty(key); +function shouldWriteType(level, type) { + if (type === 'write') { + return level.name !== 'silent'; } - } - - function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er - } + return Boolean(level.flags[type === 'success' ? 'info' : type]); +} +function stringifyError(error) { + if (typeof error !== 'string' && !(error instanceof Error)) { + error = new Error(`"${error}" thrown`); } - } - - - function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) + if (typeof error === 'string') { + return error; } - } - - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er - } + return error.stack || error.message || error; +} +class ToolingLogTextWriter { + constructor(config) { + this.level = log_levels_1.parseLogLevel(config.level); + this.writeTo = config.writeTo; + if (!this.writeTo || typeof this.writeTo.write !== 'function') { + throw new Error('ToolingLogTextWriter requires the `writeTo` option be set to a stream (like process.stdout)'); + } } - } - - - function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, cb) { - return orig.call(fs, target, function (er, stats) { - if (!stats) return cb.apply(this, arguments) - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - if (cb) cb.apply(this, arguments) - }) + write(msg) { + if (!shouldWriteType(this.level, msg.type)) { + return false; + } + const prefix = has(MSG_PREFIXES, msg.type) ? MSG_PREFIXES[msg.type] : ''; + ToolingLogTextWriter.write(this.writeTo, prefix, msg); + return true; } - } - - function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target) { - var stats = orig.call(fs, target) - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - return stats; + static write(writeTo, prefix, msg) { + const txt = msg.type === 'error' + ? stringifyError(msg.args[0]) + : util_1.format(msg.args[0], ...msg.args.slice(1)); + (prefix + txt).split('\n').forEach((line, i) => { + let lineIndent = ''; + if (msg.indent > 0) { + // if we are indenting write some spaces followed by a symbol + lineIndent += ' '.repeat(msg.indent - 1); + lineIndent += line.startsWith('-') ? '└' : '│'; + } + if (line && prefix && i > 0) { + // apply additional indentation to lines after + // the first if this message gets a prefix + lineIndent += PREFIX_INDENT; + } + writeTo.write(`${lineIndent}${line}\n`); + }); } - } +} +exports.ToolingLogTextWriter = ToolingLogTextWriter; - // ENOSYS means that the fs doesn't support the op. Just ignore - // that, because it doesn't matter. - // - // if there's no getuid, or if getuid() is something other - // than 0, and the error is EINVAL or EPERM, then just ignore - // it. - // - // This specific case is a silent failure in cp, install, tar, - // and most other unix tools that manage permissions. - // - // When running as root, or if other types of errors are - // encountered, then it's strict. - function chownErOk (er) { - if (!er) - return true - if (er.code === "ENOSYS") - return true +/***/ }), +/* 403 */ +/***/ (function(module, exports, __webpack_require__) { - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true - } +"use strict"; - return false - } +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const LEVELS = ['silent', 'error', 'warning', 'info', 'debug', 'verbose']; +function pickLevelFromFlags(flags, options = {}) { + if (flags.verbose) + return 'verbose'; + if (flags.debug) + return 'debug'; + if (flags.quiet) + return 'error'; + if (flags.silent) + return 'silent'; + return options.default || 'info'; +} +exports.pickLevelFromFlags = pickLevelFromFlags; +function parseLogLevel(name) { + const i = LEVELS.indexOf(name); + if (i === -1) { + const msg = `Invalid log level "${name}" ` + `(expected one of ${LEVELS.join(',')})`; + throw new Error(msg); + } + const flags = {}; + LEVELS.forEach((level, levelI) => { + flags[level] = levelI <= i; + }); + return { + name, + flags: flags, + }; } +exports.parseLogLevel = parseLogLevel; /***/ }), -/* 425 */ +/* 404 */ /***/ (function(module, exports, __webpack_require__) { -var Stream = __webpack_require__(27).Stream +"use strict"; -module.exports = legacy +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const tooling_log_text_writer_1 = __webpack_require__(402); +class ToolingLogCollectingWriter extends tooling_log_text_writer_1.ToolingLogTextWriter { + constructor(level = 'verbose') { + super({ + level, + writeTo: { + write: (msg) => { + // trim trailing new line + this.messages.push(msg.slice(0, -1)); + }, + }, + }); + this.messages = []; + } +} +exports.ToolingLogCollectingWriter = ToolingLogCollectingWriter; -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream - } - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); +/***/ }), +/* 405 */ +/***/ (function(module, exports, __webpack_require__) { - Stream.call(this); +"use strict"; - var self = this; +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +var absolute_path_serializer_1 = __webpack_require__(406); +exports.createAbsolutePathSerializer = absolute_path_serializer_1.createAbsolutePathSerializer; - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; +/***/ }), +/* 406 */ +/***/ (function(module, exports, __webpack_require__) { - options = options || {}; +"use strict"; - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } - - if (this.encoding) this.setEncoding(this.encoding); +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const repo_root_1 = __webpack_require__(407); +function createAbsolutePathSerializer(rootPath = repo_root_1.REPO_ROOT) { + return { + print: (value) => value.replace(rootPath, '').replace(/\\/g, '/'), + test: (value) => typeof value === 'string' && value.startsWith(rootPath), + }; +} +exports.createAbsolutePathSerializer = createAbsolutePathSerializer; - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); - } - if (this.start > this.end) { - throw new Error('start must be <= end'); - } +/***/ }), +/* 407 */ +/***/ (function(module, exports, __webpack_require__) { - this.pos = this.start; - } +"use strict"; - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = __webpack_require__(6); +const path_1 = tslib_1.__importDefault(__webpack_require__(4)); +const fs_1 = tslib_1.__importDefault(__webpack_require__(349)); +const load_json_file_1 = tslib_1.__importDefault(__webpack_require__(408)); +const isKibanaDir = (dir) => { + try { + const path = path_1.default.resolve(dir, 'package.json'); + const json = load_json_file_1.default.sync(path); + if (json && typeof json === 'object' && 'name' in json && json.name === 'kibana') { + return true; + } } - - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; - } - - self.fd = fd; - self.emit('open', fd); - self._read(); - }) - } - - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); - - Stream.call(this); - - this.path = path; - this.fd = null; - this.writable = true; - - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; - - options = options || {}; - - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; + catch (error) { + if (error && error.code === 'ENOENT') { + return false; + } + throw error; } - - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } - - this.pos = this.start; +}; +// search for the kibana directory, since this file is moved around it might +// not be where we think but should always be a relatively close parent +// of this directory +const startDir = fs_1.default.realpathSync(__dirname); +const { root: rootDir } = path_1.default.parse(startDir); +let cursor = startDir; +while (true) { + if (isKibanaDir(cursor)) { + break; } - - this.busy = false; - this._queue = []; - - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); + const parent = path_1.default.dirname(cursor); + if (parent === rootDir) { + throw new Error(`unable to find kibana directory from ${startDir}`); } - } + cursor = parent; } +exports.REPO_ROOT = cursor; /***/ }), -/* 426 */ +/* 408 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +const path = __webpack_require__(4); +const {promisify} = __webpack_require__(397); +const fs = __webpack_require__(409); +const stripBom = __webpack_require__(414); +const parseJson = __webpack_require__(415); -module.exports = clone - -function clone (obj) { - if (obj === null || typeof obj !== 'object') - return obj +const parse = (data, filePath, options = {}) => { + data = stripBom(data); - if (obj instanceof Object) - var copy = { __proto__: obj.__proto__ } - else - var copy = Object.create(null) + if (typeof options.beforeParse === 'function') { + data = options.beforeParse(data); + } - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) - }) + return parseJson(data, options.reviver, path.relative(process.cwd(), filePath)); +}; - return copy -} +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); /***/ }), -/* 427 */ +/* 409 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +var fs = __webpack_require__(349) +var polyfills = __webpack_require__(410) +var legacy = __webpack_require__(412) +var clone = __webpack_require__(413) +var queue = [] -module.exports = string => { - if (typeof string !== 'string') { - throw new TypeError(`Expected a string, got ${typeof string}`); - } +var util = __webpack_require__(397) - // 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); - } +function noop () {} - return string; -}; +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) + } +if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(queue) + __webpack_require__(371).equal(queue.length, 0) + }) +} -/***/ }), -/* 428 */ -/***/ (function(module, exports, __webpack_require__) { +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; +} -"use strict"; +// Always patch fs.close/closeSync, because we want to +// retry() whenever a close happens *anywhere* in the program. +// This is essential when multiple graceful-fs instances are +// in play at the same time. +module.exports.close = (function (fs$close) { return function (fd, cb) { + return fs$close.call(fs, fd, function (err) { + if (!err) + retry() -const errorEx = __webpack_require__(429); -const fallback = __webpack_require__(431); -const {default: LinesAndColumns} = __webpack_require__(432); -const {codeFrameColumns} = __webpack_require__(433); + if (typeof cb === 'function') + cb.apply(this, arguments) + }) +}})(fs.close) -const JSONError = errorEx('JSONError', { - fileName: errorEx.append('in %s'), - codeFrame: errorEx.append('\n\n%s\n') -}); +module.exports.closeSync = (function (fs$closeSync) { return function (fd) { + // Note that graceful-fs also retries when fs.closeSync() fails. + // Looks like a bug to me, although it's probably a harmless one. + var rval = fs$closeSync.apply(fs, arguments) + retry() + return rval +}})(fs.closeSync) -module.exports = (string, reviver, filename) => { - if (typeof reviver === 'string') { - filename = reviver; - reviver = null; - } +// Only patch fs once, otherwise we'll run into a memory leak if +// graceful-fs is loaded multiple times, such as in test environments that +// reset the loaded modules between tests. +// We look for the string `graceful-fs` from the comment above. This +// way we are not adding any extra properties and it will detect if older +// versions of graceful-fs are installed. +if (!/\bgraceful-fs\b/.test(fs.closeSync.toString())) { + fs.closeSync = module.exports.closeSync; + fs.close = module.exports.close; +} - try { - try { - return JSON.parse(string, reviver); - } catch (error) { - fallback(string, reviver); - throw error; - } - } catch (error) { - error.message = error.message.replace(/\n/g, ''); - const indexMatch = error.message.match(/in JSON at position (\d+) while parsing near/); +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch + fs.FileReadStream = ReadStream; // Legacy name. + fs.FileWriteStream = WriteStream; // Legacy name. + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null - const jsonError = new JSONError(error); - if (filename) { - jsonError.fileName = filename; - } + return go$readFile(path, options, cb) - if (indexMatch && indexMatch.length > 0) { - const lines = new LinesAndColumns(string); - const index = Number(indexMatch[1]); - const location = lines.locationForIndex(index); + function go$readFile (path, options, cb) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } + } - const codeFrame = codeFrameColumns( - string, - {start: {line: location.line + 1, column: location.column + 1}}, - {highlightCode: true} - ); + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null - jsonError.codeFrame = codeFrame; - } + return go$writeFile(path, data, options, cb) - throw jsonError; - } -}; + function go$writeFile (path, data, options, cb) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } + } + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null -/***/ }), -/* 429 */ -/***/ (function(module, exports, __webpack_require__) { + return go$appendFile(path, data, options, cb) -"use strict"; + function go$appendFile (path, data, options, cb) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } + } + var fs$readdir = fs.readdir + fs.readdir = readdir + function readdir (path, options, cb) { + var args = [path] + if (typeof options !== 'function') { + args.push(options) + } else { + cb = options + } + args.push(go$readdir$cb) -var util = __webpack_require__(29); -var isArrayish = __webpack_require__(430); + return go$readdir(args) -var errorEx = function errorEx(name, properties) { - if (!name || name.constructor !== String) { - properties = name || {}; - name = Error.name; - } + function go$readdir$cb (err, files) { + if (files && files.sort) + files.sort() - var errorExError = function ErrorEXError(message) { - if (!this) { - return new ErrorEXError(message); - } + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readdir, [args]]) - message = message instanceof Error - ? message.message - : (message || this.message); + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + } + } - Error.call(this, message); - Error.captureStackTrace(this, errorExError); + function go$readdir (args) { + return fs$readdir.apply(fs, args) + } - this.name = name; + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream + } - Object.defineProperty(this, 'message', { - configurable: true, - enumerable: false, - get: function () { - var newMessage = message.split(/\r?\n/g); + var fs$ReadStream = fs.ReadStream + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open + } - for (var key in properties) { - if (!properties.hasOwnProperty(key)) { - continue; - } + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } - var modifier = properties[key]; + fs.ReadStream = ReadStream + fs.WriteStream = WriteStream - if ('message' in modifier) { - newMessage = modifier.message(this[key], newMessage) || newMessage; - if (!isArrayish(newMessage)) { - newMessage = [newMessage]; - } - } - } + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + } - return newMessage.join('\n'); - }, - set: function (v) { - message = v; - } - }); + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() - var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); - var stackGetter = stackDescriptor.get; - var stackValue = stackDescriptor.value; - delete stackDescriptor.value; - delete stackDescriptor.writable; + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + that.read() + } + }) + } - stackDescriptor.get = function () { - var stack = (stackGetter) - ? stackGetter.call(this).split(/\r?\n+/g) - : stackValue.split(/\r?\n+/g); + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } - // starting in Node 7, the stack builder caches the message. - // just replace it. - stack[0] = this.name + ': ' + this.message; + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + } + }) + } - var lineCount = 1; - for (var key in properties) { - if (!properties.hasOwnProperty(key)) { - continue; - } + function createReadStream (path, options) { + return new ReadStream(path, options) + } - var modifier = properties[key]; + function createWriteStream (path, options) { + return new WriteStream(path, options) + } - if ('line' in modifier) { - var line = modifier.line(this[key]); - if (line) { - stack.splice(lineCount++, 0, ' ' + line); - } - } + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null - if ('stack' in modifier) { - modifier.stack(this[key], stack); - } - } + return go$open(path, flags, mode, cb) - return stack.join('\n'); - }; - - Object.defineProperty(this, 'stack', stackDescriptor); - }; - - if (Object.setPrototypeOf) { - Object.setPrototypeOf(errorExError.prototype, Error.prototype); - Object.setPrototypeOf(errorExError, Error); - } else { - util.inherits(errorExError, Error); - } - - return errorExError; -}; - -errorEx.append = function (str, def) { - return { - message: function (v, message) { - v = v || def; - - if (v) { - message[0] += ' ' + str.replace('%s', v.toString()); - } - - return message; - } - }; -}; - -errorEx.line = function (str, def) { - return { - line: function (v) { - v = v || def; + function go$open (path, flags, mode, cb) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } + } - if (v) { - return str.replace('%s', v.toString()); - } + return fs +} - return null; - } - }; -}; +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + queue.push(elem) +} -module.exports = errorEx; +function retry () { + var elem = queue.shift() + if (elem) { + debug('RETRY', elem[0].name, elem[1]) + elem[0].apply(null, elem[1]) + } +} /***/ }), -/* 430 */ +/* 410 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - - -module.exports = function isArrayish(obj) { - if (!obj) { - return false; - } - - return obj instanceof Array || Array.isArray(obj) || - (obj.length >= 0 && obj.splice instanceof Function); -}; - +var constants = __webpack_require__(411) -/***/ }), -/* 431 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +var origCwd = process.cwd +var cwd = null +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform -module.exports = parseJson -function parseJson (txt, reviver, context) { - context = context || 20 - try { - return JSON.parse(txt, reviver) - } catch (e) { - const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i) - const errIdx = syntaxErr - ? +syntaxErr[1] - : e.message.match(/^Unexpected end of JSON.*/i) - ? txt.length - 1 - : null - if (errIdx != null) { - const start = errIdx <= context - ? 0 - : errIdx - context - const end = errIdx + context >= txt.length - ? txt.length - : errIdx + context - e.message += ` while parsing near '${ - start === 0 ? '' : '...' - }${txt.slice(start, end)}${ - end === txt.length ? '' : '...' - }'` - } else { - e.message += ` while parsing '${txt.slice(0, context * 2)}'` - } - throw e - } +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd } +try { + process.cwd() +} catch (er) {} +var chdir = process.chdir +process.chdir = function(d) { + cwd = null + chdir.call(process, d) +} -/***/ }), -/* 432 */ -/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -var LF = '\n'; -var CR = '\r'; -var LinesAndColumns = (function () { - function LinesAndColumns(string) { - this.string = string; - var offsets = [0]; - for (var offset = 0; offset < string.length;) { - switch (string[offset]) { - case LF: - offset += LF.length; - offsets.push(offset); - break; - case CR: - offset += CR.length; - if (string[offset] === LF) { - offset += LF.length; - } - offsets.push(offset); - break; - default: - offset++; - break; - } - } - this.offsets = offsets; - } - LinesAndColumns.prototype.locationForIndex = function (index) { - if (index < 0 || index > this.string.length) { - return null; - } - var line = 0; - var offsets = this.offsets; - while (offsets[line + 1] <= index) { - line++; - } - var column = index - offsets[line]; - return { line: line, column: column }; - }; - LinesAndColumns.prototype.indexForLocation = function (location) { - var line = location.line, column = location.column; - if (line < 0 || line >= this.offsets.length) { - return null; - } - if (column < 0 || column > this.lengthOfLine(line)) { - return null; - } - return this.offsets[line] + column; - }; - LinesAndColumns.prototype.lengthOfLine = function (line) { - var offset = this.offsets[line]; - var nextOffset = line === this.offsets.length - 1 ? this.string.length : this.offsets[line + 1]; - return nextOffset - offset; - }; - return LinesAndColumns; -}()); -/* harmony default export */ __webpack_exports__["default"] = (LinesAndColumns); - - -/***/ }), -/* 433 */ -/***/ (function(module, exports, __webpack_require__) { +module.exports = patch -"use strict"; +function patch (fs) { + // (re-)implement some things that are known busted or missing. + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.codeFrameColumns = codeFrameColumns; -exports.default = _default; + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } -var _highlight = _interopRequireWildcard(__webpack_require__(434)); + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. -function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) -let deprecationWarningShown = false; + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) -function getDefs(chalk) { - return { - gutter: chalk.grey, - marker: chalk.red.bold, - message: chalk.red.bold - }; -} + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) -const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) -function getMarkerLines(loc, source, opts) { - const startLoc = Object.assign({ - column: 0, - line: -1 - }, loc.start); - const endLoc = Object.assign({}, startLoc, {}, loc.end); - const { - linesAbove = 2, - linesBelow = 3 - } = opts || {}; - const startLine = startLoc.line; - const startColumn = startLoc.column; - const endLine = endLoc.line; - const endColumn = endLoc.column; - let start = Math.max(startLine - (linesAbove + 1), 0); - let end = Math.min(source.length, endLine + linesBelow); + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) - if (startLine === -1) { - start = 0; + // if lchmod/lchown do not exist, then make them no-ops + if (!fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) + } + fs.lchmodSync = function () {} } - - if (endLine === -1) { - end = source.length; + if (!fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) + } + fs.lchownSync = function () {} } - const lineDiff = endLine - startLine; - const markerLines = {}; + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. - if (lineDiff) { - for (let i = 0; i <= lineDiff; i++) { - const lineNumber = i + startLine; + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = (function (fs$rename) { return function (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + }})(fs.rename) + } - if (!startColumn) { - markerLines[lineNumber] = true; - } else if (i === 0) { - const sourceLength = source[lineNumber - 1].length; - markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]; - } else if (i === lineDiff) { - markerLines[lineNumber] = [0, endColumn]; - } else { - const sourceLength = source[lineNumber - i].length; - markerLines[lineNumber] = [0, sourceLength]; + // if read() returns EAGAIN, then just try it again. + fs.read = (function (fs$read) { return function (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) } } - } else { - if (startColumn === endColumn) { - if (startColumn) { - markerLines[startLine] = [startColumn, 0]; - } else { - markerLines[startLine] = true; + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + }})(fs.read) + + fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er } - } else { - markerLines[startLine] = [startColumn, endColumn - startColumn]; } - } - - return { - start, - end, - markerLines - }; -} - -function codeFrameColumns(rawLines, loc, opts = {}) { - const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts); - const chalk = (0, _highlight.getChalk)(opts); - const defs = getDefs(chalk); + }})(fs.readSync) - const maybeHighlight = (chalkFn, string) => { - return highlighted ? chalkFn(string) : string; - }; + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } - const lines = rawLines.split(NEWLINE); - const { - start, - end, - markerLines - } = getMarkerLines(loc, lines, opts); - const hasColumns = loc.start && typeof loc.start.column === "number"; - const numberMaxWidth = String(end).length; - const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines; - let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => { - const number = start + 1 + index; - const paddedNumber = ` ${number}`.slice(-numberMaxWidth); - const gutter = ` ${paddedNumber} | `; - const hasMarker = markerLines[number]; - const lastMarkerLine = !markerLines[number + 1]; + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) - if (hasMarker) { - let markerLine = ""; + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + } - if (Array.isArray(hasMarker)) { - const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); - const numberOfMarkers = hasMarker[1] || 1; - markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK")) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } - if (lastMarkerLine && opts.message) { - markerLine += " " + maybeHighlight(defs.message, opts.message); + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } } + return ret } - return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); } else { - return ` ${maybeHighlight(defs.gutter, gutter)}${line}`; + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} } - }).join("\n"); - - if (opts.message && !hasColumns) { - frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`; } - if (highlighted) { - return chalk.reset(frame); - } else { - return frame; + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } } -} - -function _default(rawLines, lineNumber, colNumber, opts = {}) { - if (!deprecationWarningShown) { - deprecationWarningShown = true; - const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; - if (process.emitWarning) { - process.emitWarning(message, "DeprecationWarning"); - } else { - const deprecationError = new Error(message); - deprecationError.name = "DeprecationWarning"; - console.warn(new Error(message)); + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } } } - colNumber = Math.max(colNumber, 0); - const location = { - start: { - column: colNumber, - line: lineNumber - } - }; - return codeFrameColumns(rawLines, location, opts); -} - -/***/ }), -/* 434 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.shouldHighlight = shouldHighlight; -exports.getChalk = getChalk; -exports.default = highlight; - -var _jsTokens = _interopRequireWildcard(__webpack_require__(435)); - -var _helperValidatorIdentifier = __webpack_require__(436); - -var _chalk = _interopRequireDefault(__webpack_require__(439)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } - -function getDefs(chalk) { - return { - keyword: chalk.cyan, - capitalized: chalk.yellow, - jsx_tag: chalk.yellow, - punctuator: chalk.yellow, - number: chalk.magenta, - string: chalk.green, - regex: chalk.magenta, - comment: chalk.grey, - invalid: chalk.white.bgRed.bold - }; -} - -const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; -const JSX_TAG = /^[a-z][\w-]*$/i; -const BRACKET = /^[()[\]{}]$/; - -function getTokenType(match) { - const [offset, text] = match.slice(-2); - const token = (0, _jsTokens.matchToToken)(match); - - if (token.type === "name") { - if ((0, _helperValidatorIdentifier.isKeyword)(token.value) || (0, _helperValidatorIdentifier.isReservedWord)(token.value)) { - return "keyword"; - } - if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == " colorize(str)).join("\n"); - } else { - return args[0]; + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true } - }); -} - -function shouldHighlight(options) { - return _chalk.default.supportsColor || options.forceColor; -} - -function getChalk(options) { - let chalk = _chalk.default; - if (options.forceColor) { - chalk = new _chalk.default.constructor({ - enabled: true, - level: 1 - }); + return false } - - return chalk; } -function highlight(code, options = {}) { - if (shouldHighlight(options)) { - const chalk = getChalk(options); - const defs = getDefs(chalk); - return highlightTokens(defs, code); - } else { - return code; - } -} /***/ }), -/* 435 */ +/* 411 */ /***/ (function(module, exports) { -// Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell -// License: MIT. (See LICENSE.) - -Object.defineProperty(exports, "__esModule", { - value: true -}) - -// This regex comes from regex.coffee, and is inserted here by generate-index.js -// (run `npm run build`). -exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g - -exports.matchToToken = function(match) { - var token = {type: "invalid", value: match[0], closed: undefined} - if (match[ 1]) token.type = "string" , token.closed = !!(match[3] || match[4]) - else if (match[ 5]) token.type = "comment" - else if (match[ 6]) token.type = "comment", token.closed = !!match[7] - else if (match[ 8]) token.type = "regex" - else if (match[ 9]) token.type = "number" - else if (match[10]) token.type = "name" - else if (match[11]) token.type = "punctuator" - else if (match[12]) token.type = "whitespace" - return token -} - +module.exports = require("constants"); /***/ }), -/* 436 */ +/* 412 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +var Stream = __webpack_require__(382).Stream +module.exports = legacy -Object.defineProperty(exports, "__esModule", { - value: true -}); -Object.defineProperty(exports, "isIdentifierName", { - enumerable: true, - get: function () { - return _identifier.isIdentifierName; - } -}); -Object.defineProperty(exports, "isIdentifierChar", { - enumerable: true, - get: function () { - return _identifier.isIdentifierChar; - } -}); -Object.defineProperty(exports, "isIdentifierStart", { - enumerable: true, - get: function () { - return _identifier.isIdentifierStart; - } -}); -Object.defineProperty(exports, "isReservedWord", { - enumerable: true, - get: function () { - return _keyword.isReservedWord; - } -}); -Object.defineProperty(exports, "isStrictBindOnlyReservedWord", { - enumerable: true, - get: function () { - return _keyword.isStrictBindOnlyReservedWord; - } -}); -Object.defineProperty(exports, "isStrictBindReservedWord", { - enumerable: true, - get: function () { - return _keyword.isStrictBindReservedWord; - } -}); -Object.defineProperty(exports, "isStrictReservedWord", { - enumerable: true, - get: function () { - return _keyword.isStrictReservedWord; - } -}); -Object.defineProperty(exports, "isKeyword", { - enumerable: true, - get: function () { - return _keyword.isKeyword; +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream } -}); -var _identifier = __webpack_require__(437); + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); -var _keyword = __webpack_require__(438); + Stream.call(this); -/***/ }), -/* 437 */ -/***/ (function(module, exports, __webpack_require__) { + var self = this; -"use strict"; + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isIdentifierStart = isIdentifierStart; -exports.isIdentifierChar = isIdentifierChar; -exports.isIdentifierName = isIdentifierName; -let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; -let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; -const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); -const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); -nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; -const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938]; -const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; + options = options || {}; -function isInAstralSet(code, set) { - let pos = 0x10000; + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } - for (let i = 0, length = set.length; i < length; i += 2) { - pos += set[i]; - if (pos > code) return false; - pos += set[i + 1]; - if (pos >= code) return true; - } + if (this.encoding) this.setEncoding(this.encoding); - return false; -} + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); + } -function isIdentifierStart(code) { - if (code < 65) return code === 36; - if (code <= 90) return true; - if (code < 97) return code === 95; - if (code <= 122) return true; + if (this.start > this.end) { + throw new Error('start must be <= end'); + } - if (code <= 0xffff) { - return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); - } + this.pos = this.start; + } - return isInAstralSet(code, astralIdentifierStartCodes); -} + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } -function isIdentifierChar(code) { - if (code < 48) return code === 36; - if (code < 58) return true; - if (code < 65) return false; - if (code <= 90) return true; - if (code < 97) return code === 95; - if (code <= 122) return true; + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } - if (code <= 0xffff) { - return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); + self.fd = fd; + self.emit('open', fd); + self._read(); + }) } - return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); -} + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); -function isIdentifierName(name) { - let isFirst = true; + Stream.call(this); - for (let _i = 0, _Array$from = Array.from(name); _i < _Array$from.length; _i++) { - const char = _Array$from[_i]; - const cp = char.codePointAt(0); + this.path = path; + this.fd = null; + this.writable = true; - if (isFirst) { - if (!isIdentifierStart(cp)) { - return false; + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.start < 0) { + throw new Error('start must be >= zero'); } - isFirst = false; - } else if (!isIdentifierChar(cp)) { - return false; + this.pos = this.start; } - } - return true; + this.busy = false; + this._queue = []; + + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); + } + } } + /***/ }), -/* 438 */ +/* 413 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isReservedWord = isReservedWord; -exports.isStrictReservedWord = isStrictReservedWord; -exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord; -exports.isStrictBindReservedWord = isStrictBindReservedWord; -exports.isKeyword = isKeyword; -const reservedWords = { - keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], - strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], - strictBind: ["eval", "arguments"] -}; -const keywords = new Set(reservedWords.keyword); -const reservedWordsStrictSet = new Set(reservedWords.strict); -const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); +module.exports = clone -function isReservedWord(word, inModule) { - return inModule && word === "await" || word === "enum"; -} +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj -function isStrictReservedWord(word, inModule) { - return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); -} + if (obj instanceof Object) + var copy = { __proto__: obj.__proto__ } + else + var copy = Object.create(null) -function isStrictBindOnlyReservedWord(word) { - return reservedWordsStrictBindSet.has(word); -} + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) -function isStrictBindReservedWord(word, inModule) { - return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); + return copy } -function isKeyword(word) { - return keywords.has(word); -} /***/ }), -/* 439 */ +/* 414 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const escapeStringRegexp = __webpack_require__(3); -const ansiStyles = __webpack_require__(440); -const stdoutColor = __webpack_require__(441).stdout; -const template = __webpack_require__(442); +module.exports = string => { + if (typeof string !== 'string') { + throw new TypeError(`Expected a string, got ${typeof string}`); + } -const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); + // 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); + } -// `supportsColor.level` → `ansiStyles.color[name]` mapping -const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; + return string; +}; -// `color-convert` models to exclude from the Chalk API due to conflicts and such -const skipModels = new Set(['gray']); -const styles = Object.create(null); +/***/ }), +/* 415 */ +/***/ (function(module, exports, __webpack_require__) { -function applyOptions(obj, options) { - options = options || {}; +"use strict"; - // Detect level if not set manually - const scLevel = stdoutColor ? stdoutColor.level : 0; - obj.level = options.level === undefined ? scLevel : options.level; - obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; -} +const errorEx = __webpack_require__(416); +const fallback = __webpack_require__(418); +const {default: LinesAndColumns} = __webpack_require__(419); +const {codeFrameColumns} = __webpack_require__(420); -function Chalk(options) { - // We check for this.template here since calling `chalk.constructor()` - // by itself will have a `this` of a previously constructed chalk object - if (!this || !(this instanceof Chalk) || this.template) { - const chalk = {}; - applyOptions(chalk, options); +const JSONError = errorEx('JSONError', { + fileName: errorEx.append('in %s'), + codeFrame: errorEx.append('\n\n%s\n') +}); - chalk.template = function () { - const args = [].slice.call(arguments); - return chalkTag.apply(null, [chalk.template].concat(args)); - }; +module.exports = (string, reviver, filename) => { + if (typeof reviver === 'string') { + filename = reviver; + reviver = null; + } - Object.setPrototypeOf(chalk, Chalk.prototype); - Object.setPrototypeOf(chalk.template, chalk); + try { + try { + return JSON.parse(string, reviver); + } catch (error) { + fallback(string, reviver); + throw error; + } + } catch (error) { + error.message = error.message.replace(/\n/g, ''); + const indexMatch = error.message.match(/in JSON at position (\d+) while parsing near/); - chalk.template.constructor = Chalk; + const jsonError = new JSONError(error); + if (filename) { + jsonError.fileName = filename; + } - return chalk.template; - } + if (indexMatch && indexMatch.length > 0) { + const lines = new LinesAndColumns(string); + const index = Number(indexMatch[1]); + const location = lines.locationForIndex(index); - applyOptions(this, options); -} - -// Use bright blue on Windows as the normal blue color is illegible -if (isSimpleWindowsTerm) { - ansiStyles.blue.open = '\u001B[94m'; -} - -for (const key of Object.keys(ansiStyles)) { - ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + const codeFrame = codeFrameColumns( + string, + {start: {line: location.line + 1, column: location.column + 1}}, + {highlightCode: true} + ); - styles[key] = { - get() { - const codes = ansiStyles[key]; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + jsonError.codeFrame = codeFrame; } - }; -} -styles.visible = { - get() { - return build.call(this, this._styles || [], true, 'visible'); + throw jsonError; } }; -ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); -for (const model of Object.keys(ansiStyles.color.ansi)) { - if (skipModels.has(model)) { - continue; - } - styles[model] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles.color.close, - closeRe: ansiStyles.color.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; -} +/***/ }), +/* 416 */ +/***/ (function(module, exports, __webpack_require__) { -ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); -for (const model of Object.keys(ansiStyles.bgColor.ansi)) { - if (skipModels.has(model)) { - continue; +"use strict"; + + +var util = __webpack_require__(397); +var isArrayish = __webpack_require__(417); + +var errorEx = function errorEx(name, properties) { + if (!name || name.constructor !== String) { + properties = name || {}; + name = Error.name; } - const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); - styles[bgModel] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles.bgColor.close, - closeRe: ansiStyles.bgColor.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; + var errorExError = function ErrorEXError(message) { + if (!this) { + return new ErrorEXError(message); } - }; -} -const proto = Object.defineProperties(() => {}, styles); + message = message instanceof Error + ? message.message + : (message || this.message); -function build(_styles, _empty, key) { - const builder = function () { - return applyStyle.apply(builder, arguments); - }; + Error.call(this, message); + Error.captureStackTrace(this, errorExError); - builder._styles = _styles; - builder._empty = _empty; + this.name = name; - const self = this; + Object.defineProperty(this, 'message', { + configurable: true, + enumerable: false, + get: function () { + var newMessage = message.split(/\r?\n/g); - Object.defineProperty(builder, 'level', { - enumerable: true, - get() { - return self.level; - }, - set(level) { - self.level = level; - } - }); + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } - Object.defineProperty(builder, 'enabled', { - enumerable: true, - get() { - return self.enabled; - }, - set(enabled) { - self.enabled = enabled; - } - }); + var modifier = properties[key]; - // See below for fix regarding invisible grey/dim combination on Windows - builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; + if ('message' in modifier) { + newMessage = modifier.message(this[key], newMessage) || newMessage; + if (!isArrayish(newMessage)) { + newMessage = [newMessage]; + } + } + } - // `__proto__` is used because we must return a function, but there is - // no way to create a function with a different prototype - builder.__proto__ = proto; // eslint-disable-line no-proto + return newMessage.join('\n'); + }, + set: function (v) { + message = v; + } + }); - return builder; -} + var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); + var stackGetter = stackDescriptor.get; + var stackValue = stackDescriptor.value; + delete stackDescriptor.value; + delete stackDescriptor.writable; -function applyStyle() { - // Support varags, but simply cast to string in case there's only one arg - const args = arguments; - const argsLen = args.length; - let str = String(arguments[0]); + stackDescriptor.get = function () { + var stack = (stackGetter) + ? stackGetter.call(this).split(/\r?\n+/g) + : stackValue.split(/\r?\n+/g); - if (argsLen === 0) { - return ''; - } + // starting in Node 7, the stack builder caches the message. + // just replace it. + stack[0] = this.name + ': ' + this.message; - if (argsLen > 1) { - // Don't slice `arguments`, it prevents V8 optimizations - for (let a = 1; a < argsLen; a++) { - str += ' ' + args[a]; - } - } + var lineCount = 1; + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } - if (!this.enabled || this.level <= 0 || !str) { - return this._empty ? '' : str; - } + var modifier = properties[key]; - // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, - // see https://github.com/chalk/chalk/issues/58 - // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. - const originalDim = ansiStyles.dim.open; - if (isSimpleWindowsTerm && this.hasGrey) { - ansiStyles.dim.open = ''; - } + if ('line' in modifier) { + var line = modifier.line(this[key]); + if (line) { + stack.splice(lineCount++, 0, ' ' + line); + } + } - for (const code of this._styles.slice().reverse()) { - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - str = code.open + str.replace(code.closeRe, code.open) + code.close; + if ('stack' in modifier) { + modifier.stack(this[key], stack); + } + } - // Close the styling before a linebreak and reopen - // after next line to fix a bleed issue on macOS - // https://github.com/chalk/chalk/pull/92 - str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); + return stack.join('\n'); + }; + + Object.defineProperty(this, 'stack', stackDescriptor); + }; + + if (Object.setPrototypeOf) { + Object.setPrototypeOf(errorExError.prototype, Error.prototype); + Object.setPrototypeOf(errorExError, Error); + } else { + util.inherits(errorExError, Error); } - // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue - ansiStyles.dim.open = originalDim; + return errorExError; +}; - return str; -} +errorEx.append = function (str, def) { + return { + message: function (v, message) { + v = v || def; -function chalkTag(chalk, strings) { - if (!Array.isArray(strings)) { - // If chalk() was called by itself or with a string, - // return the string itself as a string. - return [].slice.call(arguments, 1).join(' '); - } + if (v) { + message[0] += ' ' + str.replace('%s', v.toString()); + } - const args = [].slice.call(arguments, 2); - const parts = [strings.raw[0]]; + return message; + } + }; +}; - for (let i = 1; i < strings.length; i++) { - parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); - parts.push(String(strings.raw[i])); - } +errorEx.line = function (str, def) { + return { + line: function (v) { + v = v || def; - return template(chalk, parts.join('')); -} + if (v) { + return str.replace('%s', v.toString()); + } -Object.defineProperties(Chalk.prototype, styles); + return null; + } + }; +}; -module.exports = Chalk(); // eslint-disable-line new-cap -module.exports.supportsColor = stdoutColor; -module.exports.default = module.exports; // For TypeScript +module.exports = errorEx; /***/ }), -/* 440 */ +/* 417 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* WEBPACK VAR INJECTION */(function(module) { -const colorConvert = __webpack_require__(6); -const wrapAnsi16 = (fn, offset) => function () { - const code = fn.apply(colorConvert, arguments); - return `\u001B[${code + offset}m`; -}; -const wrapAnsi256 = (fn, offset) => function () { - const code = fn.apply(colorConvert, arguments); - return `\u001B[${38 + offset};5;${code}m`; -}; +module.exports = function isArrayish(obj) { + if (!obj) { + return false; + } -const wrapAnsi16m = (fn, offset) => function () { - const rgb = fn.apply(colorConvert, arguments); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; + return obj instanceof Array || Array.isArray(obj) || + (obj.length >= 0 && obj.splice instanceof Function); }; -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39], - - // Bright color - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; +/***/ }), +/* 418 */ +/***/ (function(module, exports, __webpack_require__) { - // Fix humans - styles.color.grey = styles.color.gray; +"use strict"; - for (const groupName of Object.keys(styles)) { - const group = styles[groupName]; - for (const styleName of Object.keys(group)) { - const style = group[styleName]; +module.exports = parseJson +function parseJson (txt, reviver, context) { + context = context || 20 + try { + return JSON.parse(txt, reviver) + } catch (e) { + const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i) + const errIdx = syntaxErr + ? +syntaxErr[1] + : e.message.match(/^Unexpected end of JSON.*/i) + ? txt.length - 1 + : null + if (errIdx != null) { + const start = errIdx <= context + ? 0 + : errIdx - context + const end = errIdx + context >= txt.length + ? txt.length + : errIdx + context + e.message += ` while parsing near '${ + start === 0 ? '' : '...' + }${txt.slice(start, end)}${ + end === txt.length ? '' : '...' + }'` + } else { + e.message += ` while parsing '${txt.slice(0, context * 2)}'` + } + throw e + } +} - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; - group[styleName] = styles[styleName]; +/***/ }), +/* 419 */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { - codes.set(style[0], style[1]); - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +var LF = '\n'; +var CR = '\r'; +var LinesAndColumns = (function () { + function LinesAndColumns(string) { + this.string = string; + var offsets = [0]; + for (var offset = 0; offset < string.length;) { + switch (string[offset]) { + case LF: + offset += LF.length; + offsets.push(offset); + break; + case CR: + offset += CR.length; + if (string[offset] === LF) { + offset += LF.length; + } + offsets.push(offset); + break; + default: + offset++; + break; + } + } + this.offsets = offsets; + } + LinesAndColumns.prototype.locationForIndex = function (index) { + if (index < 0 || index > this.string.length) { + return null; + } + var line = 0; + var offsets = this.offsets; + while (offsets[line + 1] <= index) { + line++; + } + var column = index - offsets[line]; + return { line: line, column: column }; + }; + LinesAndColumns.prototype.indexForLocation = function (location) { + var line = location.line, column = location.column; + if (line < 0 || line >= this.offsets.length) { + return null; + } + if (column < 0 || column > this.lengthOfLine(line)) { + return null; + } + return this.offsets[line] + column; + }; + LinesAndColumns.prototype.lengthOfLine = function (line) { + var offset = this.offsets[line]; + var nextOffset = line === this.offsets.length - 1 ? this.string.length : this.offsets[line + 1]; + return nextOffset - offset; + }; + return LinesAndColumns; +}()); +/* harmony default export */ __webpack_exports__["default"] = (LinesAndColumns); - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - } +/***/ }), +/* 420 */ +/***/ (function(module, exports, __webpack_require__) { - const ansi2ansi = n => n; - const rgb2rgb = (r, g, b) => [r, g, b]; +"use strict"; - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; - styles.color.ansi = { - ansi: wrapAnsi16(ansi2ansi, 0) - }; - styles.color.ansi256 = { - ansi256: wrapAnsi256(ansi2ansi, 0) - }; - styles.color.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 0) - }; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.codeFrameColumns = codeFrameColumns; +exports.default = _default; - styles.bgColor.ansi = { - ansi: wrapAnsi16(ansi2ansi, 10) - }; - styles.bgColor.ansi256 = { - ansi256: wrapAnsi256(ansi2ansi, 10) - }; - styles.bgColor.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 10) - }; +var _highlight = _interopRequireWildcard(__webpack_require__(421)); - for (let key of Object.keys(colorConvert)) { - if (typeof colorConvert[key] !== 'object') { - continue; - } +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } - const suite = colorConvert[key]; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } - if (key === 'ansi16') { - key = 'ansi'; - } +let deprecationWarningShown = false; - if ('ansi16' in suite) { - styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); - styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); - } +function getDefs(chalk) { + return { + gutter: chalk.grey, + marker: chalk.red.bold, + message: chalk.red.bold + }; +} - if ('ansi256' in suite) { - styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); - styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); - } +const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; - if ('rgb' in suite) { - styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); - styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); - } - } +function getMarkerLines(loc, source, opts) { + const startLoc = Object.assign({ + column: 0, + line: -1 + }, loc.start); + const endLoc = Object.assign({}, startLoc, {}, loc.end); + const { + linesAbove = 2, + linesBelow = 3 + } = opts || {}; + const startLine = startLoc.line; + const startColumn = startLoc.column; + const endLine = endLoc.line; + const endColumn = endLoc.column; + let start = Math.max(startLine - (linesAbove + 1), 0); + let end = Math.min(source.length, endLine + linesBelow); - return styles; -} + if (startLine === -1) { + start = 0; + } -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); + if (endLine === -1) { + end = source.length; + } -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(5)(module))) + const lineDiff = endLine - startLine; + const markerLines = {}; -/***/ }), -/* 441 */ -/***/ (function(module, exports, __webpack_require__) { + if (lineDiff) { + for (let i = 0; i <= lineDiff; i++) { + const lineNumber = i + startLine; -"use strict"; + if (!startColumn) { + markerLines[lineNumber] = true; + } else if (i === 0) { + const sourceLength = source[lineNumber - 1].length; + markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]; + } else if (i === lineDiff) { + markerLines[lineNumber] = [0, endColumn]; + } else { + const sourceLength = source[lineNumber - i].length; + markerLines[lineNumber] = [0, sourceLength]; + } + } + } else { + if (startColumn === endColumn) { + if (startColumn) { + markerLines[startLine] = [startColumn, 0]; + } else { + markerLines[startLine] = true; + } + } else { + markerLines[startLine] = [startColumn, endColumn - startColumn]; + } + } -const os = __webpack_require__(11); -const hasFlag = __webpack_require__(12); + return { + start, + end, + markerLines + }; +} -const env = process.env; +function codeFrameColumns(rawLines, loc, opts = {}) { + const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts); + const chalk = (0, _highlight.getChalk)(opts); + const defs = getDefs(chalk); -let forceColor; -if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false')) { - forceColor = false; -} else if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - forceColor = true; -} -if ('FORCE_COLOR' in env) { - forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; -} + const maybeHighlight = (chalkFn, string) => { + return highlighted ? chalkFn(string) : string; + }; -function translateLevel(level) { - if (level === 0) { - return false; - } + const lines = rawLines.split(NEWLINE); + const { + start, + end, + markerLines + } = getMarkerLines(loc, lines, opts); + const hasColumns = loc.start && typeof loc.start.column === "number"; + const numberMaxWidth = String(end).length; + const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines; + let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => { + const number = start + 1 + index; + const paddedNumber = ` ${number}`.slice(-numberMaxWidth); + const gutter = ` ${paddedNumber} | `; + const hasMarker = markerLines[number]; + const lastMarkerLine = !markerLines[number + 1]; - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; -} + if (hasMarker) { + let markerLine = ""; -function supportsColor(stream) { - if (forceColor === false) { - return 0; - } + if (Array.isArray(hasMarker)) { + const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); + const numberOfMarkers = hasMarker[1] || 1; + markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; - } + if (lastMarkerLine && opts.message) { + markerLine += " " + maybeHighlight(defs.message, opts.message); + } + } - if (hasFlag('color=256')) { - return 2; - } + return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); + } else { + return ` ${maybeHighlight(defs.gutter, gutter)}${line}`; + } + }).join("\n"); - if (stream && !stream.isTTY && forceColor !== true) { - // VS code debugger doesn't have isTTY set - if (env.VSCODE_PID) { - return 1; - } - return 0; - } + if (opts.message && !hasColumns) { + frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`; + } - const min = forceColor ? 1 : 0; + if (highlighted) { + return chalk.reset(frame); + } else { + return frame; + } +} - if (process.platform === 'win32') { - // Node.js 7.5.0 is the first version of Node.js to include a patch to - // libuv that enables 256 color output on Windows. Anything earlier and it - // won't work. However, here we target Node.js 8 at minimum as it is an LTS - // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows - // release that supports 256 colors. Windows 10 build 14931 is the first release - // that supports 16m/TrueColor. - const osRelease = os.release().split('.'); - if ( - Number(process.versions.node.split('.')[0]) >= 8 && - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } +function _default(rawLines, lineNumber, colNumber, opts = {}) { + if (!deprecationWarningShown) { + deprecationWarningShown = true; + const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; - return 1; - } + if (process.emitWarning) { + process.emitWarning(message, "DeprecationWarning"); + } else { + const deprecationError = new Error(message); + deprecationError.name = "DeprecationWarning"; + console.warn(new Error(message)); + } + } - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } + colNumber = Math.max(colNumber, 0); + const location = { + start: { + column: colNumber, + line: lineNumber + } + }; + return codeFrameColumns(rawLines, location, opts); +} - return min; - } +/***/ }), +/* 421 */ +/***/ (function(module, exports, __webpack_require__) { - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } +"use strict"; - if (env.COLORTERM === 'truecolor') { - return 3; - } - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.shouldHighlight = shouldHighlight; +exports.getChalk = getChalk; +exports.default = highlight; - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default - } - } +var _jsTokens = _interopRequireWildcard(__webpack_require__(422)); - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } +var _helperValidatorIdentifier = __webpack_require__(423); - if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } +var _chalk = _interopRequireDefault(__webpack_require__(426)); - if ('COLORTERM' in env) { - return 1; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (env.TERM === 'dumb') { - return min; - } +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } - return min; -} +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -function getSupportLevel(stream) { - const level = supportsColor(stream); - return translateLevel(level); +function getDefs(chalk) { + return { + keyword: chalk.cyan, + capitalized: chalk.yellow, + jsx_tag: chalk.yellow, + punctuator: chalk.yellow, + number: chalk.magenta, + string: chalk.green, + regex: chalk.magenta, + comment: chalk.grey, + invalid: chalk.white.bgRed.bold + }; } -module.exports = { - supportsColor: getSupportLevel, - stdout: getSupportLevel(process.stdout), - stderr: getSupportLevel(process.stderr) -}; +const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; +const JSX_TAG = /^[a-z][\w-]*$/i; +const BRACKET = /^[()[\]{}]$/; +function getTokenType(match) { + const [offset, text] = match.slice(-2); + const token = (0, _jsTokens.matchToToken)(match); -/***/ }), -/* 442 */ -/***/ (function(module, exports, __webpack_require__) { + if (token.type === "name") { + if ((0, _helperValidatorIdentifier.isKeyword)(token.value) || (0, _helperValidatorIdentifier.isReservedWord)(token.value)) { + return "keyword"; + } -"use strict"; + if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == " escape ? unescape(escape) : chr)); - } else { - throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); - } - } +function highlightTokens(defs, text) { + return text.replace(_jsTokens.default, function (...args) { + const type = getTokenType(args); + const colorize = defs[type]; - return results; + if (colorize) { + return args[0].split(NEWLINE).map(str => colorize(str)).join("\n"); + } else { + return args[0]; + } + }); } -function parseStyle(style) { - STYLE_REGEX.lastIndex = 0; +function shouldHighlight(options) { + return _chalk.default.supportsColor || options.forceColor; +} - const results = []; - let matches; +function getChalk(options) { + let chalk = _chalk.default; - while ((matches = STYLE_REGEX.exec(style)) !== null) { - const name = matches[1]; + if (options.forceColor) { + chalk = new _chalk.default.constructor({ + enabled: true, + level: 1 + }); + } - if (matches[2]) { - const args = parseArguments(name, matches[2]); - results.push([name].concat(args)); - } else { - results.push([name]); - } - } + return chalk; +} - return results; +function highlight(code, options = {}) { + if (shouldHighlight(options)) { + const chalk = getChalk(options); + const defs = getDefs(chalk); + return highlightTokens(defs, code); + } else { + return code; + } } -function buildStyle(chalk, styles) { - const enabled = {}; +/***/ }), +/* 422 */ +/***/ (function(module, exports) { - for (const layer of styles) { - for (const style of layer.styles) { - enabled[style[0]] = layer.inverse ? null : style.slice(1); - } - } +// Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell +// License: MIT. (See LICENSE.) - let current = chalk; - for (const styleName of Object.keys(enabled)) { - if (Array.isArray(enabled[styleName])) { - if (!(styleName in current)) { - throw new Error(`Unknown Chalk style: ${styleName}`); - } +Object.defineProperty(exports, "__esModule", { + value: true +}) - if (enabled[styleName].length > 0) { - current = current[styleName].apply(current, enabled[styleName]); - } else { - current = current[styleName]; - } - } - } +// This regex comes from regex.coffee, and is inserted here by generate-index.js +// (run `npm run build`). +exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g - return current; +exports.matchToToken = function(match) { + var token = {type: "invalid", value: match[0], closed: undefined} + if (match[ 1]) token.type = "string" , token.closed = !!(match[3] || match[4]) + else if (match[ 5]) token.type = "comment" + else if (match[ 6]) token.type = "comment", token.closed = !!match[7] + else if (match[ 8]) token.type = "regex" + else if (match[ 9]) token.type = "number" + else if (match[10]) token.type = "name" + else if (match[11]) token.type = "punctuator" + else if (match[12]) token.type = "whitespace" + return token } -module.exports = (chalk, tmp) => { - const styles = []; - const chunks = []; - let chunk = []; - // eslint-disable-next-line max-params - tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { - if (escapeChar) { - chunk.push(unescape(escapeChar)); - } else if (style) { - const str = chunk.join(''); - chunk = []; - chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); - styles.push({inverse, styles: parseStyle(style)}); - } else if (close) { - if (styles.length === 0) { - throw new Error('Found extraneous } in Chalk template literal'); - } +/***/ }), +/* 423 */ +/***/ (function(module, exports, __webpack_require__) { - chunks.push(buildStyle(chalk, styles)(chunk.join(''))); - chunk = []; - styles.pop(); - } else { - chunk.push(chr); - } - }); +"use strict"; - chunks.push(chunk.join('')); - if (styles.length > 0) { - const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; - throw new Error(errMsg); - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "isIdentifierName", { + enumerable: true, + get: function () { + return _identifier.isIdentifierName; + } +}); +Object.defineProperty(exports, "isIdentifierChar", { + enumerable: true, + get: function () { + return _identifier.isIdentifierChar; + } +}); +Object.defineProperty(exports, "isIdentifierStart", { + enumerable: true, + get: function () { + return _identifier.isIdentifierStart; + } +}); +Object.defineProperty(exports, "isReservedWord", { + enumerable: true, + get: function () { + return _keyword.isReservedWord; + } +}); +Object.defineProperty(exports, "isStrictBindOnlyReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictBindOnlyReservedWord; + } +}); +Object.defineProperty(exports, "isStrictBindReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictBindReservedWord; + } +}); +Object.defineProperty(exports, "isStrictReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictReservedWord; + } +}); +Object.defineProperty(exports, "isKeyword", { + enumerable: true, + get: function () { + return _keyword.isKeyword; + } +}); - return chunks.join(''); -}; +var _identifier = __webpack_require__(424); +var _keyword = __webpack_require__(425); /***/ }), -/* 443 */ +/* 424 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const path_1 = __webpack_require__(16); -exports.CA_CERT_PATH = path_1.resolve(__dirname, '../certs/ca.crt'); -exports.ES_KEY_PATH = path_1.resolve(__dirname, '../certs/elasticsearch.key'); -exports.ES_CERT_PATH = path_1.resolve(__dirname, '../certs/elasticsearch.crt'); -exports.ES_P12_PATH = path_1.resolve(__dirname, '../certs/elasticsearch.p12'); -exports.ES_P12_PASSWORD = 'storepass'; -exports.ES_EMPTYPASSWORD_P12_PATH = path_1.resolve(__dirname, '../certs/elasticsearch_emptypassword.p12'); -exports.ES_NOPASSWORD_P12_PATH = path_1.resolve(__dirname, '../certs/elasticsearch_nopassword.p12'); -exports.KBN_KEY_PATH = path_1.resolve(__dirname, '../certs/kibana.key'); -exports.KBN_CERT_PATH = path_1.resolve(__dirname, '../certs/kibana.crt'); -exports.KBN_P12_PATH = path_1.resolve(__dirname, '../certs/kibana.p12'); -exports.KBN_P12_PASSWORD = 'storepass'; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isIdentifierStart = isIdentifierStart; +exports.isIdentifierChar = isIdentifierChar; +exports.isIdentifierName = isIdentifierName; +let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; +let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; +const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); +const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); +nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; +const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938]; +const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; -/***/ }), -/* 444 */ -/***/ (function(module, exports, __webpack_require__) { +function isInAstralSet(code, set) { + let pos = 0x10000; -"use strict"; + for (let i = 0, length = set.length; i < length; i += 2) { + pos += set[i]; + if (pos > code) return false; + pos += set[i + 1]; + if (pos >= code) return true; + } -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -var run_1 = __webpack_require__(445); -exports.run = run_1.run; -var fail_1 = __webpack_require__(446); -exports.createFailError = fail_1.createFailError; -exports.createFlagError = fail_1.createFlagError; -exports.combineErrors = fail_1.combineErrors; -exports.isFailError = fail_1.isFailError; + return false; +} +function isIdentifierStart(code) { + if (code < 65) return code === 36; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; -/***/ }), -/* 445 */ -/***/ (function(module, exports, __webpack_require__) { + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } -"use strict"; + return isInAstralSet(code, astralIdentifierStartCodes); +} -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(36); -const util_1 = __webpack_require__(29); -// @ts-ignore @types are outdated and module is super simple -const exit_hook_1 = tslib_1.__importDefault(__webpack_require__(368)); -const tooling_log_1 = __webpack_require__(414); -const fail_1 = __webpack_require__(446); -const flags_1 = __webpack_require__(447); -const proc_runner_1 = __webpack_require__(37); -async function run(fn, options = {}) { - var _a; - const flags = flags_1.getFlags(process.argv.slice(2), options); - if (flags.help) { - process.stderr.write(flags_1.getHelp(options)); - process.exit(1); - } - const log = new tooling_log_1.ToolingLog({ - level: tooling_log_1.pickLevelFromFlags(flags), - writeTo: process.stdout, - }); - process.on('unhandledRejection', (error) => { - log.error('UNHANDLED PROMISE REJECTION'); - log.error(error instanceof Error - ? error - : new Error(`non-Error type rejection value: ${util_1.inspect(error)}`)); - process.exit(1); - }); - const handleErrorWithoutExit = (error) => { - if (fail_1.isFailError(error)) { - log.error(error.message); - if (error.showHelp) { - log.write(flags_1.getHelp(options)); - } - process.exitCode = error.exitCode; - } - else { - log.error('UNHANDLED ERROR'); - log.error(error); - process.exitCode = 1; - } - }; - const doCleanup = () => { - const tasks = cleanupTasks.slice(0); - cleanupTasks.length = 0; - for (const task of tasks) { - try { - task(); - } - catch (error) { - handleErrorWithoutExit(error); - } - } - }; - const unhookExit = exit_hook_1.default(doCleanup); - const cleanupTasks = [unhookExit]; - try { - if (!((_a = options.flags) === null || _a === void 0 ? void 0 : _a.allowUnexpected) && flags.unexpected.length) { - throw fail_1.createFlagError(`Unknown flag(s) "${flags.unexpected.join('", "')}"`); - } - try { - await proc_runner_1.withProcRunner(log, async (procRunner) => { - await fn({ - log, - flags, - procRunner, - addCleanupTask: (task) => cleanupTasks.push(task), - }); - }); - } - finally { - doCleanup(); - } - } - catch (error) { - handleErrorWithoutExit(error); - process.exit(); - } +function isIdentifierChar(code) { + if (code < 48) return code === 36; + if (code < 58) return true; + if (code < 65) return false; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); + } + + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); } -exports.run = run; +function isIdentifierName(name) { + let isFirst = true; -/***/ }), -/* 446 */ -/***/ (function(module, exports, __webpack_require__) { + for (let _i = 0, _Array$from = Array.from(name); _i < _Array$from.length; _i++) { + const char = _Array$from[_i]; + const cp = char.codePointAt(0); -"use strict"; + if (isFirst) { + if (!isIdentifierStart(cp)) { + return false; + } -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const util_1 = __webpack_require__(29); -const FAIL_TAG = Symbol('fail error'); -function createFailError(reason, options = {}) { - const { exitCode = 1, showHelp = false } = options; - return Object.assign(new Error(reason), { - exitCode, - showHelp, - [FAIL_TAG]: true, - }); -} -exports.createFailError = createFailError; -function createFlagError(reason) { - return createFailError(reason, { - showHelp: true, - }); -} -exports.createFlagError = createFlagError; -function isFailError(error) { - return Boolean(error && error[FAIL_TAG]); -} -exports.isFailError = isFailError; -function combineErrors(errors) { - if (errors.length === 1) { - return errors[0]; + isFirst = false; + } else if (!isIdentifierChar(cp)) { + return false; } - const exitCode = errors - .filter(isFailError) - .reduce((acc, error) => Math.max(acc, error.exitCode), 1); - const showHelp = errors.some((error) => isFailError(error) && error.showHelp); - const message = errors.reduce((acc, error) => { - if (isFailError(error)) { - return acc + '\n' + error.message; - } - return acc + `\nUNHANDLED ERROR\n${util_1.inspect(error)}`; - }, ''); - return createFailError(`${errors.length} errors:\n${message}`, { - exitCode, - showHelp, - }); -} -exports.combineErrors = combineErrors; + } + return true; +} /***/ }), -/* 447 */ +/* 425 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(36); -const path_1 = __webpack_require__(16); -const dedent_1 = tslib_1.__importDefault(__webpack_require__(14)); -const getopts_1 = tslib_1.__importDefault(__webpack_require__(448)); -function getFlags(argv, options) { - const unexpectedNames = new Set(); - const flagOpts = options.flags || {}; - const { verbose, quiet, silent, debug, help, _, ...others } = getopts_1.default(argv, { - string: flagOpts.string, - boolean: [...(flagOpts.boolean || []), 'verbose', 'quiet', 'silent', 'debug', 'help'], - alias: { - ...(flagOpts.alias || {}), - v: 'verbose', - }, - default: flagOpts.default, - unknown: (name) => { - unexpectedNames.add(name); - return flagOpts.guessTypesForUnexpectedFlags; - }, - }); - const unexpected = []; - for (const unexpectedName of unexpectedNames) { - const matchingArgv = []; - iterArgv: for (const [i, v] of argv.entries()) { - for (const prefix of ['--', '-']) { - if (v.startsWith(prefix)) { - // -/--name=value - if (v.startsWith(`${prefix}${unexpectedName}=`)) { - matchingArgv.push(v); - continue iterArgv; - } - // -/--name (value possibly follows) - if (v === `${prefix}${unexpectedName}`) { - matchingArgv.push(v); - // value follows -/--name - if (argv.length > i + 1 && !argv[i + 1].startsWith('-')) { - matchingArgv.push(argv[i + 1]); - } - continue iterArgv; - } - } - } - // special case for `--no-{flag}` disabling of boolean flags - if (v === `--no-${unexpectedName}`) { - matchingArgv.push(v); - continue iterArgv; - } - // special case for shortcut flags formatted as `-abc` where `a`, `b`, - // and `c` will be three separate unexpected flags - if (unexpectedName.length === 1 && - v[0] === '-' && - v[1] !== '-' && - !v.includes('=') && - v.includes(unexpectedName)) { - matchingArgv.push(`-${unexpectedName}`); - continue iterArgv; - } - } - if (matchingArgv.length) { - unexpected.push(...matchingArgv); - } - else { - throw new Error(`unable to find unexpected flag named "${unexpectedName}"`); - } - } - return { - verbose, - quiet, - silent, - debug, - help, - _, - unexpected, - ...others, - }; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isReservedWord = isReservedWord; +exports.isStrictReservedWord = isStrictReservedWord; +exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord; +exports.isStrictBindReservedWord = isStrictBindReservedWord; +exports.isKeyword = isKeyword; +const reservedWords = { + keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], + strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], + strictBind: ["eval", "arguments"] +}; +const keywords = new Set(reservedWords.keyword); +const reservedWordsStrictSet = new Set(reservedWords.strict); +const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); + +function isReservedWord(word, inModule) { + return inModule && word === "await" || word === "enum"; } -exports.getFlags = getFlags; -function getHelp(options) { - var _a, _b; - const usage = options.usage || `node ${path_1.relative(process.cwd(), process.argv[1])}`; - const optionHelp = (dedent_1.default(((_b = (_a = options) === null || _a === void 0 ? void 0 : _a.flags) === null || _b === void 0 ? void 0 : _b.help) || '') + - '\n' + - dedent_1.default ` - --verbose, -v Log verbosely - --debug Log debug messages (less than verbose) - --quiet Only log errors - --silent Don't log anything - --help Show this message - `) - .split('\n') - .filter(Boolean) - .join('\n '); - return ` - ${usage} - ${dedent_1.default(options.description || 'Runs a dev task') - .split('\n') - .join('\n ')} +function isStrictReservedWord(word, inModule) { + return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); +} - Options: - ${optionHelp + '\n\n'}`; +function isStrictBindOnlyReservedWord(word) { + return reservedWordsStrictBindSet.has(word); +} + +function isStrictBindReservedWord(word, inModule) { + return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); } -exports.getHelp = getHelp; +function isKeyword(word) { + return keywords.has(word); +} /***/ }), -/* 448 */ +/* 426 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +const escapeStringRegexp = __webpack_require__(387); +const ansiStyles = __webpack_require__(427); +const stdoutColor = __webpack_require__(428).stdout; -const EMPTYARR = [] -const SHORTSPLIT = /$|[!-@[-`{-~][\s\S]*/g -const isArray = Array.isArray +const template = __webpack_require__(429); -const parseValue = function(any) { - if (any === "") return "" - if (any === "false") return false - const maybe = Number(any) - return maybe * 0 === 0 ? maybe : any -} +const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); -const parseAlias = function(aliases) { - let out = {}, - key, - alias, - prev, - len, - any, - i, - k +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; - for (key in aliases) { - any = aliases[key] - alias = out[key] = isArray(any) ? any : [any] +// `color-convert` models to exclude from the Chalk API due to conflicts and such +const skipModels = new Set(['gray']); - for (i = 0, len = alias.length; i < len; i++) { - prev = out[alias[i]] = [key] +const styles = Object.create(null); - for (k = 0; k < len; k++) { - if (i !== k) prev.push(alias[k]) - } - } - } +function applyOptions(obj, options) { + options = options || {}; - return out + // Detect level if not set manually + const scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; } -const parseDefault = function(aliases, defaults) { - let out = {}, - key, - alias, - value, - len, - i +function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + const chalk = {}; + applyOptions(chalk, options); - for (key in defaults) { - value = defaults[key] - alias = aliases[key] + chalk.template = function () { + const args = [].slice.call(arguments); + return chalkTag.apply(null, [chalk.template].concat(args)); + }; - out[key] = value + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); - if (alias === undefined) { - aliases[key] = EMPTYARR - } else { - for (i = 0, len = alias.length; i < len; i++) { - out[alias[i]] = value - } - } - } + chalk.template.constructor = Chalk; - return out + return chalk.template; + } + + applyOptions(this, options); } -const parseOptions = function(aliases, options, value) { - let out = {}, - key, - alias, - len, - end, - i, - k +// Use bright blue on Windows as the normal blue color is illegible +if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001B[94m'; +} - if (options !== undefined) { - for (i = 0, len = options.length; i < len; i++) { - key = options[i] - alias = aliases[key] - - out[key] = value - - if (alias === undefined) { - aliases[key] = EMPTYARR - } else { - for (k = 0, end = alias.length; k < end; k++) { - out[alias[k]] = value - } - } - } - } +for (const key of Object.keys(ansiStyles)) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); - return out + styles[key] = { + get() { + const codes = ansiStyles[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + }; } -const write = function(out, key, value, aliases, unknown) { - let i, - prev, - alias = aliases[key], - len = alias === undefined ? -1 : alias.length - - if (len >= 0 || unknown === undefined || unknown(key)) { - prev = out[key] +styles.visible = { + get() { + return build.call(this, this._styles || [], true, 'visible'); + } +}; - if (prev === undefined) { - out[key] = value - } else { - if (isArray(prev)) { - prev.push(value) - } else { - out[key] = [prev, value] - } - } +ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); +for (const model of Object.keys(ansiStyles.color.ansi)) { + if (skipModels.has(model)) { + continue; + } - for (i = 0; i < len; i++) { - out[alias[i]] = out[key] - } - } + styles[model] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.color.close, + closeRe: ansiStyles.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; } -const getopts = function(argv, opts) { - let unknown = (opts = opts || {}).unknown, - aliases = parseAlias(opts.alias), - strings = parseOptions(aliases, opts.string, ""), - values = parseDefault(aliases, opts.default), - bools = parseOptions(aliases, opts.boolean, false), - stopEarly = opts.stopEarly, - _ = [], - out = { _ }, - i = 0, - k = 0, - len = argv.length, - key, - arg, - end, - match, - value - - for (; i < len; i++) { - arg = argv[i] - - if (arg[0] !== "-" || arg === "-") { - if (stopEarly) while (i < len) _.push(argv[i++]) - else _.push(arg) - } else if (arg === "--") { - while (++i < len) _.push(argv[i]) - } else if (arg[1] === "-") { - end = arg.indexOf("=", 2) - if (arg[2] === "n" && arg[3] === "o" && arg[4] === "-") { - key = arg.slice(5, end >= 0 ? end : undefined) - value = false - } else if (end >= 0) { - key = arg.slice(2, end) - value = - bools[key] !== undefined || - (strings[key] === undefined - ? parseValue(arg.slice(end + 1)) - : arg.slice(end + 1)) - } else { - key = arg.slice(2) - value = - bools[key] !== undefined || - (len === i + 1 || argv[i + 1][0] === "-" - ? strings[key] === undefined - ? true - : "" - : strings[key] === undefined - ? parseValue(argv[++i]) - : argv[++i]) - } - write(out, key, value, aliases, unknown) - } else { - SHORTSPLIT.lastIndex = 2 - match = SHORTSPLIT.exec(arg) - end = match.index - value = match[0] - - for (k = 1; k < end; k++) { - write( - out, - (key = arg[k]), - k + 1 < end - ? strings[key] === undefined || - arg.substring(k + 1, (k = end)) + value - : value === "" - ? len === i + 1 || argv[i + 1][0] === "-" - ? strings[key] === undefined || "" - : bools[key] !== undefined || - (strings[key] === undefined ? parseValue(argv[++i]) : argv[++i]) - : bools[key] !== undefined || - (strings[key] === undefined ? parseValue(value) : value), - aliases, - unknown - ) - } - } - } - - for (key in values) if (out[key] === undefined) out[key] = values[key] - for (key in bools) if (out[key] === undefined) out[key] = false - for (key in strings) if (out[key] === undefined) out[key] = "" +ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); +for (const model of Object.keys(ansiStyles.bgColor.ansi)) { + if (skipModels.has(model)) { + continue; + } - return out + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.bgColor.close, + closeRe: ansiStyles.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; } -module.exports = getopts - - -/***/ }), -/* 449 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -var kbn_client_1 = __webpack_require__(450); -exports.KbnClient = kbn_client_1.KbnClient; -var kbn_client_requester_1 = __webpack_require__(451); -exports.uriencode = kbn_client_requester_1.uriencode; +const proto = Object.defineProperties(() => {}, styles); +function build(_styles, _empty, key) { + const builder = function () { + return applyStyle.apply(builder, arguments); + }; -/***/ }), -/* 450 */ -/***/ (function(module, exports, __webpack_require__) { + builder._styles = _styles; + builder._empty = _empty; -"use strict"; + const self = this; -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const kbn_client_requester_1 = __webpack_require__(451); -const kbn_client_status_1 = __webpack_require__(494); -const kbn_client_plugins_1 = __webpack_require__(495); -const kbn_client_version_1 = __webpack_require__(496); -const kbn_client_saved_objects_1 = __webpack_require__(497); -const kbn_client_ui_settings_1 = __webpack_require__(498); -class KbnClient { - /** - * Basic Kibana server client that implements common behaviors for talking - * to the Kibana server from dev tooling. - * - * @param log ToolingLog - * @param kibanaUrls Array of kibana server urls to send requests to - * @param uiSettingDefaults Map of uiSetting values that will be merged with all uiSetting resets - */ - constructor(log, kibanaUrls, uiSettingDefaults) { - this.log = log; - this.kibanaUrls = kibanaUrls; - this.uiSettingDefaults = uiSettingDefaults; - this.requester = new kbn_client_requester_1.KbnClientRequester(this.log, this.kibanaUrls); - this.status = new kbn_client_status_1.KbnClientStatus(this.requester); - this.plugins = new kbn_client_plugins_1.KbnClientPlugins(this.status); - this.version = new kbn_client_version_1.KbnClientVersion(this.status); - this.savedObjects = new kbn_client_saved_objects_1.KbnClientSavedObjects(this.log, this.requester); - this.uiSettings = new kbn_client_ui_settings_1.KbnClientUiSettings(this.log, this.requester, this.uiSettingDefaults); - if (!kibanaUrls.length) { - throw new Error('missing Kibana urls'); - } - } - /** - * Make a direct request to the Kibana server - */ - async request(options) { - return await this.requester.request(options); - } - resolveUrl(relativeUrl) { - return this.requester.resolveUrl(relativeUrl); - } -} -exports.KbnClient = KbnClient; + Object.defineProperty(builder, 'level', { + enumerable: true, + get() { + return self.level; + }, + set(level) { + self.level = level; + } + }); + Object.defineProperty(builder, 'enabled', { + enumerable: true, + get() { + return self.enabled; + }, + set(enabled) { + self.enabled = enabled; + } + }); -/***/ }), -/* 451 */ -/***/ (function(module, exports, __webpack_require__) { + // See below for fix regarding invisible grey/dim combination on Windows + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; -"use strict"; + // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + builder.__proto__ = proto; // eslint-disable-line no-proto -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(36); -const url_1 = tslib_1.__importDefault(__webpack_require__(452)); -const axios_1 = tslib_1.__importDefault(__webpack_require__(453)); -const axios_2 = __webpack_require__(492); -const isConcliftOnGetError = (error) => { - return (axios_2.isAxiosResponseError(error) && error.config.method === 'GET' && error.response.status === 409); -}; -exports.uriencode = (strings, ...values) => { - const queue = strings.slice(); - if (queue.length === 0) { - throw new Error('how could strings passed to `uriencode` template tag be empty?'); - } - if (queue.length !== values.length + 1) { - throw new Error('strings and values passed to `uriencode` template tag are unbalanced'); - } - // pull the first string off the queue, there is one less item in `values` - // since the values are always wrapped in strings, so we shift the extra string - // off the queue to balance the queue and values array. - const leadingString = queue.shift(); - return queue.reduce((acc, string, i) => `${acc}${encodeURIComponent(values[i])}${string}`, leadingString); -}; -const DEFAULT_MAX_ATTEMPTS = 5; -const delay = (ms) => new Promise((resolve) => { - setTimeout(resolve, ms); -}); -class KbnClientRequester { - constructor(log, kibanaUrls) { - this.log = log; - this.kibanaUrls = kibanaUrls; - } - pickUrl() { - const url = this.kibanaUrls.shift(); - this.kibanaUrls.push(url); - return url; - } - resolveUrl(relativeUrl = '/') { - return url_1.default.resolve(this.pickUrl(), relativeUrl); - } - async request(options) { - var _a; - const url = url_1.default.resolve(this.pickUrl(), options.path); - const description = options.description || `${options.method} ${url}`; - let attempt = 0; - const maxAttempts = (_a = options.retries, (_a !== null && _a !== void 0 ? _a : DEFAULT_MAX_ATTEMPTS)); - while (true) { - attempt += 1; - try { - const response = await axios_1.default.request({ - method: options.method, - url, - data: options.body, - params: options.query, - headers: { - 'kbn-xsrf': 'kbn-client', - }, - }); - return response.data; - } - catch (error) { - const conflictOnGet = isConcliftOnGetError(error); - const requestedRetries = options.retries !== undefined; - const failedToGetResponse = axios_2.isAxiosRequestError(error); - let errorMessage; - if (conflictOnGet) { - errorMessage = `Conflict on GET (path=${options.path}, attempt=${attempt}/${maxAttempts})`; - this.log.error(errorMessage); - } - else if (requestedRetries || failedToGetResponse) { - errorMessage = `[${description}] request failed (attempt=${attempt}/${maxAttempts})`; - this.log.error(errorMessage); - } - else { - throw error; - } - if (attempt < maxAttempts) { - await delay(1000 * attempt); - continue; - } - throw new Error(`${errorMessage} -- and ran out of retries`); - } - } - } + return builder; } -exports.KbnClientRequester = KbnClientRequester; - - -/***/ }), -/* 452 */ -/***/ (function(module, exports) { - -module.exports = require("url"); - -/***/ }), -/* 453 */ -/***/ (function(module, exports, __webpack_require__) { -module.exports = __webpack_require__(454); +function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + const args = arguments; + const argsLen = args.length; + let str = String(arguments[0]); -/***/ }), -/* 454 */ -/***/ (function(module, exports, __webpack_require__) { + if (argsLen === 0) { + return ''; + } -"use strict"; + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (let a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } -var utils = __webpack_require__(455); -var bind = __webpack_require__(456); -var Axios = __webpack_require__(457); -var mergeConfig = __webpack_require__(488); -var defaults = __webpack_require__(463); + // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + const originalDim = ansiStyles.dim.open; + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles.dim.open = ''; + } -/** - * Create an instance of Axios - * - * @param {Object} defaultConfig The default config for the instance - * @return {Axios} A new instance of Axios - */ -function createInstance(defaultConfig) { - var context = new Axios(defaultConfig); - var instance = bind(Axios.prototype.request, context); + for (const code of this._styles.slice().reverse()) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; - // Copy axios.prototype to instance - utils.extend(instance, Axios.prototype, context); + // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); + } - // Copy context to instance - utils.extend(instance, context); + // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + ansiStyles.dim.open = originalDim; - return instance; + return str; } -// Create the default instance to be exported -var axios = createInstance(defaults); - -// Expose Axios class to allow class inheritance -axios.Axios = Axios; +function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } -// Factory for creating new instances -axios.create = function create(instanceConfig) { - return createInstance(mergeConfig(axios.defaults, instanceConfig)); -}; + const args = [].slice.call(arguments, 2); + const parts = [strings.raw[0]]; -// Expose Cancel & CancelToken -axios.Cancel = __webpack_require__(489); -axios.CancelToken = __webpack_require__(490); -axios.isCancel = __webpack_require__(462); + for (let i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } -// Expose all/spread -axios.all = function all(promises) { - return Promise.all(promises); -}; -axios.spread = __webpack_require__(491); + return template(chalk, parts.join('')); +} -module.exports = axios; +Object.defineProperties(Chalk.prototype, styles); -// Allow use of default import syntax in TypeScript -module.exports.default = axios; +module.exports = Chalk(); // eslint-disable-line new-cap +module.exports.supportsColor = stdoutColor; +module.exports.default = module.exports; // For TypeScript /***/ }), -/* 455 */ +/* 427 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/* WEBPACK VAR INJECTION */(function(module) { +const colorConvert = __webpack_require__(389); +const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${code + offset}m`; +}; -var bind = __webpack_require__(456); - -/*global toString:true*/ - -// utils is a library of generic helper functions non-specific to axios +const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};5;${code}m`; +}; -var toString = Object.prototype.toString; +const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; -/** - * Determine if a value is an Array - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Array, otherwise false - */ -function isArray(val) { - return toString.call(val) === '[object Array]'; -} - -/** - * Determine if a value is undefined - * - * @param {Object} val The value to test - * @returns {boolean} True if the value is undefined, otherwise false - */ -function isUndefined(val) { - return typeof val === 'undefined'; -} - -/** - * Determine if a value is a Buffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Buffer, otherwise false - */ -function isBuffer(val) { - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) - && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); -} - -/** - * Determine if a value is an ArrayBuffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an ArrayBuffer, otherwise false - */ -function isArrayBuffer(val) { - return toString.call(val) === '[object ArrayBuffer]'; -} +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], -/** - * Determine if a value is a FormData - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an FormData, otherwise false - */ -function isFormData(val) { - return (typeof FormData !== 'undefined') && (val instanceof FormData); -} + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], -/** - * Determine if a value is a view on an ArrayBuffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false - */ -function isArrayBufferView(val) { - var result; - if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { - result = ArrayBuffer.isView(val); - } else { - result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); - } - return result; -} + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; -/** - * Determine if a value is a String - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a String, otherwise false - */ -function isString(val) { - return typeof val === 'string'; -} + // Fix humans + styles.color.grey = styles.color.gray; -/** - * Determine if a value is a Number - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Number, otherwise false - */ -function isNumber(val) { - return typeof val === 'number'; -} + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; -/** - * Determine if a value is an Object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Object, otherwise false - */ -function isObject(val) { - return val !== null && typeof val === 'object'; -} + for (const styleName of Object.keys(group)) { + const style = group[styleName]; -/** - * Determine if a value is a Date - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Date, otherwise false - */ -function isDate(val) { - return toString.call(val) === '[object Date]'; -} + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; -/** - * Determine if a value is a File - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a File, otherwise false - */ -function isFile(val) { - return toString.call(val) === '[object File]'; -} + group[styleName] = styles[styleName]; -/** - * Determine if a value is a Blob - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Blob, otherwise false - */ -function isBlob(val) { - return toString.call(val) === '[object Blob]'; -} + codes.set(style[0], style[1]); + } -/** - * Determine if a value is a Function - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Function, otherwise false - */ -function isFunction(val) { - return toString.call(val) === '[object Function]'; -} + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); -/** - * Determine if a value is a Stream - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Stream, otherwise false - */ -function isStream(val) { - return isObject(val) && isFunction(val.pipe); -} + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } -/** - * Determine if a value is a URLSearchParams object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a URLSearchParams object, otherwise false - */ -function isURLSearchParams(val) { - return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; -} + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; -/** - * Trim excess whitespace off the beginning and end of a string - * - * @param {String} str The String to trim - * @returns {String} The String freed of excess whitespace - */ -function trim(str) { - return str.replace(/^\s*/, '').replace(/\s*$/, ''); -} + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; -/** - * Determine if we're running in a standard browser environment - * - * This allows axios to run in a web worker, and react-native. - * Both environments support XMLHttpRequest, but not fully standard globals. - * - * web workers: - * typeof window -> undefined - * typeof document -> undefined - * - * react-native: - * navigator.product -> 'ReactNative' - * nativescript - * navigator.product -> 'NativeScript' or 'NS' - */ -function isStandardBrowserEnv() { - if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || - navigator.product === 'NativeScript' || - navigator.product === 'NS')) { - return false; - } - return ( - typeof window !== 'undefined' && - typeof document !== 'undefined' - ); -} + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; -/** - * Iterate over an Array or an Object invoking a function for each item. - * - * If `obj` is an Array callback will be called passing - * the value, index, and complete array for each item. - * - * If 'obj' is an Object callback will be called passing - * the value, key, and complete object for each property. - * - * @param {Object|Array} obj The object to iterate - * @param {Function} fn The callback to invoke for each item - */ -function forEach(obj, fn) { - // Don't bother if no value provided - if (obj === null || typeof obj === 'undefined') { - return; - } + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; - // Force an array if not already something iterable - if (typeof obj !== 'object') { - /*eslint no-param-reassign:0*/ - obj = [obj]; - } + for (let key of Object.keys(colorConvert)) { + if (typeof colorConvert[key] !== 'object') { + continue; + } - if (isArray(obj)) { - // Iterate over array values - for (var i = 0, l = obj.length; i < l; i++) { - fn.call(null, obj[i], i, obj); - } - } else { - // Iterate over object keys - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - fn.call(null, obj[key], key, obj); - } - } - } -} + const suite = colorConvert[key]; -/** - * Accepts varargs expecting each argument to be an object, then - * immutably merges the properties of each object and returns result. - * - * When multiple objects contain the same key the later object in - * the arguments list will take precedence. - * - * Example: - * - * ```js - * var result = merge({foo: 123}, {foo: 456}); - * console.log(result.foo); // outputs 456 - * ``` - * - * @param {Object} obj1 Object to merge - * @returns {Object} Result of all merge properties - */ -function merge(/* obj1, obj2, obj3, ... */) { - var result = {}; - function assignValue(val, key) { - if (typeof result[key] === 'object' && typeof val === 'object') { - result[key] = merge(result[key], val); - } else { - result[key] = val; - } - } + if (key === 'ansi16') { + key = 'ansi'; + } - for (var i = 0, l = arguments.length; i < l; i++) { - forEach(arguments[i], assignValue); - } - return result; -} + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } -/** - * Function equal to merge with the difference being that no reference - * to original objects is kept. - * - * @see merge - * @param {Object} obj1 Object to merge - * @returns {Object} Result of all merge properties - */ -function deepMerge(/* obj1, obj2, obj3, ... */) { - var result = {}; - function assignValue(val, key) { - if (typeof result[key] === 'object' && typeof val === 'object') { - result[key] = deepMerge(result[key], val); - } else if (typeof val === 'object') { - result[key] = deepMerge({}, val); - } else { - result[key] = val; - } - } + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } - for (var i = 0, l = arguments.length; i < l; i++) { - forEach(arguments[i], assignValue); - } - return result; -} + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } -/** - * Extends object a by mutably adding to it the properties of object b. - * - * @param {Object} a The object to be extended - * @param {Object} b The object to copy properties from - * @param {Object} thisArg The object to bind function to - * @return {Object} The resulting value of object a - */ -function extend(a, b, thisArg) { - forEach(b, function assignValue(val, key) { - if (thisArg && typeof val === 'function') { - a[key] = bind(val, thisArg); - } else { - a[key] = val; - } - }); - return a; + return styles; } -module.exports = { - isArray: isArray, - isArrayBuffer: isArrayBuffer, - isBuffer: isBuffer, - isFormData: isFormData, - isArrayBufferView: isArrayBufferView, - isString: isString, - isNumber: isNumber, - isObject: isObject, - isUndefined: isUndefined, - isDate: isDate, - isFile: isFile, - isBlob: isBlob, - isFunction: isFunction, - isStream: isStream, - isURLSearchParams: isURLSearchParams, - isStandardBrowserEnv: isStandardBrowserEnv, - forEach: forEach, - merge: merge, - deepMerge: deepMerge, - extend: extend, - trim: trim -}; +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(11)(module))) /***/ }), -/* 456 */ +/* 428 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +const os = __webpack_require__(364); +const hasFlag = __webpack_require__(394); -module.exports = function bind(fn, thisArg) { - return function wrap() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - return fn.apply(thisArg, args); - }; -}; - - -/***/ }), -/* 457 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +const env = process.env; +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; +} -var utils = __webpack_require__(455); -var buildURL = __webpack_require__(458); -var InterceptorManager = __webpack_require__(459); -var dispatchRequest = __webpack_require__(460); -var mergeConfig = __webpack_require__(488); +function translateLevel(level) { + if (level === 0) { + return false; + } -/** - * Create a new instance of Axios - * - * @param {Object} instanceConfig The default config for the instance - */ -function Axios(instanceConfig) { - this.defaults = instanceConfig; - this.interceptors = { - request: new InterceptorManager(), - response: new InterceptorManager() - }; + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; } -/** - * Dispatch a request - * - * @param {Object} config The config specific for this request (merged with this.defaults) - */ -Axios.prototype.request = function request(config) { - /*eslint no-param-reassign:0*/ - // Allow for axios('example/url'[, config]) a la fetch API - if (typeof config === 'string') { - config = arguments[1] || {}; - config.url = arguments[0]; - } else { - config = config || {}; - } +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } - config = mergeConfig(this.defaults, config); + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } - // Set config.method - if (config.method) { - config.method = config.method.toLowerCase(); - } else if (this.defaults.method) { - config.method = this.defaults.method.toLowerCase(); - } else { - config.method = 'get'; - } + if (hasFlag('color=256')) { + return 2; + } - // Hook up interceptors middleware - var chain = [dispatchRequest, undefined]; - var promise = Promise.resolve(config); + if (stream && !stream.isTTY && forceColor !== true) { + // VS code debugger doesn't have isTTY set + if (env.VSCODE_PID) { + return 1; + } + return 0; + } - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - chain.unshift(interceptor.fulfilled, interceptor.rejected); - }); + const min = forceColor ? 1 : 0; - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - chain.push(interceptor.fulfilled, interceptor.rejected); - }); + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(process.versions.node.split('.')[0]) >= 8 && + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } - while (chain.length) { - promise = promise.then(chain.shift(), chain.shift()); - } + return 1; + } - return promise; -}; + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } -Axios.prototype.getUri = function getUri(config) { - config = mergeConfig(this.defaults, config); - return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); -}; + return min; + } -// Provide aliases for supported request methods -utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { - /*eslint func-names:0*/ - Axios.prototype[method] = function(url, config) { - return this.request(utils.merge(config || {}, { - method: method, - url: url - })); - }; -}); + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - /*eslint func-names:0*/ - Axios.prototype[method] = function(url, data, config) { - return this.request(utils.merge(config || {}, { - method: method, - url: url, - data: data - })); - }; -}); + if (env.COLORTERM === 'truecolor') { + return 3; + } -module.exports = Axios; + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } -/***/ }), -/* 458 */ -/***/ (function(module, exports, __webpack_require__) { + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } -"use strict"; + if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + if ('COLORTERM' in env) { + return 1; + } -var utils = __webpack_require__(455); + if (env.TERM === 'dumb') { + return min; + } -function encode(val) { - return encodeURIComponent(val). - replace(/%40/gi, '@'). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, '+'). - replace(/%5B/gi, '['). - replace(/%5D/gi, ']'); + return min; } -/** - * Build a URL by appending params to the end - * - * @param {string} url The base of the url (e.g., http://www.google.com) - * @param {object} [params] The params to be appended - * @returns {string} The formatted url - */ -module.exports = function buildURL(url, params, paramsSerializer) { - /*eslint no-param-reassign:0*/ - if (!params) { - return url; - } - - var serializedParams; - if (paramsSerializer) { - serializedParams = paramsSerializer(params); - } else if (utils.isURLSearchParams(params)) { - serializedParams = params.toString(); - } else { - var parts = []; - - utils.forEach(params, function serialize(val, key) { - if (val === null || typeof val === 'undefined') { - return; - } - - if (utils.isArray(val)) { - key = key + '[]'; - } else { - val = [val]; - } - - utils.forEach(val, function parseValue(v) { - if (utils.isDate(v)) { - v = v.toISOString(); - } else if (utils.isObject(v)) { - v = JSON.stringify(v); - } - parts.push(encode(key) + '=' + encode(v)); - }); - }); - - serializedParams = parts.join('&'); - } - - if (serializedParams) { - var hashmarkIndex = url.indexOf('#'); - if (hashmarkIndex !== -1) { - url = url.slice(0, hashmarkIndex); - } - - url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; - } +function getSupportLevel(stream) { + const level = supportsColor(stream); + return translateLevel(level); +} - return url; +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) }; /***/ }), -/* 459 */ +/* 429 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; +const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; +const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; +const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; -var utils = __webpack_require__(455); - -function InterceptorManager() { - this.handlers = []; -} +const ESCAPES = new Map([ + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['b', '\b'], + ['f', '\f'], + ['v', '\v'], + ['0', '\0'], + ['\\', '\\'], + ['e', '\u001B'], + ['a', '\u0007'] +]); -/** - * Add a new interceptor to the stack - * - * @param {Function} fulfilled The function to handle `then` for a `Promise` - * @param {Function} rejected The function to handle `reject` for a `Promise` - * - * @return {Number} An ID used to remove interceptor later - */ -InterceptorManager.prototype.use = function use(fulfilled, rejected) { - this.handlers.push({ - fulfilled: fulfilled, - rejected: rejected - }); - return this.handlers.length - 1; -}; +function unescape(c) { + if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } -/** - * Remove an interceptor from the stack - * - * @param {Number} id The ID that was returned by `use` - */ -InterceptorManager.prototype.eject = function eject(id) { - if (this.handlers[id]) { - this.handlers[id] = null; - } -}; + return ESCAPES.get(c) || c; +} -/** - * Iterate over all the registered interceptors - * - * This method is particularly useful for skipping over any - * interceptors that may have become `null` calling `eject`. - * - * @param {Function} fn The function to call for each interceptor - */ -InterceptorManager.prototype.forEach = function forEach(fn) { - utils.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) { - fn(h); - } - }); -}; +function parseArguments(name, args) { + const results = []; + const chunks = args.trim().split(/\s*,\s*/g); + let matches; -module.exports = InterceptorManager; + for (const chunk of chunks) { + if (!isNaN(chunk)) { + results.push(Number(chunk)); + } else if ((matches = chunk.match(STRING_REGEX))) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } + return results; +} -/***/ }), -/* 460 */ -/***/ (function(module, exports, __webpack_require__) { +function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; -"use strict"; + const results = []; + let matches; + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; -var utils = __webpack_require__(455); -var transformData = __webpack_require__(461); -var isCancel = __webpack_require__(462); -var defaults = __webpack_require__(463); + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } -/** - * Throws a `Cancel` if cancellation has been requested. - */ -function throwIfCancellationRequested(config) { - if (config.cancelToken) { - config.cancelToken.throwIfRequested(); - } + return results; } -/** - * Dispatch a request to the server using the configured adapter. - * - * @param {object} config The config that is to be used for the request - * @returns {Promise} The Promise to be fulfilled - */ -module.exports = function dispatchRequest(config) { - throwIfCancellationRequested(config); +function buildStyle(chalk, styles) { + const enabled = {}; - // Ensure headers exist - config.headers = config.headers || {}; + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } - // Transform request data - config.data = transformData( - config.data, - config.headers, - config.transformRequest - ); + let current = chalk; + for (const styleName of Object.keys(enabled)) { + if (Array.isArray(enabled[styleName])) { + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } - // Flatten headers - config.headers = utils.merge( - config.headers.common || {}, - config.headers[config.method] || {}, - config.headers - ); + if (enabled[styleName].length > 0) { + current = current[styleName].apply(current, enabled[styleName]); + } else { + current = current[styleName]; + } + } + } - utils.forEach( - ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], - function cleanHeaderConfig(method) { - delete config.headers[method]; - } - ); + return current; +} - var adapter = config.adapter || defaults.adapter; +module.exports = (chalk, tmp) => { + const styles = []; + const chunks = []; + let chunk = []; - return adapter(config).then(function onAdapterResolution(response) { - throwIfCancellationRequested(config); + // eslint-disable-next-line max-params + tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { + if (escapeChar) { + chunk.push(unescape(escapeChar)); + } else if (style) { + const str = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); + styles.push({inverse, styles: parseStyle(style)}); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } - // Transform response data - response.data = transformData( - response.data, - response.headers, - config.transformResponse - ); + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(chr); + } + }); - return response; - }, function onAdapterRejection(reason) { - if (!isCancel(reason)) { - throwIfCancellationRequested(config); + chunks.push(chunk.join('')); - // Transform response data - if (reason && reason.response) { - reason.response.data = transformData( - reason.response.data, - reason.response.headers, - config.transformResponse - ); - } - } + if (styles.length > 0) { + const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMsg); + } - return Promise.reject(reason); - }); + return chunks.join(''); }; /***/ }), -/* 461 */ +/* 430 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - -var utils = __webpack_require__(455); - -/** - * Transform the data for a request or a response +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * @param {Object|String} data The data to be transformed - * @param {Array} headers The headers for the request or response - * @param {Array|Function} fns A single function or Array of functions - * @returns {*} The resulting transformed data + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ -module.exports = function transformData(data, headers, fns) { - /*eslint no-param-reassign:0*/ - utils.forEach(fns, function transform(fn) { - data = fn(data, headers); - }); - - return data; -}; +Object.defineProperty(exports, "__esModule", { value: true }); +const path_1 = __webpack_require__(4); +exports.CA_CERT_PATH = path_1.resolve(__dirname, '../certs/ca.crt'); +exports.ES_KEY_PATH = path_1.resolve(__dirname, '../certs/elasticsearch.key'); +exports.ES_CERT_PATH = path_1.resolve(__dirname, '../certs/elasticsearch.crt'); +exports.ES_P12_PATH = path_1.resolve(__dirname, '../certs/elasticsearch.p12'); +exports.ES_P12_PASSWORD = 'storepass'; +exports.ES_EMPTYPASSWORD_P12_PATH = path_1.resolve(__dirname, '../certs/elasticsearch_emptypassword.p12'); +exports.ES_NOPASSWORD_P12_PATH = path_1.resolve(__dirname, '../certs/elasticsearch_nopassword.p12'); +exports.KBN_KEY_PATH = path_1.resolve(__dirname, '../certs/kibana.key'); +exports.KBN_CERT_PATH = path_1.resolve(__dirname, '../certs/kibana.crt'); +exports.KBN_P12_PATH = path_1.resolve(__dirname, '../certs/kibana.p12'); +exports.KBN_P12_PASSWORD = 'storepass'; /***/ }), -/* 462 */ +/* 431 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - -module.exports = function isCancel(value) { - return !!(value && value.__CANCEL__); -}; +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +var run_1 = __webpack_require__(432); +exports.run = run_1.run; +var fail_1 = __webpack_require__(433); +exports.createFailError = fail_1.createFailError; +exports.createFlagError = fail_1.createFlagError; +exports.combineErrors = fail_1.combineErrors; +exports.isFailError = fail_1.isFailError; /***/ }), -/* 463 */ +/* 432 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - -var utils = __webpack_require__(455); -var normalizeHeaderName = __webpack_require__(464); - -var DEFAULT_CONTENT_TYPE = { - 'Content-Type': 'application/x-www-form-urlencoded' -}; - -function setContentTypeIfUnset(headers, value) { - if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { - headers['Content-Type'] = value; - } -} - -function getDefaultAdapter() { - var adapter; - if (typeof XMLHttpRequest !== 'undefined') { - // For browsers use XHR adapter - adapter = __webpack_require__(465); - } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { - // For node use HTTP adapter - adapter = __webpack_require__(475); - } - return adapter; -} - -var defaults = { - adapter: getDefaultAdapter(), - - transformRequest: [function transformRequest(data, headers) { - normalizeHeaderName(headers, 'Accept'); - normalizeHeaderName(headers, 'Content-Type'); - if (utils.isFormData(data) || - utils.isArrayBuffer(data) || - utils.isBuffer(data) || - utils.isStream(data) || - utils.isFile(data) || - utils.isBlob(data) - ) { - return data; - } - if (utils.isArrayBufferView(data)) { - return data.buffer; - } - if (utils.isURLSearchParams(data)) { - setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); - return data.toString(); +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = __webpack_require__(6); +const util_1 = __webpack_require__(397); +// @ts-ignore @types are outdated and module is super simple +const exit_hook_1 = tslib_1.__importDefault(__webpack_require__(339)); +const tooling_log_1 = __webpack_require__(400); +const fail_1 = __webpack_require__(433); +const flags_1 = __webpack_require__(434); +const proc_runner_1 = __webpack_require__(7); +async function run(fn, options = {}) { + var _a; + const flags = flags_1.getFlags(process.argv.slice(2), options); + if (flags.help) { + process.stderr.write(flags_1.getHelp(options)); + process.exit(1); } - if (utils.isObject(data)) { - setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); - return JSON.stringify(data); + const log = new tooling_log_1.ToolingLog({ + level: tooling_log_1.pickLevelFromFlags(flags), + writeTo: process.stdout, + }); + process.on('unhandledRejection', (error) => { + log.error('UNHANDLED PROMISE REJECTION'); + log.error(error instanceof Error + ? error + : new Error(`non-Error type rejection value: ${util_1.inspect(error)}`)); + process.exit(1); + }); + const handleErrorWithoutExit = (error) => { + if (fail_1.isFailError(error)) { + log.error(error.message); + if (error.showHelp) { + log.write(flags_1.getHelp(options)); + } + process.exitCode = error.exitCode; + } + else { + log.error('UNHANDLED ERROR'); + log.error(error); + process.exitCode = 1; + } + }; + const doCleanup = () => { + const tasks = cleanupTasks.slice(0); + cleanupTasks.length = 0; + for (const task of tasks) { + try { + task(); + } + catch (error) { + handleErrorWithoutExit(error); + } + } + }; + const unhookExit = exit_hook_1.default(doCleanup); + const cleanupTasks = [unhookExit]; + try { + if (!((_a = options.flags) === null || _a === void 0 ? void 0 : _a.allowUnexpected) && flags.unexpected.length) { + throw fail_1.createFlagError(`Unknown flag(s) "${flags.unexpected.join('", "')}"`); + } + try { + await proc_runner_1.withProcRunner(log, async (procRunner) => { + await fn({ + log, + flags, + procRunner, + addCleanupTask: (task) => cleanupTasks.push(task), + }); + }); + } + finally { + doCleanup(); + } } - return data; - }], - - transformResponse: [function transformResponse(data) { - /*eslint no-param-reassign:0*/ - if (typeof data === 'string') { - try { - data = JSON.parse(data); - } catch (e) { /* Ignore */ } + catch (error) { + handleErrorWithoutExit(error); + process.exit(); } - return data; - }], - - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, - - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN', - - maxContentLength: -1, - - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - } -}; +} +exports.run = run; -defaults.headers = { - common: { - 'Accept': 'application/json, text/plain, */*' - } -}; -utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { - defaults.headers[method] = {}; -}); +/***/ }), +/* 433 */ +/***/ (function(module, exports, __webpack_require__) { -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); -}); +"use strict"; -module.exports = defaults; +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const util_1 = __webpack_require__(397); +const FAIL_TAG = Symbol('fail error'); +function createFailError(reason, options = {}) { + const { exitCode = 1, showHelp = false } = options; + return Object.assign(new Error(reason), { + exitCode, + showHelp, + [FAIL_TAG]: true, + }); +} +exports.createFailError = createFailError; +function createFlagError(reason) { + return createFailError(reason, { + showHelp: true, + }); +} +exports.createFlagError = createFlagError; +function isFailError(error) { + return Boolean(error && error[FAIL_TAG]); +} +exports.isFailError = isFailError; +function combineErrors(errors) { + if (errors.length === 1) { + return errors[0]; + } + const exitCode = errors + .filter(isFailError) + .reduce((acc, error) => Math.max(acc, error.exitCode), 1); + const showHelp = errors.some((error) => isFailError(error) && error.showHelp); + const message = errors.reduce((acc, error) => { + if (isFailError(error)) { + return acc + '\n' + error.message; + } + return acc + `\nUNHANDLED ERROR\n${util_1.inspect(error)}`; + }, ''); + return createFailError(`${errors.length} errors:\n${message}`, { + exitCode, + showHelp, + }); +} +exports.combineErrors = combineErrors; /***/ }), -/* 464 */ +/* 434 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = __webpack_require__(6); +const path_1 = __webpack_require__(4); +const dedent_1 = tslib_1.__importDefault(__webpack_require__(2)); +const getopts_1 = tslib_1.__importDefault(__webpack_require__(435)); +function getFlags(argv, options) { + const unexpectedNames = new Set(); + const flagOpts = options.flags || {}; + const { verbose, quiet, silent, debug, help, _, ...others } = getopts_1.default(argv, { + string: flagOpts.string, + boolean: [...(flagOpts.boolean || []), 'verbose', 'quiet', 'silent', 'debug', 'help'], + alias: { + ...(flagOpts.alias || {}), + v: 'verbose', + }, + default: flagOpts.default, + unknown: (name) => { + unexpectedNames.add(name); + return flagOpts.guessTypesForUnexpectedFlags; + }, + }); + const unexpected = []; + for (const unexpectedName of unexpectedNames) { + const matchingArgv = []; + iterArgv: for (const [i, v] of argv.entries()) { + for (const prefix of ['--', '-']) { + if (v.startsWith(prefix)) { + // -/--name=value + if (v.startsWith(`${prefix}${unexpectedName}=`)) { + matchingArgv.push(v); + continue iterArgv; + } + // -/--name (value possibly follows) + if (v === `${prefix}${unexpectedName}`) { + matchingArgv.push(v); + // value follows -/--name + if (argv.length > i + 1 && !argv[i + 1].startsWith('-')) { + matchingArgv.push(argv[i + 1]); + } + continue iterArgv; + } + } + } + // special case for `--no-{flag}` disabling of boolean flags + if (v === `--no-${unexpectedName}`) { + matchingArgv.push(v); + continue iterArgv; + } + // special case for shortcut flags formatted as `-abc` where `a`, `b`, + // and `c` will be three separate unexpected flags + if (unexpectedName.length === 1 && + v[0] === '-' && + v[1] !== '-' && + !v.includes('=') && + v.includes(unexpectedName)) { + matchingArgv.push(`-${unexpectedName}`); + continue iterArgv; + } + } + if (matchingArgv.length) { + unexpected.push(...matchingArgv); + } + else { + throw new Error(`unable to find unexpected flag named "${unexpectedName}"`); + } + } + return { + verbose, + quiet, + silent, + debug, + help, + _, + unexpected, + ...others, + }; +} +exports.getFlags = getFlags; +function getHelp(options) { + var _a, _b; + const usage = options.usage || `node ${path_1.relative(process.cwd(), process.argv[1])}`; + const optionHelp = (dedent_1.default(((_b = (_a = options) === null || _a === void 0 ? void 0 : _a.flags) === null || _b === void 0 ? void 0 : _b.help) || '') + + '\n' + + dedent_1.default ` + --verbose, -v Log verbosely + --debug Log debug messages (less than verbose) + --quiet Only log errors + --silent Don't log anything + --help Show this message + `) + .split('\n') + .filter(Boolean) + .join('\n '); + return ` + ${usage} -var utils = __webpack_require__(455); + ${dedent_1.default(options.description || 'Runs a dev task') + .split('\n') + .join('\n ')} -module.exports = function normalizeHeaderName(headers, normalizedName) { - utils.forEach(headers, function processHeader(value, name) { - if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { - headers[normalizedName] = value; - delete headers[name]; - } - }); -}; + Options: + ${optionHelp + '\n\n'}`; +} +exports.getHelp = getHelp; /***/ }), -/* 465 */ +/* 435 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var utils = __webpack_require__(455); -var settle = __webpack_require__(466); -var buildURL = __webpack_require__(458); -var buildFullPath = __webpack_require__(469); -var parseHeaders = __webpack_require__(472); -var isURLSameOrigin = __webpack_require__(473); -var createError = __webpack_require__(467); - -module.exports = function xhrAdapter(config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - var requestData = config.data; - var requestHeaders = config.headers; - - if (utils.isFormData(requestData)) { - delete requestHeaders['Content-Type']; // Let the browser set it - } +const EMPTYARR = [] +const SHORTSPLIT = /$|[!-@[-`{-~][\s\S]*/g +const isArray = Array.isArray - var request = new XMLHttpRequest(); +const parseValue = function(any) { + if (any === "") return "" + if (any === "false") return false + const maybe = Number(any) + return maybe * 0 === 0 ? maybe : any +} - // HTTP basic authentication - if (config.auth) { - var username = config.auth.username || ''; - var password = config.auth.password || ''; - requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); - } +const parseAlias = function(aliases) { + let out = {}, + key, + alias, + prev, + len, + any, + i, + k - var fullPath = buildFullPath(config.baseURL, config.url); - request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); + for (key in aliases) { + any = aliases[key] + alias = out[key] = isArray(any) ? any : [any] - // Set the request timeout in MS - request.timeout = config.timeout; + for (i = 0, len = alias.length; i < len; i++) { + prev = out[alias[i]] = [key] - // Listen for ready state - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; + for (k = 0; k < len; k++) { + if (i !== k) prev.push(alias[k]) } + } + } - // The request errored out and we didn't get a response, this will be - // handled by onerror instead - // With one exception: request that using file: protocol, most browsers - // will return status as 0 even though it's a successful request - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { - return; - } + return out +} - // Prepare the response - var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; - var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; - var response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config: config, - request: request - }; +const parseDefault = function(aliases, defaults) { + let out = {}, + key, + alias, + value, + len, + i - settle(resolve, reject, response); + for (key in defaults) { + value = defaults[key] + alias = aliases[key] - // Clean up request - request = null; - }; + out[key] = value - // Handle browser request cancellation (as opposed to a manual cancellation) - request.onabort = function handleAbort() { - if (!request) { - return; + if (alias === undefined) { + aliases[key] = EMPTYARR + } else { + for (i = 0, len = alias.length; i < len; i++) { + out[alias[i]] = value } + } + } - reject(createError('Request aborted', config, 'ECONNABORTED', request)); + return out +} - // Clean up request - request = null; - }; +const parseOptions = function(aliases, options, value) { + let out = {}, + key, + alias, + len, + end, + i, + k - // Handle low level network errors - request.onerror = function handleError() { - // Real errors are hidden from us by the browser - // onerror should only fire if it's a network error - reject(createError('Network Error', config, null, request)); + if (options !== undefined) { + for (i = 0, len = options.length; i < len; i++) { + key = options[i] + alias = aliases[key] - // Clean up request - request = null; - }; + out[key] = value - // Handle timeout - request.ontimeout = function handleTimeout() { - var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; + if (alias === undefined) { + aliases[key] = EMPTYARR + } else { + for (k = 0, end = alias.length; k < end; k++) { + out[alias[k]] = value + } } - reject(createError(timeoutErrorMessage, config, 'ECONNABORTED', - request)); + } + } - // Clean up request - request = null; - }; + return out +} - // Add xsrf header - // This is only done if running in a standard browser environment. - // Specifically not if we're in a web worker, or react-native. - if (utils.isStandardBrowserEnv()) { - var cookies = __webpack_require__(474); +const write = function(out, key, value, aliases, unknown) { + let i, + prev, + alias = aliases[key], + len = alias === undefined ? -1 : alias.length - // Add xsrf header - var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? - cookies.read(config.xsrfCookieName) : - undefined; + if (len >= 0 || unknown === undefined || unknown(key)) { + prev = out[key] - if (xsrfValue) { - requestHeaders[config.xsrfHeaderName] = xsrfValue; + if (prev === undefined) { + out[key] = value + } else { + if (isArray(prev)) { + prev.push(value) + } else { + out[key] = [prev, value] } } - // Add headers to the request - if ('setRequestHeader' in request) { - utils.forEach(requestHeaders, function setRequestHeader(val, key) { - if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { - // Remove Content-Type if data is undefined - delete requestHeaders[key]; - } else { - // Otherwise add header to the request - request.setRequestHeader(key, val); - } - }); + for (i = 0; i < len; i++) { + out[alias[i]] = out[key] } + } +} - // Add withCredentials to request if needed - if (!utils.isUndefined(config.withCredentials)) { - request.withCredentials = !!config.withCredentials; - } +const getopts = function(argv, opts) { + let unknown = (opts = opts || {}).unknown, + aliases = parseAlias(opts.alias), + strings = parseOptions(aliases, opts.string, ""), + values = parseDefault(aliases, opts.default), + bools = parseOptions(aliases, opts.boolean, false), + stopEarly = opts.stopEarly, + _ = [], + out = { _ }, + i = 0, + k = 0, + len = argv.length, + key, + arg, + end, + match, + value - // Add responseType to request if needed - if (config.responseType) { - try { - request.responseType = config.responseType; - } catch (e) { - // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. - // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. - if (config.responseType !== 'json') { - throw e; - } - } - } + for (; i < len; i++) { + arg = argv[i] - // Handle progress if needed - if (typeof config.onDownloadProgress === 'function') { - request.addEventListener('progress', config.onDownloadProgress); - } + if (arg[0] !== "-" || arg === "-") { + if (stopEarly) while (i < len) _.push(argv[i++]) + else _.push(arg) + } else if (arg === "--") { + while (++i < len) _.push(argv[i]) + } else if (arg[1] === "-") { + end = arg.indexOf("=", 2) + if (arg[2] === "n" && arg[3] === "o" && arg[4] === "-") { + key = arg.slice(5, end >= 0 ? end : undefined) + value = false + } else if (end >= 0) { + key = arg.slice(2, end) + value = + bools[key] !== undefined || + (strings[key] === undefined + ? parseValue(arg.slice(end + 1)) + : arg.slice(end + 1)) + } else { + key = arg.slice(2) + value = + bools[key] !== undefined || + (len === i + 1 || argv[i + 1][0] === "-" + ? strings[key] === undefined + ? true + : "" + : strings[key] === undefined + ? parseValue(argv[++i]) + : argv[++i]) + } + write(out, key, value, aliases, unknown) + } else { + SHORTSPLIT.lastIndex = 2 + match = SHORTSPLIT.exec(arg) + end = match.index + value = match[0] - // Not all browsers support upload events - if (typeof config.onUploadProgress === 'function' && request.upload) { - request.upload.addEventListener('progress', config.onUploadProgress); + for (k = 1; k < end; k++) { + write( + out, + (key = arg[k]), + k + 1 < end + ? strings[key] === undefined || + arg.substring(k + 1, (k = end)) + value + : value === "" + ? len === i + 1 || argv[i + 1][0] === "-" + ? strings[key] === undefined || "" + : bools[key] !== undefined || + (strings[key] === undefined ? parseValue(argv[++i]) : argv[++i]) + : bools[key] !== undefined || + (strings[key] === undefined ? parseValue(value) : value), + aliases, + unknown + ) + } } + } - if (config.cancelToken) { - // Handle cancellation - config.cancelToken.promise.then(function onCanceled(cancel) { - if (!request) { - return; - } - - request.abort(); - reject(cancel); - // Clean up request - request = null; - }); - } + for (key in values) if (out[key] === undefined) out[key] = values[key] + for (key in bools) if (out[key] === undefined) out[key] = false + for (key in strings) if (out[key] === undefined) out[key] = "" - if (requestData === undefined) { - requestData = null; - } + return out +} - // Send the request - request.send(requestData); - }); -}; +module.exports = getopts /***/ }), -/* 466 */ +/* 436 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - -var createError = __webpack_require__(467); - -/** - * Resolve or reject a Promise based on response status. +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * @param {Function} resolve A function that resolves the promise. - * @param {Function} reject A function that rejects the promise. - * @param {object} response The response. + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ -module.exports = function settle(resolve, reject, response) { - var validateStatus = response.config.validateStatus; - if (!validateStatus || validateStatus(response.status)) { - resolve(response); - } else { - reject(createError( - 'Request failed with status code ' + response.status, - response.config, - null, - response.request, - response - )); - } -}; +Object.defineProperty(exports, "__esModule", { value: true }); +var kbn_client_1 = __webpack_require__(437); +exports.KbnClient = kbn_client_1.KbnClient; +var kbn_client_requester_1 = __webpack_require__(438); +exports.uriencode = kbn_client_requester_1.uriencode; /***/ }), -/* 467 */ +/* 437 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - -var enhanceError = __webpack_require__(468); - -/** - * Create an Error with the specified message, config, error code, request and response. +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * @param {string} message The error message. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The created error. + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ -module.exports = function createError(message, config, code, request, response) { - var error = new Error(message); - return enhanceError(error, config, code, request, response); -}; +Object.defineProperty(exports, "__esModule", { value: true }); +const kbn_client_requester_1 = __webpack_require__(438); +const kbn_client_status_1 = __webpack_require__(481); +const kbn_client_plugins_1 = __webpack_require__(482); +const kbn_client_version_1 = __webpack_require__(483); +const kbn_client_saved_objects_1 = __webpack_require__(484); +const kbn_client_ui_settings_1 = __webpack_require__(485); +class KbnClient { + /** + * Basic Kibana server client that implements common behaviors for talking + * to the Kibana server from dev tooling. + * + * @param log ToolingLog + * @param kibanaUrls Array of kibana server urls to send requests to + * @param uiSettingDefaults Map of uiSetting values that will be merged with all uiSetting resets + */ + constructor(log, kibanaUrls, uiSettingDefaults) { + this.log = log; + this.kibanaUrls = kibanaUrls; + this.uiSettingDefaults = uiSettingDefaults; + this.requester = new kbn_client_requester_1.KbnClientRequester(this.log, this.kibanaUrls); + this.status = new kbn_client_status_1.KbnClientStatus(this.requester); + this.plugins = new kbn_client_plugins_1.KbnClientPlugins(this.status); + this.version = new kbn_client_version_1.KbnClientVersion(this.status); + this.savedObjects = new kbn_client_saved_objects_1.KbnClientSavedObjects(this.log, this.requester); + this.uiSettings = new kbn_client_ui_settings_1.KbnClientUiSettings(this.log, this.requester, this.uiSettingDefaults); + if (!kibanaUrls.length) { + throw new Error('missing Kibana urls'); + } + } + /** + * Make a direct request to the Kibana server + */ + async request(options) { + return await this.requester.request(options); + } + resolveUrl(relativeUrl) { + return this.requester.resolveUrl(relativeUrl); + } +} +exports.KbnClient = KbnClient; /***/ }), -/* 468 */ +/* 438 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - -/** - * Update an Error with the specified config, error code, and response. +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * @param {Error} error The error to update. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The error. + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ -module.exports = function enhanceError(error, config, code, request, response) { - error.config = config; - if (code) { - error.code = code; - } - - error.request = request; - error.response = response; - error.isAxiosError = true; - - error.toJSON = function() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: this.config, - code: this.code - }; - }; - return error; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = __webpack_require__(6); +const url_1 = tslib_1.__importDefault(__webpack_require__(439)); +const axios_1 = tslib_1.__importDefault(__webpack_require__(440)); +const axios_2 = __webpack_require__(479); +const isConcliftOnGetError = (error) => { + return (axios_2.isAxiosResponseError(error) && error.config.method === 'GET' && error.response.status === 409); +}; +exports.uriencode = (strings, ...values) => { + const queue = strings.slice(); + if (queue.length === 0) { + throw new Error('how could strings passed to `uriencode` template tag be empty?'); + } + if (queue.length !== values.length + 1) { + throw new Error('strings and values passed to `uriencode` template tag are unbalanced'); + } + // pull the first string off the queue, there is one less item in `values` + // since the values are always wrapped in strings, so we shift the extra string + // off the queue to balance the queue and values array. + const leadingString = queue.shift(); + return queue.reduce((acc, string, i) => `${acc}${encodeURIComponent(values[i])}${string}`, leadingString); }; +const DEFAULT_MAX_ATTEMPTS = 5; +const delay = (ms) => new Promise((resolve) => { + setTimeout(resolve, ms); +}); +class KbnClientRequester { + constructor(log, kibanaUrls) { + this.log = log; + this.kibanaUrls = kibanaUrls; + } + pickUrl() { + const url = this.kibanaUrls.shift(); + this.kibanaUrls.push(url); + return url; + } + resolveUrl(relativeUrl = '/') { + return url_1.default.resolve(this.pickUrl(), relativeUrl); + } + async request(options) { + var _a; + const url = url_1.default.resolve(this.pickUrl(), options.path); + const description = options.description || `${options.method} ${url}`; + let attempt = 0; + const maxAttempts = (_a = options.retries, (_a !== null && _a !== void 0 ? _a : DEFAULT_MAX_ATTEMPTS)); + while (true) { + attempt += 1; + try { + const response = await axios_1.default.request({ + method: options.method, + url, + data: options.body, + params: options.query, + headers: { + 'kbn-xsrf': 'kbn-client', + }, + }); + return response.data; + } + catch (error) { + const conflictOnGet = isConcliftOnGetError(error); + const requestedRetries = options.retries !== undefined; + const failedToGetResponse = axios_2.isAxiosRequestError(error); + let errorMessage; + if (conflictOnGet) { + errorMessage = `Conflict on GET (path=${options.path}, attempt=${attempt}/${maxAttempts})`; + this.log.error(errorMessage); + } + else if (requestedRetries || failedToGetResponse) { + errorMessage = `[${description}] request failed (attempt=${attempt}/${maxAttempts})`; + this.log.error(errorMessage); + } + else { + throw error; + } + if (attempt < maxAttempts) { + await delay(1000 * attempt); + continue; + } + throw new Error(`${errorMessage} -- and ran out of retries`); + } + } + } +} +exports.KbnClientRequester = KbnClientRequester; /***/ }), -/* 469 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var isAbsoluteURL = __webpack_require__(470); -var combineURLs = __webpack_require__(471); - -/** - * Creates a new URL by combining the baseURL with the requestedURL, - * only when the requestedURL is not already an absolute URL. - * If the requestURL is absolute, this function returns the requestedURL untouched. - * - * @param {string} baseURL The base URL - * @param {string} requestedURL Absolute or relative URL to combine - * @returns {string} The combined full path - */ -module.exports = function buildFullPath(baseURL, requestedURL) { - if (baseURL && !isAbsoluteURL(requestedURL)) { - return combineURLs(baseURL, requestedURL); - } - return requestedURL; -}; +/* 439 */ +/***/ (function(module, exports) { +module.exports = require("url"); /***/ }), -/* 470 */ +/* 440 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - - -/** - * Determines whether the specified URL is absolute - * - * @param {string} url The URL to test - * @returns {boolean} True if the specified URL is absolute, otherwise false - */ -module.exports = function isAbsoluteURL(url) { - // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). - // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed - // by any combination of letters, digits, plus, period, or hyphen. - return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); -}; - +module.exports = __webpack_require__(441); /***/ }), -/* 471 */ +/* 441 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +var utils = __webpack_require__(442); +var bind = __webpack_require__(443); +var Axios = __webpack_require__(444); +var mergeConfig = __webpack_require__(475); +var defaults = __webpack_require__(450); + /** - * Creates a new URL by combining the specified URLs + * Create an instance of Axios * - * @param {string} baseURL The base URL - * @param {string} relativeURL The relative URL - * @returns {string} The combined URL + * @param {Object} defaultConfig The default config for the instance + * @return {Axios} A new instance of Axios */ -module.exports = function combineURLs(baseURL, relativeURL) { - return relativeURL - ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') - : baseURL; -}; - +function createInstance(defaultConfig) { + var context = new Axios(defaultConfig); + var instance = bind(Axios.prototype.request, context); -/***/ }), -/* 472 */ -/***/ (function(module, exports, __webpack_require__) { + // Copy axios.prototype to instance + utils.extend(instance, Axios.prototype, context); -"use strict"; + // Copy context to instance + utils.extend(instance, context); + return instance; +} -var utils = __webpack_require__(455); +// Create the default instance to be exported +var axios = createInstance(defaults); -// Headers whose duplicates are ignored by node -// c.f. https://nodejs.org/api/http.html#http_message_headers -var ignoreDuplicateOf = [ - 'age', 'authorization', 'content-length', 'content-type', 'etag', - 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', - 'last-modified', 'location', 'max-forwards', 'proxy-authorization', - 'referer', 'retry-after', 'user-agent' -]; +// Expose Axios class to allow class inheritance +axios.Axios = Axios; -/** - * Parse headers into an object - * - * ``` - * Date: Wed, 27 Aug 2014 08:58:49 GMT - * Content-Type: application/json - * Connection: keep-alive - * Transfer-Encoding: chunked - * ``` - * - * @param {String} headers Headers needing to be parsed - * @returns {Object} Headers parsed into an object - */ -module.exports = function parseHeaders(headers) { - var parsed = {}; - var key; - var val; - var i; +// Factory for creating new instances +axios.create = function create(instanceConfig) { + return createInstance(mergeConfig(axios.defaults, instanceConfig)); +}; - if (!headers) { return parsed; } +// Expose Cancel & CancelToken +axios.Cancel = __webpack_require__(476); +axios.CancelToken = __webpack_require__(477); +axios.isCancel = __webpack_require__(449); - utils.forEach(headers.split('\n'), function parser(line) { - i = line.indexOf(':'); - key = utils.trim(line.substr(0, i)).toLowerCase(); - val = utils.trim(line.substr(i + 1)); +// Expose all/spread +axios.all = function all(promises) { + return Promise.all(promises); +}; +axios.spread = __webpack_require__(478); - if (key) { - if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { - return; - } - if (key === 'set-cookie') { - parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); - } else { - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; - } - } - }); +module.exports = axios; - return parsed; -}; +// Allow use of default import syntax in TypeScript +module.exports.default = axios; /***/ }), -/* 473 */ +/* 442 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var utils = __webpack_require__(455); +var bind = __webpack_require__(443); -module.exports = ( - utils.isStandardBrowserEnv() ? +/*global toString:true*/ - // Standard browser envs have full support of the APIs needed to test - // whether the request URL is of the same origin as current location. - (function standardBrowserEnv() { - var msie = /(msie|trident)/i.test(navigator.userAgent); - var urlParsingNode = document.createElement('a'); - var originURL; +// utils is a library of generic helper functions non-specific to axios - /** - * Parse a URL to discover it's components - * - * @param {String} url The URL to be parsed - * @returns {Object} - */ - function resolveURL(url) { - var href = url; +var toString = Object.prototype.toString; - if (msie) { - // IE needs attribute set twice to normalize properties - urlParsingNode.setAttribute('href', href); - href = urlParsingNode.href; - } +/** + * Determine if a value is an Array + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Array, otherwise false + */ +function isArray(val) { + return toString.call(val) === '[object Array]'; +} - urlParsingNode.setAttribute('href', href); +/** + * Determine if a value is undefined + * + * @param {Object} val The value to test + * @returns {boolean} True if the value is undefined, otherwise false + */ +function isUndefined(val) { + return typeof val === 'undefined'; +} - // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils - return { - href: urlParsingNode.href, - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', - host: urlParsingNode.host, - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', - hostname: urlParsingNode.hostname, - port: urlParsingNode.port, - pathname: (urlParsingNode.pathname.charAt(0) === '/') ? - urlParsingNode.pathname : - '/' + urlParsingNode.pathname - }; - } +/** + * Determine if a value is a Buffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Buffer, otherwise false + */ +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); +} - originURL = resolveURL(window.location.href); +/** + * Determine if a value is an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ +function isArrayBuffer(val) { + return toString.call(val) === '[object ArrayBuffer]'; +} - /** - * Determine if a URL shares the same origin as the current location - * - * @param {String} requestURL The URL to test - * @returns {boolean} True if URL shares the same origin, otherwise false - */ - return function isURLSameOrigin(requestURL) { - var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; - return (parsed.protocol === originURL.protocol && - parsed.host === originURL.host); - }; - })() : +/** + * Determine if a value is a FormData + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an FormData, otherwise false + */ +function isFormData(val) { + return (typeof FormData !== 'undefined') && (val instanceof FormData); +} - // Non standard browser envs (web workers, react-native) lack needed support. - (function nonStandardBrowserEnv() { - return function isURLSameOrigin() { - return true; - }; - })() -); +/** + * Determine if a value is a view on an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ +function isArrayBufferView(val) { + var result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); + } + return result; +} +/** + * Determine if a value is a String + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a String, otherwise false + */ +function isString(val) { + return typeof val === 'string'; +} -/***/ }), -/* 474 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Determine if a value is a Number + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Number, otherwise false + */ +function isNumber(val) { + return typeof val === 'number'; +} -"use strict"; +/** + * Determine if a value is an Object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Object, otherwise false + */ +function isObject(val) { + return val !== null && typeof val === 'object'; +} +/** + * Determine if a value is a Date + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Date, otherwise false + */ +function isDate(val) { + return toString.call(val) === '[object Date]'; +} -var utils = __webpack_require__(455); +/** + * Determine if a value is a File + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a File, otherwise false + */ +function isFile(val) { + return toString.call(val) === '[object File]'; +} -module.exports = ( - utils.isStandardBrowserEnv() ? +/** + * Determine if a value is a Blob + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Blob, otherwise false + */ +function isBlob(val) { + return toString.call(val) === '[object Blob]'; +} - // Standard browser envs support document.cookie - (function standardBrowserEnv() { - return { - write: function write(name, value, expires, path, domain, secure) { - var cookie = []; - cookie.push(name + '=' + encodeURIComponent(value)); +/** + * Determine if a value is a Function + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ +function isFunction(val) { + return toString.call(val) === '[object Function]'; +} - if (utils.isNumber(expires)) { - cookie.push('expires=' + new Date(expires).toGMTString()); - } +/** + * Determine if a value is a Stream + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Stream, otherwise false + */ +function isStream(val) { + return isObject(val) && isFunction(val.pipe); +} - if (utils.isString(path)) { - cookie.push('path=' + path); - } +/** + * Determine if a value is a URLSearchParams object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ +function isURLSearchParams(val) { + return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; +} - if (utils.isString(domain)) { - cookie.push('domain=' + domain); - } +/** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * @returns {String} The String freed of excess whitespace + */ +function trim(str) { + return str.replace(/^\s*/, '').replace(/\s*$/, ''); +} - if (secure === true) { - cookie.push('secure'); - } +/** + * Determine if we're running in a standard browser environment + * + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + * nativescript + * navigator.product -> 'NativeScript' or 'NS' + */ +function isStandardBrowserEnv() { + if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || + navigator.product === 'NativeScript' || + navigator.product === 'NS')) { + return false; + } + return ( + typeof window !== 'undefined' && + typeof document !== 'undefined' + ); +} - document.cookie = cookie.join('; '); - }, +/** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + */ +function forEach(obj, fn) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } - read: function read(name) { - var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); - return (match ? decodeURIComponent(match[3]) : null); - }, + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } - remove: function remove(name) { - this.write(name, '', Date.now() - 86400000); - } - }; - })() : + if (isArray(obj)) { + // Iterate over array values + for (var i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn.call(null, obj[key], key, obj); + } + } + } +} - // Non standard browser env (web workers, react-native) lack needed support. - (function nonStandardBrowserEnv() { - return { - write: function write() {}, - read: function read() { return null; }, - remove: function remove() {} - }; - })() -); +/** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * @returns {Object} Result of all merge properties + */ +function merge(/* obj1, obj2, obj3, ... */) { + var result = {}; + function assignValue(val, key) { + if (typeof result[key] === 'object' && typeof val === 'object') { + result[key] = merge(result[key], val); + } else { + result[key] = val; + } + } + + for (var i = 0, l = arguments.length; i < l; i++) { + forEach(arguments[i], assignValue); + } + return result; +} + +/** + * Function equal to merge with the difference being that no reference + * to original objects is kept. + * + * @see merge + * @param {Object} obj1 Object to merge + * @returns {Object} Result of all merge properties + */ +function deepMerge(/* obj1, obj2, obj3, ... */) { + var result = {}; + function assignValue(val, key) { + if (typeof result[key] === 'object' && typeof val === 'object') { + result[key] = deepMerge(result[key], val); + } else if (typeof val === 'object') { + result[key] = deepMerge({}, val); + } else { + result[key] = val; + } + } + + for (var i = 0, l = arguments.length; i < l; i++) { + forEach(arguments[i], assignValue); + } + return result; +} + +/** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * @return {Object} The resulting value of object a + */ +function extend(a, b, thisArg) { + forEach(b, function assignValue(val, key) { + if (thisArg && typeof val === 'function') { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }); + return a; +} + +module.exports = { + isArray: isArray, + isArrayBuffer: isArrayBuffer, + isBuffer: isBuffer, + isFormData: isFormData, + isArrayBufferView: isArrayBufferView, + isString: isString, + isNumber: isNumber, + isObject: isObject, + isUndefined: isUndefined, + isDate: isDate, + isFile: isFile, + isBlob: isBlob, + isFunction: isFunction, + isStream: isStream, + isURLSearchParams: isURLSearchParams, + isStandardBrowserEnv: isStandardBrowserEnv, + forEach: forEach, + merge: merge, + deepMerge: deepMerge, + extend: extend, + trim: trim +}; /***/ }), -/* 475 */ +/* 443 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var utils = __webpack_require__(455); -var settle = __webpack_require__(466); -var buildFullPath = __webpack_require__(469); -var buildURL = __webpack_require__(458); -var http = __webpack_require__(476); -var https = __webpack_require__(477); -var httpFollow = __webpack_require__(478).http; -var httpsFollow = __webpack_require__(478).https; -var url = __webpack_require__(452); -var zlib = __webpack_require__(486); -var pkg = __webpack_require__(487); -var createError = __webpack_require__(467); -var enhanceError = __webpack_require__(468); +module.exports = function bind(fn, thisArg) { + return function wrap() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + return fn.apply(thisArg, args); + }; +}; -var isHttps = /https:?/; -/*eslint consistent-return:0*/ -module.exports = function httpAdapter(config) { - return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) { - var resolve = function resolve(value) { - resolvePromise(value); - }; - var reject = function reject(value) { - rejectPromise(value); - }; - var data = config.data; - var headers = config.headers; +/***/ }), +/* 444 */ +/***/ (function(module, exports, __webpack_require__) { - // Set User-Agent (required by some servers) - // Only set header if it hasn't been set in config - // See https://github.com/axios/axios/issues/69 - if (!headers['User-Agent'] && !headers['user-agent']) { - headers['User-Agent'] = 'axios/' + pkg.version; - } +"use strict"; - if (data && !utils.isStream(data)) { - if (Buffer.isBuffer(data)) { - // Nothing to do... - } else if (utils.isArrayBuffer(data)) { - data = Buffer.from(new Uint8Array(data)); - } else if (utils.isString(data)) { - data = Buffer.from(data, 'utf-8'); - } else { - return reject(createError( - 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', - config - )); - } - // Add Content-Length header if data exists - headers['Content-Length'] = data.length; - } +var utils = __webpack_require__(442); +var buildURL = __webpack_require__(445); +var InterceptorManager = __webpack_require__(446); +var dispatchRequest = __webpack_require__(447); +var mergeConfig = __webpack_require__(475); - // HTTP basic authentication - var auth = undefined; - if (config.auth) { - var username = config.auth.username || ''; - var password = config.auth.password || ''; - auth = username + ':' + password; - } +/** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + */ +function Axios(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager(), + response: new InterceptorManager() + }; +} - // Parse url - var fullPath = buildFullPath(config.baseURL, config.url); - var parsed = url.parse(fullPath); - var protocol = parsed.protocol || 'http:'; +/** + * Dispatch a request + * + * @param {Object} config The config specific for this request (merged with this.defaults) + */ +Axios.prototype.request = function request(config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof config === 'string') { + config = arguments[1] || {}; + config.url = arguments[0]; + } else { + config = config || {}; + } - if (!auth && parsed.auth) { - var urlAuth = parsed.auth.split(':'); - var urlUsername = urlAuth[0] || ''; - var urlPassword = urlAuth[1] || ''; - auth = urlUsername + ':' + urlPassword; - } + config = mergeConfig(this.defaults, config); - if (auth) { - delete headers.Authorization; - } + // Set config.method + if (config.method) { + config.method = config.method.toLowerCase(); + } else if (this.defaults.method) { + config.method = this.defaults.method.toLowerCase(); + } else { + config.method = 'get'; + } - var isHttpsRequest = isHttps.test(protocol); - var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; + // Hook up interceptors middleware + var chain = [dispatchRequest, undefined]; + var promise = Promise.resolve(config); - var options = { - path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''), - method: config.method.toUpperCase(), - headers: headers, - agent: agent, - agents: { http: config.httpAgent, https: config.httpsAgent }, - auth: auth - }; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + chain.unshift(interceptor.fulfilled, interceptor.rejected); + }); - if (config.socketPath) { - options.socketPath = config.socketPath; - } else { - options.hostname = parsed.hostname; - options.port = parsed.port; - } + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + chain.push(interceptor.fulfilled, interceptor.rejected); + }); - var proxy = config.proxy; - if (!proxy && proxy !== false) { - var proxyEnv = protocol.slice(0, -1) + '_proxy'; - var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()]; - if (proxyUrl) { - var parsedProxyUrl = url.parse(proxyUrl); - var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY; - var shouldProxy = true; + while (chain.length) { + promise = promise.then(chain.shift(), chain.shift()); + } - if (noProxyEnv) { - var noProxy = noProxyEnv.split(',').map(function trim(s) { - return s.trim(); - }); + return promise; +}; - shouldProxy = !noProxy.some(function proxyMatch(proxyElement) { - if (!proxyElement) { - return false; - } - if (proxyElement === '*') { - return true; - } - if (proxyElement[0] === '.' && - parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) { - return true; - } +Axios.prototype.getUri = function getUri(config) { + config = mergeConfig(this.defaults, config); + return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); +}; - return parsed.hostname === proxyElement; - }); - } +// Provide aliases for supported request methods +utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(utils.merge(config || {}, { + method: method, + url: url + })); + }; +}); +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, data, config) { + return this.request(utils.merge(config || {}, { + method: method, + url: url, + data: data + })); + }; +}); - if (shouldProxy) { - proxy = { - host: parsedProxyUrl.hostname, - port: parsedProxyUrl.port - }; +module.exports = Axios; - if (parsedProxyUrl.auth) { - var proxyUrlAuth = parsedProxyUrl.auth.split(':'); - proxy.auth = { - username: proxyUrlAuth[0], - password: proxyUrlAuth[1] - }; - } - } - } - } - if (proxy) { - options.hostname = proxy.host; - options.host = proxy.host; - options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : ''); - options.port = proxy.port; - options.path = protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path; +/***/ }), +/* 445 */ +/***/ (function(module, exports, __webpack_require__) { - // Basic proxy authorization - if (proxy.auth) { - var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64'); - options.headers['Proxy-Authorization'] = 'Basic ' + base64; - } - } +"use strict"; - var transport; - var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true); - if (config.transport) { - transport = config.transport; - } else if (config.maxRedirects === 0) { - transport = isHttpsProxy ? https : http; - } else { - if (config.maxRedirects) { - options.maxRedirects = config.maxRedirects; - } - transport = isHttpsProxy ? httpsFollow : httpFollow; - } - if (config.maxContentLength && config.maxContentLength > -1) { - options.maxBodyLength = config.maxContentLength; - } +var utils = __webpack_require__(442); - // Create the request - var req = transport.request(options, function handleResponse(res) { - if (req.aborted) return; +function encode(val) { + return encodeURIComponent(val). + replace(/%40/gi, '@'). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, '+'). + replace(/%5B/gi, '['). + replace(/%5D/gi, ']'); +} - // uncompress the response body transparently if required - var stream = res; - switch (res.headers['content-encoding']) { - /*eslint default-case:0*/ - case 'gzip': - case 'compress': - case 'deflate': - // add the unzipper to the body stream processing pipeline - stream = (res.statusCode === 204) ? stream : stream.pipe(zlib.createUnzip()); +/** + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @returns {string} The formatted url + */ +module.exports = function buildURL(url, params, paramsSerializer) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } - // remove the content-encoding in order to not confuse downstream operations - delete res.headers['content-encoding']; - break; + var serializedParams; + if (paramsSerializer) { + serializedParams = paramsSerializer(params); + } else if (utils.isURLSearchParams(params)) { + serializedParams = params.toString(); + } else { + var parts = []; + + utils.forEach(params, function serialize(val, key) { + if (val === null || typeof val === 'undefined') { + return; } - // return the last request in case of redirects - var lastRequest = res.req || req; + if (utils.isArray(val)) { + key = key + '[]'; + } else { + val = [val]; + } - var response = { - status: res.statusCode, - statusText: res.statusMessage, - headers: res.headers, - config: config, - request: lastRequest - }; + utils.forEach(val, function parseValue(v) { + if (utils.isDate(v)) { + v = v.toISOString(); + } else if (utils.isObject(v)) { + v = JSON.stringify(v); + } + parts.push(encode(key) + '=' + encode(v)); + }); + }); - if (config.responseType === 'stream') { - response.data = stream; - settle(resolve, reject, response); - } else { - var responseBuffer = []; - stream.on('data', function handleStreamData(chunk) { - responseBuffer.push(chunk); + serializedParams = parts.join('&'); + } - // make sure the content length is not over the maxContentLength if specified - if (config.maxContentLength > -1 && Buffer.concat(responseBuffer).length > config.maxContentLength) { - stream.destroy(); - reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded', - config, null, lastRequest)); - } - }); + if (serializedParams) { + var hashmarkIndex = url.indexOf('#'); + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } - stream.on('error', function handleStreamError(err) { - if (req.aborted) return; - reject(enhanceError(err, config, null, lastRequest)); - }); + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } - stream.on('end', function handleStreamEnd() { - var responseData = Buffer.concat(responseBuffer); - if (config.responseType !== 'arraybuffer') { - responseData = responseData.toString(config.responseEncoding); - } + return url; +}; - response.data = responseData; - settle(resolve, reject, response); - }); - } - }); - // Handle errors - req.on('error', function handleRequestError(err) { - if (req.aborted) return; - reject(enhanceError(err, config, null, req)); - }); +/***/ }), +/* 446 */ +/***/ (function(module, exports, __webpack_require__) { - // Handle request timeout - if (config.timeout) { - // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. - // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. - // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. - // And then these socket which be hang up will devoring CPU little by little. - // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. - req.setTimeout(config.timeout, function handleRequestTimeout() { - req.abort(); - reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', req)); - }); - } +"use strict"; - if (config.cancelToken) { - // Handle cancellation - config.cancelToken.promise.then(function onCanceled(cancel) { - if (req.aborted) return; - req.abort(); - reject(cancel); - }); - } +var utils = __webpack_require__(442); - // Send the request - if (utils.isStream(data)) { - data.on('error', function handleStreamError(err) { - reject(enhanceError(err, config, null, req)); - }).pipe(req); - } else { - req.end(data); - } +function InterceptorManager() { + this.handlers = []; +} + +/** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ +InterceptorManager.prototype.use = function use(fulfilled, rejected) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected }); + return this.handlers.length - 1; }; +/** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + */ +InterceptorManager.prototype.eject = function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } +}; -/***/ }), -/* 476 */ -/***/ (function(module, exports) { - -module.exports = require("http"); +/** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + */ +InterceptorManager.prototype.forEach = function forEach(fn) { + utils.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); +}; -/***/ }), -/* 477 */ -/***/ (function(module, exports) { +module.exports = InterceptorManager; -module.exports = require("https"); /***/ }), -/* 478 */ +/* 447 */ /***/ (function(module, exports, __webpack_require__) { -var url = __webpack_require__(452); -var http = __webpack_require__(476); -var https = __webpack_require__(477); -var assert = __webpack_require__(30); -var Writable = __webpack_require__(27).Writable; -var debug = __webpack_require__(479)("follow-redirects"); - -// RFC7231§4.2.1: Of the request methods defined by this specification, -// the GET, HEAD, OPTIONS, and TRACE methods are defined to be safe. -var SAFE_METHODS = { GET: true, HEAD: true, OPTIONS: true, TRACE: true }; +"use strict"; -// Create handlers that pass events from native requests -var eventHandlers = Object.create(null); -["abort", "aborted", "error", "socket", "timeout"].forEach(function (event) { - eventHandlers[event] = function (arg) { - this._redirectable.emit(event, arg); - }; -}); -// An HTTP(S) request that can be redirected -function RedirectableRequest(options, responseCallback) { - // Initialize the request - Writable.call(this); - options.headers = options.headers || {}; - this._options = options; - this._redirectCount = 0; - this._redirects = []; - this._requestBodyLength = 0; - this._requestBodyBuffers = []; +var utils = __webpack_require__(442); +var transformData = __webpack_require__(448); +var isCancel = __webpack_require__(449); +var defaults = __webpack_require__(450); - // Since http.request treats host as an alias of hostname, - // but the url module interprets host as hostname plus port, - // eliminate the host property to avoid confusion. - if (options.host) { - // Use hostname if set, because it has precedence - if (!options.hostname) { - options.hostname = options.host; - } - delete options.host; +/** + * Throws a `Cancel` if cancellation has been requested. + */ +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); } +} - // Attach a callback if passed - if (responseCallback) { - this.on("response", responseCallback); - } +/** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * @returns {Promise} The Promise to be fulfilled + */ +module.exports = function dispatchRequest(config) { + throwIfCancellationRequested(config); - // React to responses of native requests - var self = this; - this._onNativeResponse = function (response) { - self._processResponse(response); - }; + // Ensure headers exist + config.headers = config.headers || {}; - // Complete the URL object when necessary - if (!options.pathname && options.path) { - var searchPos = options.path.indexOf("?"); - if (searchPos < 0) { - options.pathname = options.path; - } - else { - options.pathname = options.path.substring(0, searchPos); - options.search = options.path.substring(searchPos); + // Transform request data + config.data = transformData( + config.data, + config.headers, + config.transformRequest + ); + + // Flatten headers + config.headers = utils.merge( + config.headers.common || {}, + config.headers[config.method] || {}, + config.headers + ); + + utils.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + function cleanHeaderConfig(method) { + delete config.headers[method]; } - } + ); - // Perform the first request - this._performRequest(); -} -RedirectableRequest.prototype = Object.create(Writable.prototype); + var adapter = config.adapter || defaults.adapter; -// Writes buffered data to the current native request -RedirectableRequest.prototype.write = function (data, encoding, callback) { - // Validate input and shift parameters if necessary - if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { - throw new Error("data should be a string, Buffer or Uint8Array"); - } - if (typeof encoding === "function") { - callback = encoding; - encoding = null; - } + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); - // Ignore empty buffers, since writing them doesn't invoke the callback - // https://github.com/nodejs/node/issues/22066 - if (data.length === 0) { - if (callback) { - callback(); - } - return; - } - // Only write when we don't exceed the maximum body length - if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { - this._requestBodyLength += data.length; - this._requestBodyBuffers.push({ data: data, encoding: encoding }); - this._currentRequest.write(data, encoding, callback); - } - // Error when we exceed the maximum body length - else { - this.emit("error", new Error("Request body larger than maxBodyLength limit")); - this.abort(); - } -}; + // Transform response data + response.data = transformData( + response.data, + response.headers, + config.transformResponse + ); -// Ends the current native request -RedirectableRequest.prototype.end = function (data, encoding, callback) { - // Shift parameters if necessary - if (typeof data === "function") { - callback = data; - data = encoding = null; - } - else if (typeof encoding === "function") { - callback = encoding; - encoding = null; - } + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); - // Write data and end - var currentRequest = this._currentRequest; - this.write(data || "", encoding, function () { - currentRequest.end(null, null, callback); + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData( + reason.response.data, + reason.response.headers, + config.transformResponse + ); + } + } + + return Promise.reject(reason); }); }; -// Sets a header value on the current native request -RedirectableRequest.prototype.setHeader = function (name, value) { - this._options.headers[name] = value; - this._currentRequest.setHeader(name, value); -}; -// Clears a header value on the current native request -RedirectableRequest.prototype.removeHeader = function (name) { - delete this._options.headers[name]; - this._currentRequest.removeHeader(name); -}; +/***/ }), +/* 448 */ +/***/ (function(module, exports, __webpack_require__) { -// Proxy all other public ClientRequest methods -[ - "abort", "flushHeaders", "getHeader", - "setNoDelay", "setSocketKeepAlive", "setTimeout", -].forEach(function (method) { - RedirectableRequest.prototype[method] = function (a, b) { - return this._currentRequest[method](a, b); - }; -}); +"use strict"; -// Proxy all public ClientRequest properties -["aborted", "connection", "socket"].forEach(function (property) { - Object.defineProperty(RedirectableRequest.prototype, property, { - get: function () { return this._currentRequest[property]; }, - }); -}); -// Executes the next native request (initial or redirect) -RedirectableRequest.prototype._performRequest = function () { - // Load the native protocol - var protocol = this._options.protocol; - var nativeProtocol = this._options.nativeProtocols[protocol]; - if (!nativeProtocol) { - this.emit("error", new Error("Unsupported protocol " + protocol)); - return; - } - - // If specified, use the agent corresponding to the protocol - // (HTTP and HTTPS use different types of agents) - if (this._options.agents) { - var scheme = protocol.substr(0, protocol.length - 1); - this._options.agent = this._options.agents[scheme]; - } - - // Create the native request - var request = this._currentRequest = - nativeProtocol.request(this._options, this._onNativeResponse); - this._currentUrl = url.format(this._options); +var utils = __webpack_require__(442); - // Set up event handlers - request._redirectable = this; - for (var event in eventHandlers) { - /* istanbul ignore else */ - if (event) { - request.on(event, eventHandlers[event]); - } - } +/** + * Transform the data for a request or a response + * + * @param {Object|String} data The data to be transformed + * @param {Array} headers The headers for the request or response + * @param {Array|Function} fns A single function or Array of functions + * @returns {*} The resulting transformed data + */ +module.exports = function transformData(data, headers, fns) { + /*eslint no-param-reassign:0*/ + utils.forEach(fns, function transform(fn) { + data = fn(data, headers); + }); - // End a redirected request - // (The first request must be ended explicitly with RedirectableRequest#end) - if (this._isRedirect) { - // Write the request entity and end. - var i = 0; - var buffers = this._requestBodyBuffers; - (function writeNext() { - if (i < buffers.length) { - var buffer = buffers[i++]; - request.write(buffer.data, buffer.encoding, writeNext); - } - else { - request.end(); - } - }()); - } + return data; }; -// Processes a response from the current native request -RedirectableRequest.prototype._processResponse = function (response) { - // Store the redirected response - if (this._options.trackRedirects) { - this._redirects.push({ - url: this._currentUrl, - headers: response.headers, - statusCode: response.statusCode, - }); - } - - // RFC7231§6.4: The 3xx (Redirection) class of status code indicates - // that further action needs to be taken by the user agent in order to - // fulfill the request. If a Location header field is provided, - // the user agent MAY automatically redirect its request to the URI - // referenced by the Location field value, - // even if the specific status code is not understood. - var location = response.headers.location; - if (location && this._options.followRedirects !== false && - response.statusCode >= 300 && response.statusCode < 400) { - // RFC7231§6.4: A client SHOULD detect and intervene - // in cyclical redirections (i.e., "infinite" redirection loops). - if (++this._redirectCount > this._options.maxRedirects) { - this.emit("error", new Error("Max redirects exceeded.")); - return; - } - - // RFC7231§6.4: Automatic redirection needs to done with - // care for methods not known to be safe […], - // since the user might not wish to redirect an unsafe request. - // RFC7231§6.4.7: The 307 (Temporary Redirect) status code indicates - // that the target resource resides temporarily under a different URI - // and the user agent MUST NOT change the request method - // if it performs an automatic redirection to that URI. - var header; - var headers = this._options.headers; - if (response.statusCode !== 307 && !(this._options.method in SAFE_METHODS)) { - this._options.method = "GET"; - // Drop a possible entity and headers related to it - this._requestBodyBuffers = []; - for (header in headers) { - if (/^content-/i.test(header)) { - delete headers[header]; - } - } - } - // Drop the Host header, as the redirect might lead to a different host - if (!this._isRedirect) { - for (header in headers) { - if (/^host$/i.test(header)) { - delete headers[header]; - } - } - } +/***/ }), +/* 449 */ +/***/ (function(module, exports, __webpack_require__) { - // Perform the redirected request - var redirectUrl = url.resolve(this._currentUrl, location); - debug("redirecting to", redirectUrl); - Object.assign(this._options, url.parse(redirectUrl)); - this._isRedirect = true; - this._performRequest(); +"use strict"; - // Discard the remainder of the response to avoid waiting for data - response.destroy(); - } - else { - // The response is not a redirect; return it as-is - response.responseUrl = this._currentUrl; - response.redirects = this._redirects; - this.emit("response", response); - // Clean up - this._requestBodyBuffers = []; - } +module.exports = function isCancel(value) { + return !!(value && value.__CANCEL__); }; -// Wraps the key/value object of protocols with redirect functionality -function wrap(protocols) { - // Default settings - var exports = { - maxRedirects: 21, - maxBodyLength: 10 * 1024 * 1024, - }; - - // Wrap each protocol - var nativeProtocols = {}; - Object.keys(protocols).forEach(function (scheme) { - var protocol = scheme + ":"; - var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; - var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); - - // Executes a request, following redirects - wrappedProtocol.request = function (options, callback) { - if (typeof options === "string") { - options = url.parse(options); - options.maxRedirects = exports.maxRedirects; - } - else { - options = Object.assign({ - protocol: protocol, - maxRedirects: exports.maxRedirects, - maxBodyLength: exports.maxBodyLength, - }, options); - } - options.nativeProtocols = nativeProtocols; - assert.equal(options.protocol, protocol, "protocol mismatch"); - debug("options", options); - return new RedirectableRequest(options, callback); - }; - // Executes a GET request, following redirects - wrappedProtocol.get = function (options, callback) { - var request = wrappedProtocol.request(options, callback); - request.end(); - return request; - }; - }); - return exports; -} +/***/ }), +/* 450 */ +/***/ (function(module, exports, __webpack_require__) { -// Exports -module.exports = wrap({ http: http, https: https }); -module.exports.wrap = wrap; +"use strict"; -/***/ }), -/* 479 */ -/***/ (function(module, exports, __webpack_require__) { +var utils = __webpack_require__(442); +var normalizeHeaderName = __webpack_require__(451); -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ +var DEFAULT_CONTENT_TYPE = { + 'Content-Type': 'application/x-www-form-urlencoded' +}; -if (typeof process === 'undefined' || process.type === 'renderer') { - module.exports = __webpack_require__(480); -} else { - module.exports = __webpack_require__(483); +function setContentTypeIfUnset(headers, value) { + if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { + headers['Content-Type'] = value; + } } +function getDefaultAdapter() { + var adapter; + if (typeof XMLHttpRequest !== 'undefined') { + // For browsers use XHR adapter + adapter = __webpack_require__(452); + } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { + // For node use HTTP adapter + adapter = __webpack_require__(462); + } + return adapter; +} -/***/ }), -/* 480 */ -/***/ (function(module, exports, __webpack_require__) { +var defaults = { + adapter: getDefaultAdapter(), -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ + transformRequest: [function transformRequest(data, headers) { + normalizeHeaderName(headers, 'Accept'); + normalizeHeaderName(headers, 'Content-Type'); + if (utils.isFormData(data) || + utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) + ) { + return data; + } + if (utils.isArrayBufferView(data)) { + return data.buffer; + } + if (utils.isURLSearchParams(data)) { + setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); + return data.toString(); + } + if (utils.isObject(data)) { + setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); + return JSON.stringify(data); + } + return data; + }], -exports = module.exports = __webpack_require__(481); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); + transformResponse: [function transformResponse(data) { + /*eslint no-param-reassign:0*/ + if (typeof data === 'string') { + try { + data = JSON.parse(data); + } catch (e) { /* Ignore */ } + } + return data; + }], -/** - * Colors. - */ + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, -exports.colors = [ - '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', - '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', - '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', - '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', - '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', - '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', - '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', - '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', - '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', - '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', - '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' -]; + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ + maxContentLength: -1, -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; } +}; - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; +defaults.headers = { + common: { + 'Accept': 'application/json, text/plain, */*' } +}; - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ +utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { + defaults.headers[method] = {}; +}); -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); +}); +module.exports = defaults; -/** - * Colorize log arguments if enabled. - * - * @api public - */ -function formatArgs(args) { - var useColors = this.useColors; +/***/ }), +/* 451 */ +/***/ (function(module, exports, __webpack_require__) { - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); +"use strict"; - if (!useColors) return; - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') +var utils = __webpack_require__(442); - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; +module.exports = function normalizeHeaderName(headers, normalizedName) { + utils.forEach(headers, function processHeader(value, name) { + if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { + headers[normalizedName] = value; + delete headers[name]; } }); +}; - args.splice(lastC, 0, c); -} -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ +/***/ }), +/* 452 */ +/***/ (function(module, exports, __webpack_require__) { -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} +"use strict"; -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} -} +var utils = __webpack_require__(442); +var settle = __webpack_require__(453); +var buildURL = __webpack_require__(445); +var buildFullPath = __webpack_require__(456); +var parseHeaders = __webpack_require__(459); +var isURLSameOrigin = __webpack_require__(460); +var createError = __webpack_require__(454); -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ +module.exports = function xhrAdapter(config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + var requestData = config.data; + var requestHeaders = config.headers; -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} + if (utils.isFormData(requestData)) { + delete requestHeaders['Content-Type']; // Let the browser set it + } - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } + var request = new XMLHttpRequest(); - return r; -} + // HTTP basic authentication + if (config.auth) { + var username = config.auth.username || ''; + var password = config.auth.password || ''; + requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); + } -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ + var fullPath = buildFullPath(config.baseURL, config.url); + request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); -exports.enable(load()); + // Set the request timeout in MS + request.timeout = config.timeout; -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ + // Listen for ready state + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } + // Prepare the response + var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; + var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; + var response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config: config, + request: request + }; -/***/ }), -/* 481 */ -/***/ (function(module, exports, __webpack_require__) { + settle(resolve, reject, response); + // Clean up request + request = null; + }; -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = __webpack_require__(482); + reject(createError('Request aborted', config, 'ECONNABORTED', request)); -/** - * Active `debug` instances. - */ -exports.instances = []; - -/** - * The currently active debug mode names, and names to skip. - */ - -exports.names = []; -exports.skips = []; - -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - -exports.formatters = {}; - -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ + // Clean up request + request = null; + }; -function selectColor(namespace) { - var hash = 0, i; + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(createError('Network Error', config, null, request)); - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } + // Clean up request + request = null; + }; - return exports.colors[Math.abs(hash) % exports.colors.length]; -} + // Handle timeout + request.ontimeout = function handleTimeout() { + var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; + } + reject(createError(timeoutErrorMessage, config, 'ECONNABORTED', + request)); -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ + // Clean up request + request = null; + }; -function createDebug(namespace) { + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + if (utils.isStandardBrowserEnv()) { + var cookies = __webpack_require__(461); - var prevTime; + // Add xsrf header + var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? + cookies.read(config.xsrfCookieName) : + undefined; - function debug() { - // disabled? - if (!debug.enabled) return; + if (xsrfValue) { + requestHeaders[config.xsrfHeaderName] = xsrfValue; + } + } - var self = debug; + // Add headers to the request + if ('setRequestHeader' in request) { + utils.forEach(requestHeaders, function setRequestHeader(val, key) { + if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { + // Remove Content-Type if data is undefined + delete requestHeaders[key]; + } else { + // Otherwise add header to the request + request.setRequestHeader(key, val); + } + }); + } - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + // Add withCredentials to request if needed + if (!utils.isUndefined(config.withCredentials)) { + request.withCredentials = !!config.withCredentials; + } - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; + // Add responseType to request if needed + if (config.responseType) { + try { + request.responseType = config.responseType; + } catch (e) { + // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. + // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. + if (config.responseType !== 'json') { + throw e; + } + } } - args[0] = exports.coerce(args[0]); + // Handle progress if needed + if (typeof config.onDownloadProgress === 'function') { + request.addEventListener('progress', config.onDownloadProgress); + } - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); + // Not all browsers support upload events + if (typeof config.onUploadProgress === 'function' && request.upload) { + request.upload.addEventListener('progress', config.onUploadProgress); } - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); + if (config.cancelToken) { + // Handle cancellation + config.cancelToken.promise.then(function onCanceled(cancel) { + if (!request) { + return; + } - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + request.abort(); + reject(cancel); + // Clean up request + request = null; + }); + } - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); + if (requestData === undefined) { + requestData = null; + } - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } + // Send the request + request.send(requestData); + }); +}; - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); - debug.destroy = destroy; - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } +/***/ }), +/* 453 */ +/***/ (function(module, exports, __webpack_require__) { - exports.instances.push(debug); +"use strict"; - return debug; -} -function destroy () { - var index = exports.instances.indexOf(this); - if (index !== -1) { - exports.instances.splice(index, 1); - return true; - } else { - return false; - } -} +var createError = __webpack_require__(454); /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. + * Resolve or reject a Promise based on response status. * - * @param {String} namespaces - * @api public + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. */ +module.exports = function settle(resolve, reject, response) { + var validateStatus = response.config.validateStatus; + if (!validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(createError( + 'Request failed with status code ' + response.status, + response.config, + null, + response.request, + response + )); + } +}; -function enable(namespaces) { - exports.save(namespaces); - exports.names = []; - exports.skips = []; +/***/ }), +/* 454 */ +/***/ (function(module, exports, __webpack_require__) { - var i; - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; +"use strict"; - for (i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); - } - } - for (i = 0; i < exports.instances.length; i++) { - var instance = exports.instances[i]; - instance.enabled = exports.enabled(instance.namespace); - } -} +var enhanceError = __webpack_require__(455); /** - * Disable debug output. + * Create an Error with the specified message, config, error code, request and response. * - * @api public + * @param {string} message The error message. + * @param {Object} config The config. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The created error. */ +module.exports = function createError(message, config, code, request, response) { + var error = new Error(message); + return enhanceError(error, config, code, request, response); +}; -function disable() { - exports.enable(''); -} -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ +/***/ }), +/* 455 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; -function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } - } - return false; -} /** - * Coerce `val`. + * Update an Error with the specified config, error code, and response. * - * @param {Mixed} val - * @return {Mixed} - * @api private + * @param {Error} error The error to update. + * @param {Object} config The config. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The error. */ +module.exports = function enhanceError(error, config, code, request, response) { + error.config = config; + if (code) { + error.code = code; + } -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} + error.request = request; + error.response = response; + error.isAxiosError = true; + + error.toJSON = function() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: this.config, + code: this.code + }; + }; + return error; +}; /***/ }), -/* 482 */ -/***/ (function(module, exports) { +/* 456 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Helpers. - */ +"use strict"; -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; + +var isAbsoluteURL = __webpack_require__(457); +var combineURLs = __webpack_require__(458); /** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * @returns {string} The combined full path */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); +module.exports = function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); + return requestedURL; }; -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} +/***/ }), +/* 457 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +"use strict"; -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} /** - * Long format for `ms`. + * Determines whether the specified URL is absolute * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} - -/** - * Pluralization helper. + * @param {string} url The URL to test + * @returns {boolean} True if the specified URL is absolute, otherwise false */ - -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; - } - return Math.ceil(ms / n) + ' ' + name + 's'; -} +module.exports = function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); +}; /***/ }), -/* 483 */ +/* 458 */ /***/ (function(module, exports, __webpack_require__) { -/** - * Module dependencies. - */ +"use strict"; -var tty = __webpack_require__(484); -var util = __webpack_require__(29); /** - * This is the Node.js implementation of `debug()`. + * Creates a new URL by combining the specified URLs * - * Expose `debug()` as the module. - */ - -exports = module.exports = __webpack_require__(481); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; - -/** - * Colors. + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * @returns {string} The combined URL */ +module.exports = function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +}; -exports.colors = [ 6, 2, 3, 4, 5, 1 ]; -try { - var supportsColor = __webpack_require__(485); - if (supportsColor && supportsColor.level >= 2) { - exports.colors = [ - 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, - 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, - 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, - 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, - 205, 206, 207, 208, 209, 214, 215, 220, 221 - ]; - } -} catch (err) { - // swallow - we only care if `supports-color` is available; it doesn't have to be. -} +/***/ }), +/* 459 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ +"use strict"; -exports.inspectOpts = Object.keys(process.env).filter(function (key) { - return /^debug_/i.test(key); -}).reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === 'null') val = null; - else val = Number(val); +var utils = __webpack_require__(442); - obj[prop] = val; - return obj; -}, {}); +// Headers whose duplicates are ignored by node +// c.f. https://nodejs.org/api/http.html#http_message_headers +var ignoreDuplicateOf = [ + 'age', 'authorization', 'content-length', 'content-type', 'etag', + 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', + 'last-modified', 'location', 'max-forwards', 'proxy-authorization', + 'referer', 'retry-after', 'user-agent' +]; /** - * Is stdout a TTY? Colored output is enabled when `true`. + * Parse headers into an object + * + * ``` + * Date: Wed, 27 Aug 2014 08:58:49 GMT + * Content-Type: application/json + * Connection: keep-alive + * Transfer-Encoding: chunked + * ``` + * + * @param {String} headers Headers needing to be parsed + * @returns {Object} Headers parsed into an object */ +module.exports = function parseHeaders(headers) { + var parsed = {}; + var key; + var val; + var i; -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(process.stderr.fd); -} - -/** - * Map %o to `util.inspect()`, all on a single line. - */ + if (!headers) { return parsed; } -exports.formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n').map(function(str) { - return str.trim() - }).join(' '); -}; + utils.forEach(headers.split('\n'), function parser(line) { + i = line.indexOf(':'); + key = utils.trim(line.substr(0, i)).toLowerCase(); + val = utils.trim(line.substr(i + 1)); -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ + if (key) { + if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { + return; + } + if (key === 'set-cookie') { + parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + } + }); -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); + return parsed; }; -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ - -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; - - if (useColors) { - var c = this.color; - var colorCode = '\u001b[3' + (c < 8 ? c : '8;5;' + c); - var prefix = ' ' + colorCode + ';1m' + name + ' ' + '\u001b[0m'; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} - -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } else { - return new Date().toISOString() + ' '; - } -} -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ +/***/ }), +/* 460 */ +/***/ (function(module, exports, __webpack_require__) { -function log() { - return process.stderr.write(util.format.apply(util, arguments) + '\n'); -} +"use strict"; -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; - } -} +var utils = __webpack_require__(442); -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ +module.exports = ( + utils.isStandardBrowserEnv() ? -function load() { - return process.env.DEBUG; -} + // Standard browser envs have full support of the APIs needed to test + // whether the request URL is of the same origin as current location. + (function standardBrowserEnv() { + var msie = /(msie|trident)/i.test(navigator.userAgent); + var urlParsingNode = document.createElement('a'); + var originURL; -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ + /** + * Parse a URL to discover it's components + * + * @param {String} url The URL to be parsed + * @returns {Object} + */ + function resolveURL(url) { + var href = url; -function init (debug) { - debug.inspectOpts = {}; + if (msie) { + // IE needs attribute set twice to normalize properties + urlParsingNode.setAttribute('href', href); + href = urlParsingNode.href; + } - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} + urlParsingNode.setAttribute('href', href); -/** - * Enable namespaces listed in `process.env.DEBUG` initially. - */ + // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: (urlParsingNode.pathname.charAt(0) === '/') ? + urlParsingNode.pathname : + '/' + urlParsingNode.pathname + }; + } -exports.enable(load()); + originURL = resolveURL(window.location.href); + /** + * Determine if a URL shares the same origin as the current location + * + * @param {String} requestURL The URL to test + * @returns {boolean} True if URL shares the same origin, otherwise false + */ + return function isURLSameOrigin(requestURL) { + var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; + return (parsed.protocol === originURL.protocol && + parsed.host === originURL.host); + }; + })() : -/***/ }), -/* 484 */ -/***/ (function(module, exports) { + // Non standard browser envs (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return function isURLSameOrigin() { + return true; + }; + })() +); -module.exports = require("tty"); /***/ }), -/* 485 */ +/* 461 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const os = __webpack_require__(11); -const hasFlag = __webpack_require__(12); - -const env = process.env; -let forceColor; -if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false')) { - forceColor = false; -} else if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - forceColor = true; -} -if ('FORCE_COLOR' in env) { - forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; -} +var utils = __webpack_require__(442); -function translateLevel(level) { - if (level === 0) { - return false; - } +module.exports = ( + utils.isStandardBrowserEnv() ? - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; -} + // Standard browser envs support document.cookie + (function standardBrowserEnv() { + return { + write: function write(name, value, expires, path, domain, secure) { + var cookie = []; + cookie.push(name + '=' + encodeURIComponent(value)); -function supportsColor(stream) { - if (forceColor === false) { - return 0; - } + if (utils.isNumber(expires)) { + cookie.push('expires=' + new Date(expires).toGMTString()); + } - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; - } + if (utils.isString(path)) { + cookie.push('path=' + path); + } - if (hasFlag('color=256')) { - return 2; - } + if (utils.isString(domain)) { + cookie.push('domain=' + domain); + } - if (stream && !stream.isTTY && forceColor !== true) { - return 0; - } + if (secure === true) { + cookie.push('secure'); + } - const min = forceColor ? 1 : 0; + document.cookie = cookie.join('; '); + }, - if (process.platform === 'win32') { - // Node.js 7.5.0 is the first version of Node.js to include a patch to - // libuv that enables 256 color output on Windows. Anything earlier and it - // won't work. However, here we target Node.js 8 at minimum as it is an LTS - // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows - // release that supports 256 colors. Windows 10 build 14931 is the first release - // that supports 16m/TrueColor. - const osRelease = os.release().split('.'); - if ( - Number(process.versions.node.split('.')[0]) >= 8 && - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } + read: function read(name) { + var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, - return 1; - } + remove: function remove(name) { + this.write(name, '', Date.now() - 86400000); + } + }; + })() : - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } + // Non standard browser env (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return { + write: function write() {}, + read: function read() { return null; }, + remove: function remove() {} + }; + })() +); - return min; - } - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } +/***/ }), +/* 462 */ +/***/ (function(module, exports, __webpack_require__) { - if (env.COLORTERM === 'truecolor') { - return 3; - } +"use strict"; - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default - } - } +var utils = __webpack_require__(442); +var settle = __webpack_require__(453); +var buildFullPath = __webpack_require__(456); +var buildURL = __webpack_require__(445); +var http = __webpack_require__(463); +var https = __webpack_require__(464); +var httpFollow = __webpack_require__(465).http; +var httpsFollow = __webpack_require__(465).https; +var url = __webpack_require__(439); +var zlib = __webpack_require__(473); +var pkg = __webpack_require__(474); +var createError = __webpack_require__(454); +var enhanceError = __webpack_require__(455); - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } +var isHttps = /https:?/; - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } +/*eslint consistent-return:0*/ +module.exports = function httpAdapter(config) { + return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) { + var resolve = function resolve(value) { + resolvePromise(value); + }; + var reject = function reject(value) { + rejectPromise(value); + }; + var data = config.data; + var headers = config.headers; - if ('COLORTERM' in env) { - return 1; - } + // Set User-Agent (required by some servers) + // Only set header if it hasn't been set in config + // See https://github.com/axios/axios/issues/69 + if (!headers['User-Agent'] && !headers['user-agent']) { + headers['User-Agent'] = 'axios/' + pkg.version; + } - if (env.TERM === 'dumb') { - return min; - } + if (data && !utils.isStream(data)) { + if (Buffer.isBuffer(data)) { + // Nothing to do... + } else if (utils.isArrayBuffer(data)) { + data = Buffer.from(new Uint8Array(data)); + } else if (utils.isString(data)) { + data = Buffer.from(data, 'utf-8'); + } else { + return reject(createError( + 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', + config + )); + } - return min; -} + // Add Content-Length header if data exists + headers['Content-Length'] = data.length; + } -function getSupportLevel(stream) { - const level = supportsColor(stream); - return translateLevel(level); -} + // HTTP basic authentication + var auth = undefined; + if (config.auth) { + var username = config.auth.username || ''; + var password = config.auth.password || ''; + auth = username + ':' + password; + } -module.exports = { - supportsColor: getSupportLevel, - stdout: getSupportLevel(process.stdout), - stderr: getSupportLevel(process.stderr) -}; + // Parse url + var fullPath = buildFullPath(config.baseURL, config.url); + var parsed = url.parse(fullPath); + var protocol = parsed.protocol || 'http:'; + if (!auth && parsed.auth) { + var urlAuth = parsed.auth.split(':'); + var urlUsername = urlAuth[0] || ''; + var urlPassword = urlAuth[1] || ''; + auth = urlUsername + ':' + urlPassword; + } -/***/ }), -/* 486 */ -/***/ (function(module, exports) { + if (auth) { + delete headers.Authorization; + } -module.exports = require("zlib"); + var isHttpsRequest = isHttps.test(protocol); + var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; -/***/ }), -/* 487 */ -/***/ (function(module) { + var options = { + path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''), + method: config.method.toUpperCase(), + headers: headers, + agent: agent, + agents: { http: config.httpAgent, https: config.httpsAgent }, + auth: auth + }; -module.exports = JSON.parse("{\"name\":\"axios\",\"version\":\"0.19.2\",\"description\":\"Promise based HTTP client for the browser and node.js\",\"main\":\"index.js\",\"scripts\":{\"test\":\"grunt test && bundlesize\",\"start\":\"node ./sandbox/server.js\",\"build\":\"NODE_ENV=production grunt build\",\"preversion\":\"npm test\",\"version\":\"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json\",\"postversion\":\"git push && git push --tags\",\"examples\":\"node ./examples/server.js\",\"coveralls\":\"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js\",\"fix\":\"eslint --fix lib/**/*.js\"},\"repository\":{\"type\":\"git\",\"url\":\"https://github.com/axios/axios.git\"},\"keywords\":[\"xhr\",\"http\",\"ajax\",\"promise\",\"node\"],\"author\":\"Matt Zabriskie\",\"license\":\"MIT\",\"bugs\":{\"url\":\"https://github.com/axios/axios/issues\"},\"homepage\":\"https://github.com/axios/axios\",\"devDependencies\":{\"bundlesize\":\"^0.17.0\",\"coveralls\":\"^3.0.0\",\"es6-promise\":\"^4.2.4\",\"grunt\":\"^1.0.2\",\"grunt-banner\":\"^0.6.0\",\"grunt-cli\":\"^1.2.0\",\"grunt-contrib-clean\":\"^1.1.0\",\"grunt-contrib-watch\":\"^1.0.0\",\"grunt-eslint\":\"^20.1.0\",\"grunt-karma\":\"^2.0.0\",\"grunt-mocha-test\":\"^0.13.3\",\"grunt-ts\":\"^6.0.0-beta.19\",\"grunt-webpack\":\"^1.0.18\",\"istanbul-instrumenter-loader\":\"^1.0.0\",\"jasmine-core\":\"^2.4.1\",\"karma\":\"^1.3.0\",\"karma-chrome-launcher\":\"^2.2.0\",\"karma-coverage\":\"^1.1.1\",\"karma-firefox-launcher\":\"^1.1.0\",\"karma-jasmine\":\"^1.1.1\",\"karma-jasmine-ajax\":\"^0.1.13\",\"karma-opera-launcher\":\"^1.0.0\",\"karma-safari-launcher\":\"^1.0.0\",\"karma-sauce-launcher\":\"^1.2.0\",\"karma-sinon\":\"^1.0.5\",\"karma-sourcemap-loader\":\"^0.3.7\",\"karma-webpack\":\"^1.7.0\",\"load-grunt-tasks\":\"^3.5.2\",\"minimist\":\"^1.2.0\",\"mocha\":\"^5.2.0\",\"sinon\":\"^4.5.0\",\"typescript\":\"^2.8.1\",\"url-search-params\":\"^0.10.0\",\"webpack\":\"^1.13.1\",\"webpack-dev-server\":\"^1.14.1\"},\"browser\":{\"./lib/adapters/http.js\":\"./lib/adapters/xhr.js\"},\"typings\":\"./index.d.ts\",\"dependencies\":{\"follow-redirects\":\"1.5.10\"},\"bundlesize\":[{\"path\":\"./dist/axios.min.js\",\"threshold\":\"5kB\"}]}"); + if (config.socketPath) { + options.socketPath = config.socketPath; + } else { + options.hostname = parsed.hostname; + options.port = parsed.port; + } -/***/ }), -/* 488 */ -/***/ (function(module, exports, __webpack_require__) { + var proxy = config.proxy; + if (!proxy && proxy !== false) { + var proxyEnv = protocol.slice(0, -1) + '_proxy'; + var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()]; + if (proxyUrl) { + var parsedProxyUrl = url.parse(proxyUrl); + var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY; + var shouldProxy = true; -"use strict"; + if (noProxyEnv) { + var noProxy = noProxyEnv.split(',').map(function trim(s) { + return s.trim(); + }); + shouldProxy = !noProxy.some(function proxyMatch(proxyElement) { + if (!proxyElement) { + return false; + } + if (proxyElement === '*') { + return true; + } + if (proxyElement[0] === '.' && + parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) { + return true; + } -var utils = __webpack_require__(455); + return parsed.hostname === proxyElement; + }); + } -/** - * Config-specific merge-function which creates a new config-object - * by merging two configuration objects together. - * - * @param {Object} config1 - * @param {Object} config2 - * @returns {Object} New object resulting from merging config2 to config1 - */ -module.exports = function mergeConfig(config1, config2) { - // eslint-disable-next-line no-param-reassign - config2 = config2 || {}; - var config = {}; - var valueFromConfig2Keys = ['url', 'method', 'params', 'data']; - var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy']; - var defaultToConfig2Keys = [ - 'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer', - 'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', - 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', - 'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent', - 'httpsAgent', 'cancelToken', 'socketPath' - ]; + if (shouldProxy) { + proxy = { + host: parsedProxyUrl.hostname, + port: parsedProxyUrl.port + }; - utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { - if (typeof config2[prop] !== 'undefined') { - config[prop] = config2[prop]; + if (parsedProxyUrl.auth) { + var proxyUrlAuth = parsedProxyUrl.auth.split(':'); + proxy.auth = { + username: proxyUrlAuth[0], + password: proxyUrlAuth[1] + }; + } + } + } } - }); - utils.forEach(mergeDeepPropertiesKeys, function mergeDeepProperties(prop) { - if (utils.isObject(config2[prop])) { - config[prop] = utils.deepMerge(config1[prop], config2[prop]); - } else if (typeof config2[prop] !== 'undefined') { - config[prop] = config2[prop]; - } else if (utils.isObject(config1[prop])) { - config[prop] = utils.deepMerge(config1[prop]); - } else if (typeof config1[prop] !== 'undefined') { - config[prop] = config1[prop]; - } - }); + if (proxy) { + options.hostname = proxy.host; + options.host = proxy.host; + options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : ''); + options.port = proxy.port; + options.path = protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path; - utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { - if (typeof config2[prop] !== 'undefined') { - config[prop] = config2[prop]; - } else if (typeof config1[prop] !== 'undefined') { - config[prop] = config1[prop]; + // Basic proxy authorization + if (proxy.auth) { + var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64'); + options.headers['Proxy-Authorization'] = 'Basic ' + base64; + } } - }); - - var axiosKeys = valueFromConfig2Keys - .concat(mergeDeepPropertiesKeys) - .concat(defaultToConfig2Keys); - - var otherKeys = Object - .keys(config2) - .filter(function filterAxiosKeys(key) { - return axiosKeys.indexOf(key) === -1; - }); - utils.forEach(otherKeys, function otherKeysDefaultToConfig2(prop) { - if (typeof config2[prop] !== 'undefined') { - config[prop] = config2[prop]; - } else if (typeof config1[prop] !== 'undefined') { - config[prop] = config1[prop]; + var transport; + var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true); + if (config.transport) { + transport = config.transport; + } else if (config.maxRedirects === 0) { + transport = isHttpsProxy ? https : http; + } else { + if (config.maxRedirects) { + options.maxRedirects = config.maxRedirects; + } + transport = isHttpsProxy ? httpsFollow : httpFollow; } - }); - - return config; -}; + if (config.maxContentLength && config.maxContentLength > -1) { + options.maxBodyLength = config.maxContentLength; + } -/***/ }), -/* 489 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; + // Create the request + var req = transport.request(options, function handleResponse(res) { + if (req.aborted) return; + // uncompress the response body transparently if required + var stream = res; + switch (res.headers['content-encoding']) { + /*eslint default-case:0*/ + case 'gzip': + case 'compress': + case 'deflate': + // add the unzipper to the body stream processing pipeline + stream = (res.statusCode === 204) ? stream : stream.pipe(zlib.createUnzip()); -/** - * A `Cancel` is an object that is thrown when an operation is canceled. - * - * @class - * @param {string=} message The message. - */ -function Cancel(message) { - this.message = message; -} + // remove the content-encoding in order to not confuse downstream operations + delete res.headers['content-encoding']; + break; + } -Cancel.prototype.toString = function toString() { - return 'Cancel' + (this.message ? ': ' + this.message : ''); -}; + // return the last request in case of redirects + var lastRequest = res.req || req; -Cancel.prototype.__CANCEL__ = true; + var response = { + status: res.statusCode, + statusText: res.statusMessage, + headers: res.headers, + config: config, + request: lastRequest + }; -module.exports = Cancel; + if (config.responseType === 'stream') { + response.data = stream; + settle(resolve, reject, response); + } else { + var responseBuffer = []; + stream.on('data', function handleStreamData(chunk) { + responseBuffer.push(chunk); + // make sure the content length is not over the maxContentLength if specified + if (config.maxContentLength > -1 && Buffer.concat(responseBuffer).length > config.maxContentLength) { + stream.destroy(); + reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded', + config, null, lastRequest)); + } + }); -/***/ }), -/* 490 */ -/***/ (function(module, exports, __webpack_require__) { + stream.on('error', function handleStreamError(err) { + if (req.aborted) return; + reject(enhanceError(err, config, null, lastRequest)); + }); -"use strict"; + stream.on('end', function handleStreamEnd() { + var responseData = Buffer.concat(responseBuffer); + if (config.responseType !== 'arraybuffer') { + responseData = responseData.toString(config.responseEncoding); + } + response.data = responseData; + settle(resolve, reject, response); + }); + } + }); -var Cancel = __webpack_require__(489); + // Handle errors + req.on('error', function handleRequestError(err) { + if (req.aborted) return; + reject(enhanceError(err, config, null, req)); + }); -/** - * A `CancelToken` is an object that can be used to request cancellation of an operation. - * - * @class - * @param {Function} executor The executor function. - */ -function CancelToken(executor) { - if (typeof executor !== 'function') { - throw new TypeError('executor must be a function.'); - } + // Handle request timeout + if (config.timeout) { + // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. + // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. + // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. + // And then these socket which be hang up will devoring CPU little by little. + // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. + req.setTimeout(config.timeout, function handleRequestTimeout() { + req.abort(); + reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', req)); + }); + } - var resolvePromise; - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); + if (config.cancelToken) { + // Handle cancellation + config.cancelToken.promise.then(function onCanceled(cancel) { + if (req.aborted) return; - var token = this; - executor(function cancel(message) { - if (token.reason) { - // Cancellation has already been requested - return; + req.abort(); + reject(cancel); + }); } - token.reason = new Cancel(message); - resolvePromise(token.reason); + // Send the request + if (utils.isStream(data)) { + data.on('error', function handleStreamError(err) { + reject(enhanceError(err, config, null, req)); + }).pipe(req); + } else { + req.end(data); + } }); -} - -/** - * Throws a `Cancel` if cancellation has been requested. - */ -CancelToken.prototype.throwIfRequested = function throwIfRequested() { - if (this.reason) { - throw this.reason; - } }; -/** - * Returns an object that contains a new `CancelToken` and a function that, when called, - * cancels the `CancelToken`. - */ -CancelToken.source = function source() { - var cancel; - var token = new CancelToken(function executor(c) { - cancel = c; - }); - return { - token: token, - cancel: cancel - }; -}; -module.exports = CancelToken; +/***/ }), +/* 463 */ +/***/ (function(module, exports) { +module.exports = require("http"); /***/ }), -/* 491 */ +/* 464 */ +/***/ (function(module, exports) { + +module.exports = require("https"); + +/***/ }), +/* 465 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +var url = __webpack_require__(439); +var http = __webpack_require__(463); +var https = __webpack_require__(464); +var assert = __webpack_require__(371); +var Writable = __webpack_require__(382).Writable; +var debug = __webpack_require__(466)("follow-redirects"); +// RFC7231§4.2.1: Of the request methods defined by this specification, +// the GET, HEAD, OPTIONS, and TRACE methods are defined to be safe. +var SAFE_METHODS = { GET: true, HEAD: true, OPTIONS: true, TRACE: true }; -/** - * Syntactic sugar for invoking a function and expanding an array for arguments. - * - * Common use case would be to use `Function.prototype.apply`. - * - * ```js - * function f(x, y, z) {} - * var args = [1, 2, 3]; - * f.apply(null, args); - * ``` - * - * With `spread` this example can be re-written. - * - * ```js - * spread(function(x, y, z) {})([1, 2, 3]); - * ``` - * - * @param {Function} callback - * @returns {Function} - */ -module.exports = function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); +// Create handlers that pass events from native requests +var eventHandlers = Object.create(null); +["abort", "aborted", "error", "socket", "timeout"].forEach(function (event) { + eventHandlers[event] = function (arg) { + this._redirectable.emit(event, arg); }; -}; +}); +// An HTTP(S) request that can be redirected +function RedirectableRequest(options, responseCallback) { + // Initialize the request + Writable.call(this); + options.headers = options.headers || {}; + this._options = options; + this._redirectCount = 0; + this._redirects = []; + this._requestBodyLength = 0; + this._requestBodyBuffers = []; -/***/ }), -/* 492 */ -/***/ (function(module, exports, __webpack_require__) { + // Since http.request treats host as an alias of hostname, + // but the url module interprets host as hostname plus port, + // eliminate the host property to avoid confusion. + if (options.host) { + // Use hostname if set, because it has precedence + if (!options.hostname) { + options.hostname = options.host; + } + delete options.host; + } -"use strict"; + // Attach a callback if passed + if (responseCallback) { + this.on("response", responseCallback); + } -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(36); -tslib_1.__exportStar(__webpack_require__(493), exports); + // React to responses of native requests + var self = this; + this._onNativeResponse = function (response) { + self._processResponse(response); + }; + // Complete the URL object when necessary + if (!options.pathname && options.path) { + var searchPos = options.path.indexOf("?"); + if (searchPos < 0) { + options.pathname = options.path; + } + else { + options.pathname = options.path.substring(0, searchPos); + options.search = options.path.substring(searchPos); + } + } -/***/ }), -/* 493 */ -/***/ (function(module, exports, __webpack_require__) { + // Perform the first request + this._performRequest(); +} +RedirectableRequest.prototype = Object.create(Writable.prototype); -"use strict"; +// Writes buffered data to the current native request +RedirectableRequest.prototype.write = function (data, encoding, callback) { + // Validate input and shift parameters if necessary + if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { + throw new Error("data should be a string, Buffer or Uint8Array"); + } + if (typeof encoding === "function") { + callback = encoding; + encoding = null; + } -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isAxiosRequestError = (error) => { - return error && error.config && error.response === undefined; -}; -exports.isAxiosResponseError = (error) => { - return error && error.response && error.response.status !== undefined; + // Ignore empty buffers, since writing them doesn't invoke the callback + // https://github.com/nodejs/node/issues/22066 + if (data.length === 0) { + if (callback) { + callback(); + } + return; + } + // Only write when we don't exceed the maximum body length + if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { + this._requestBodyLength += data.length; + this._requestBodyBuffers.push({ data: data, encoding: encoding }); + this._currentRequest.write(data, encoding, callback); + } + // Error when we exceed the maximum body length + else { + this.emit("error", new Error("Request body larger than maxBodyLength limit")); + this.abort(); + } }; +// Ends the current native request +RedirectableRequest.prototype.end = function (data, encoding, callback) { + // Shift parameters if necessary + if (typeof data === "function") { + callback = data; + data = encoding = null; + } + else if (typeof encoding === "function") { + callback = encoding; + encoding = null; + } -/***/ }), -/* 494 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; + // Write data and end + var currentRequest = this._currentRequest; + this.write(data || "", encoding, function () { + currentRequest.end(null, null, callback); + }); +}; -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -class KbnClientStatus { - constructor(requester) { - this.requester = requester; - } - /** - * Get the full server status - */ - async get() { - return await this.requester.request({ - method: 'GET', - path: 'api/status', - }); - } - /** - * Get the overall/merged state - */ - async getOverallState() { - const status = await this.get(); - return status.status.overall.state; - } -} -exports.KbnClientStatus = KbnClientStatus; +// Sets a header value on the current native request +RedirectableRequest.prototype.setHeader = function (name, value) { + this._options.headers[name] = value; + this._currentRequest.setHeader(name, value); +}; +// Clears a header value on the current native request +RedirectableRequest.prototype.removeHeader = function (name) { + delete this._options.headers[name]; + this._currentRequest.removeHeader(name); +}; -/***/ }), -/* 495 */ -/***/ (function(module, exports, __webpack_require__) { +// Proxy all other public ClientRequest methods +[ + "abort", "flushHeaders", "getHeader", + "setNoDelay", "setSocketKeepAlive", "setTimeout", +].forEach(function (method) { + RedirectableRequest.prototype[method] = function (a, b) { + return this._currentRequest[method](a, b); + }; +}); -"use strict"; +// Proxy all public ClientRequest properties +["aborted", "connection", "socket"].forEach(function (property) { + Object.defineProperty(RedirectableRequest.prototype, property, { + get: function () { return this._currentRequest[property]; }, + }); +}); -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const PLUGIN_STATUS_ID = /^plugin:(.+?)@/; -class KbnClientPlugins { - constructor(status) { - this.status = status; - } - /** - * Get a list of plugin ids that are enabled on the server - */ - async getEnabledIds() { - const pluginIds = []; - const apiResp = await this.status.get(); - for (const status of apiResp.status.statuses) { - if (status.id) { - const match = status.id.match(PLUGIN_STATUS_ID); - if (match) { - pluginIds.push(match[1]); - } - } - } - return pluginIds; +// Executes the next native request (initial or redirect) +RedirectableRequest.prototype._performRequest = function () { + // Load the native protocol + var protocol = this._options.protocol; + var nativeProtocol = this._options.nativeProtocols[protocol]; + if (!nativeProtocol) { + this.emit("error", new Error("Unsupported protocol " + protocol)); + return; + } + + // If specified, use the agent corresponding to the protocol + // (HTTP and HTTPS use different types of agents) + if (this._options.agents) { + var scheme = protocol.substr(0, protocol.length - 1); + this._options.agent = this._options.agents[scheme]; + } + + // Create the native request + var request = this._currentRequest = + nativeProtocol.request(this._options, this._onNativeResponse); + this._currentUrl = url.format(this._options); + + // Set up event handlers + request._redirectable = this; + for (var event in eventHandlers) { + /* istanbul ignore else */ + if (event) { + request.on(event, eventHandlers[event]); } -} -exports.KbnClientPlugins = KbnClientPlugins; + } + // End a redirected request + // (The first request must be ended explicitly with RedirectableRequest#end) + if (this._isRedirect) { + // Write the request entity and end. + var i = 0; + var buffers = this._requestBodyBuffers; + (function writeNext() { + if (i < buffers.length) { + var buffer = buffers[i++]; + request.write(buffer.data, buffer.encoding, writeNext); + } + else { + request.end(); + } + }()); + } +}; -/***/ }), -/* 496 */ -/***/ (function(module, exports, __webpack_require__) { +// Processes a response from the current native request +RedirectableRequest.prototype._processResponse = function (response) { + // Store the redirected response + if (this._options.trackRedirects) { + this._redirects.push({ + url: this._currentUrl, + headers: response.headers, + statusCode: response.statusCode, + }); + } -"use strict"; + // RFC7231§6.4: The 3xx (Redirection) class of status code indicates + // that further action needs to be taken by the user agent in order to + // fulfill the request. If a Location header field is provided, + // the user agent MAY automatically redirect its request to the URI + // referenced by the Location field value, + // even if the specific status code is not understood. + var location = response.headers.location; + if (location && this._options.followRedirects !== false && + response.statusCode >= 300 && response.statusCode < 400) { + // RFC7231§6.4: A client SHOULD detect and intervene + // in cyclical redirections (i.e., "infinite" redirection loops). + if (++this._redirectCount > this._options.maxRedirects) { + this.emit("error", new Error("Max redirects exceeded.")); + return; + } -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -class KbnClientVersion { - constructor(status) { - this.status = status; + // RFC7231§6.4: Automatic redirection needs to done with + // care for methods not known to be safe […], + // since the user might not wish to redirect an unsafe request. + // RFC7231§6.4.7: The 307 (Temporary Redirect) status code indicates + // that the target resource resides temporarily under a different URI + // and the user agent MUST NOT change the request method + // if it performs an automatic redirection to that URI. + var header; + var headers = this._options.headers; + if (response.statusCode !== 307 && !(this._options.method in SAFE_METHODS)) { + this._options.method = "GET"; + // Drop a possible entity and headers related to it + this._requestBodyBuffers = []; + for (header in headers) { + if (/^content-/i.test(header)) { + delete headers[header]; + } + } } - async get() { - if (this.versionCache !== undefined) { - return this.versionCache; + + // Drop the Host header, as the redirect might lead to a different host + if (!this._isRedirect) { + for (header in headers) { + if (/^host$/i.test(header)) { + delete headers[header]; } - const status = await this.status.get(); - this.versionCache = status.version.number + (status.version.build_snapshot ? '-SNAPSHOT' : ''); - return this.versionCache; + } } -} -exports.KbnClientVersion = KbnClientVersion; + // Perform the redirected request + var redirectUrl = url.resolve(this._currentUrl, location); + debug("redirecting to", redirectUrl); + Object.assign(this._options, url.parse(redirectUrl)); + this._isRedirect = true; + this._performRequest(); -/***/ }), -/* 497 */ -/***/ (function(module, exports, __webpack_require__) { + // Discard the remainder of the response to avoid waiting for data + response.destroy(); + } + else { + // The response is not a redirect; return it as-is + response.responseUrl = this._currentUrl; + response.redirects = this._redirects; + this.emit("response", response); -"use strict"; + // Clean up + this._requestBodyBuffers = []; + } +}; -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const kbn_client_requester_1 = __webpack_require__(451); -class KbnClientSavedObjects { - constructor(log, requester) { - this.log = log; - this.requester = requester; - } - /** - * Run the saved objects migration - */ - async migrate() { - this.log.debug('Migrating saved objects'); - return await this.requester.request({ - description: 'migrate saved objects', - path: kbn_client_requester_1.uriencode `/internal/saved_objects/_migrate`, - method: 'POST', - body: {}, - }); - } - /** - * Get an object - */ - async get(options) { - this.log.debug('Gettings saved object: %j', options); - return await this.requester.request({ - description: 'get saved object', - path: kbn_client_requester_1.uriencode `/api/saved_objects/${options.type}/${options.id}`, - method: 'GET', - }); - } - /** - * Create a saved object - */ - async create(options) { - this.log.debug('Creating saved object: %j', options); - return await this.requester.request({ - description: 'update saved object', - path: options.id - ? kbn_client_requester_1.uriencode `/api/saved_objects/${options.type}/${options.id}` - : kbn_client_requester_1.uriencode `/api/saved_objects/${options.type}`, - query: { - overwrite: options.overwrite, - }, - method: 'POST', - body: { - attributes: options.attributes, - migrationVersion: options.migrationVersion, - references: options.references, - }, - }); - } - /** - * Update a saved object - */ - async update(options) { - this.log.debug('Updating saved object: %j', options); - return await this.requester.request({ - description: 'update saved object', - path: kbn_client_requester_1.uriencode `/api/saved_objects/${options.type}/${options.id}`, - query: { - overwrite: options.overwrite, - }, - method: 'PUT', - body: { - attributes: options.attributes, - migrationVersion: options.migrationVersion, - references: options.references, - }, - }); - } - /** - * Delete an object - */ - async delete(options) { - this.log.debug('Deleting saved object %s/%s', options); - return await this.requester.request({ - description: 'delete saved object', - path: kbn_client_requester_1.uriencode `/api/saved_objects/${options.type}/${options.id}`, - method: 'DELETE', - }); - } +// Wraps the key/value object of protocols with redirect functionality +function wrap(protocols) { + // Default settings + var exports = { + maxRedirects: 21, + maxBodyLength: 10 * 1024 * 1024, + }; + + // Wrap each protocol + var nativeProtocols = {}; + Object.keys(protocols).forEach(function (scheme) { + var protocol = scheme + ":"; + var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; + var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); + + // Executes a request, following redirects + wrappedProtocol.request = function (options, callback) { + if (typeof options === "string") { + options = url.parse(options); + options.maxRedirects = exports.maxRedirects; + } + else { + options = Object.assign({ + protocol: protocol, + maxRedirects: exports.maxRedirects, + maxBodyLength: exports.maxBodyLength, + }, options); + } + options.nativeProtocols = nativeProtocols; + assert.equal(options.protocol, protocol, "protocol mismatch"); + debug("options", options); + return new RedirectableRequest(options, callback); + }; + + // Executes a GET request, following redirects + wrappedProtocol.get = function (options, callback) { + var request = wrappedProtocol.request(options, callback); + request.end(); + return request; + }; + }); + return exports; } -exports.KbnClientSavedObjects = KbnClientSavedObjects; + +// Exports +module.exports = wrap({ http: http, https: https }); +module.exports.wrap = wrap; /***/ }), -/* 498 */ +/* 466 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. */ -Object.defineProperty(exports, "__esModule", { value: true }); -const kbn_client_requester_1 = __webpack_require__(451); -class KbnClientUiSettings { - constructor(log, requester, defaults) { - this.log = log; - this.requester = requester; - this.defaults = defaults; - } - async get(setting) { - var _a; - const all = await this.getAll(); - const value = (_a = all[setting]) === null || _a === void 0 ? void 0 : _a.userValue; - this.log.verbose('uiSettings.value: %j', value); - return value; - } - /** - * Gets defaultIndex from the config doc. - */ - async getDefaultIndex() { - return await this.get('defaultIndex'); - } - /** - * Unset a uiSetting - */ - async unset(setting) { - return await this.requester.request({ - path: kbn_client_requester_1.uriencode `/api/kibana/settings/${setting}`, - method: 'DELETE', - }); - } - /** - * Replace all uiSettings with the `doc` values, `doc` is merged - * with some defaults - */ - async replace(doc, { retries = 5 } = {}) { - this.log.debug('replacing kibana config doc: %j', doc); - const changes = { - ...this.defaults, - ...doc, - }; - for (const [name, { isOverridden }] of Object.entries(await this.getAll())) { - if (!isOverridden && !changes.hasOwnProperty(name)) { - changes[name] = null; - } - } - await this.requester.request({ - method: 'POST', - path: '/api/kibana/settings', - body: { changes }, - retries, - }); - } - /** - * Add fields to the config doc (like setting timezone and defaultIndex) - */ - async update(updates) { - this.log.debug('applying update to kibana config: %j', updates); - await this.requester.request({ - path: '/api/kibana/settings', - method: 'POST', - body: { - changes: updates, - }, - }); - } - async getAll() { - const resp = await this.requester.request({ - path: '/api/kibana/settings', - method: 'GET', - }); - return resp.settings; - } + +if (typeof process === 'undefined' || process.type === 'renderer') { + module.exports = __webpack_require__(467); +} else { + module.exports = __webpack_require__(470); } -exports.KbnClientUiSettings = KbnClientUiSettings; /***/ }), -/* 499 */ +/* 467 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 +/** + * This is the web browser implementation of `debug()`. * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * Expose `debug()` as the module. */ -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(36); -tslib_1.__exportStar(__webpack_require__(500), exports); +exports = module.exports = __webpack_require__(468); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); -/***/ }), -/* 500 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Colors. + */ -"use strict"; +exports.colors = [ + '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', + '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', + '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', + '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', + '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', + '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', + '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', + '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', + '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', + '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', + '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' +]; -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * TODO: add a `localStorage` variable to explicitly enable/disable colors */ -Object.defineProperty(exports, "__esModule", { value: true }); -const tslib_1 = __webpack_require__(36); -const util_1 = __webpack_require__(29); -const axios_1 = tslib_1.__importDefault(__webpack_require__(453)); -function parseConfig(log) { - const configJson = process.env.KIBANA_CI_STATS_CONFIG; - if (!configJson) { - log.debug('KIBANA_CI_STATS_CONFIG environment variable not found, disabling CiStatsReporter'); - return; - } - let config; - try { - config = JSON.parse(configJson); - } - catch (_) { - // handled below - } - if (typeof config === 'object' && config !== null) { - return validateConfig(log, config); - } - log.warning('KIBANA_CI_STATS_CONFIG is invalid, stats will not be reported'); - return; -} -function validateConfig(log, config) { - const validApiUrl = typeof config.apiUrl === 'string' && config.apiUrl.length !== 0; - if (!validApiUrl) { - log.warning('KIBANA_CI_STATS_CONFIG is missing a valid api url, stats will not be reported'); - return; - } - const validApiToken = typeof config.apiToken === 'string' && config.apiToken.length !== 0; - if (!validApiToken) { - log.warning('KIBANA_CI_STATS_CONFIG is missing a valid api token, stats will not be reported'); - return; - } - const validId = typeof config.buildId === 'string' && config.buildId.length !== 0; - if (!validId) { - log.warning('KIBANA_CI_STATS_CONFIG is missing a valid build id, stats will not be reported'); - return; - } - return config; -} -class CiStatsReporter { - constructor(config, log) { - this.config = config; - this.log = log; - } - static fromEnv(log) { - return new CiStatsReporter(parseConfig(log), log); - } - isEnabled() { - return !!this.config; - } - async metrics(metrics) { - var _a, _b, _c, _d; - if (!this.config) { - return; - } - let attempt = 0; - const maxAttempts = 5; - const bodySummary = metrics - .map(({ group, id, value }) => `[${group}/${id}=${value}]`) - .join(' '); - while (true) { - attempt += 1; - try { - await axios_1.default.request({ - method: 'POST', - url: '/v1/metrics', - baseURL: this.config.apiUrl, - headers: { - Authorization: `token ${this.config.apiToken}`, - }, - data: { - buildId: this.config.buildId, - metrics, - }, - }); - return; - } - catch (error) { - if (!((_a = error) === null || _a === void 0 ? void 0 : _a.request)) { - // not an axios error, must be a usage error that we should notify user about - throw error; - } - if (((_b = error) === null || _b === void 0 ? void 0 : _b.response) && error.response.status !== 502) { - // error response from service was received so warn the user and move on - this.log.warning(`error recording metric [status=${error.response.status}] [resp=${util_1.inspect(error.response.data)}] ${bodySummary}`); - return; - } - if (attempt === maxAttempts) { - this.log.warning(`failed to reach kibana-ci-stats service too many times, unable to record metric ${bodySummary}`); - return; - } - // we failed to reach the backend and we have remaining attempts, lets retry after a short delay - const reason = ((_d = (_c = error) === null || _c === void 0 ? void 0 : _c.response) === null || _d === void 0 ? void 0 : _d.status) ? `${error.response.status} response` - : 'no response'; - this.log.warning(`failed to reach kibana-ci-stats service [reason=${reason}], retrying in ${attempt} seconds`); - await new Promise((resolve) => setTimeout(resolve, attempt * 1000)); - } - } - } + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } -exports.CiStatsReporter = CiStatsReporter; +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ -/***/ }), -/* 501 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parallelizeBatches", function() { return parallelizeBatches; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parallelize", function() { return parallelize; }); -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + +/** + * Colorize log arguments if enabled. * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * @api public */ -async function parallelizeBatches(batches, fn) { - for (const batch of batches) { - // We need to make sure the entire batch has completed before we can move on - // to the next batch - await parallelize(batch, fn); - } -} -async function parallelize(items, fn, concurrency = 4) { - if (items.length === 0) { - return; - } - return new Promise((resolve, reject) => { - let activePromises = 0; - const values = items.slice(0); +function formatArgs(args) { + var useColors = this.useColors; - async function scheduleItem(item) { - activePromises++; + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); - try { - await fn(item); - activePromises--; + if (!useColors) return; - if (values.length > 0) { - // We have more work to do, so we schedule the next promise - scheduleItem(values.shift()); - } else if (activePromises === 0) { - // We have no more values left, and all items have completed, so we've - // completed all the work. - resolve(); - } - } catch (error) { - reject(error); - } - } + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') - values.splice(0, concurrency).map(scheduleItem); + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } }); -} -/***/ }), -/* 502 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + args.splice(lastC, 0, c); +} -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getProjects", function() { return getProjects; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buildProjectGraph", function() { return buildProjectGraph; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "topologicallyBatchProjects", function() { return topologicallyBatchProjects; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "includeTransitiveProjects", function() { return includeTransitiveProjects; }); -/* harmony import */ var glob__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(503); -/* harmony import */ var glob__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(glob__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(516); -/* harmony import */ var _project__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(517); -/* harmony import */ var _workspaces__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(578); -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". * - * http://www.apache.org/licenses/LICENSE-2.0 + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * @param {String} namespaces + * @api private */ +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + return r; +} -const glob = Object(util__WEBPACK_IMPORTED_MODULE_2__["promisify"])(glob__WEBPACK_IMPORTED_MODULE_0___default.a); -/** a Map of project names to Project instances */ +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ -async function getProjects(rootPath, projectsPathsPatterns, { - include = [], - exclude = [] -} = {}) { - const projects = new Map(); - const workspaceProjectsPaths = await Object(_workspaces__WEBPACK_IMPORTED_MODULE_5__["workspacePackagePaths"])(rootPath); +exports.enable(load()); - for (const pattern of projectsPathsPatterns) { - const pathsToProcess = await packagesFromGlobPattern({ - pattern, - rootPath - }); +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ - for (const filePath of pathsToProcess) { - const projectConfigPath = normalize(filePath); - const projectDir = path__WEBPACK_IMPORTED_MODULE_1___default.a.dirname(projectConfigPath); - const project = await _project__WEBPACK_IMPORTED_MODULE_4__["Project"].fromPath(projectDir); +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} - if (workspaceProjectsPaths.indexOf(filePath) >= 0) { - project.isWorkspaceProject = true; - } - const excludeProject = exclude.includes(project.name) || include.length > 0 && !include.includes(project.name); +/***/ }), +/* 468 */ +/***/ (function(module, exports, __webpack_require__) { - if (excludeProject) { - continue; - } - if (projects.has(project.name)) { - throw new _errors__WEBPACK_IMPORTED_MODULE_3__["CliError"](`There are multiple projects with the same name [${project.name}]`, { - name: project.name, - paths: [project.path, projects.get(project.name).path] - }); - } +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ - projects.set(project.name, project); - } - } +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = __webpack_require__(469); - return projects; -} +/** + * Active `debug` instances. + */ +exports.instances = []; -function packagesFromGlobPattern({ - pattern, - rootPath -}) { - const globOptions = { - cwd: rootPath, - // Should throw in case of unusual errors when reading the file system - strict: true, - // Always returns absolute paths for matched files - absolute: true, - // Do not match ** against multiple filenames - // (This is only specified because we currently don't have a need for it.) - noglobstar: true - }; - return glob(path__WEBPACK_IMPORTED_MODULE_1___default.a.join(pattern, 'package.json'), globOptions); -} // https://github.com/isaacs/node-glob/blob/master/common.js#L104 -// glob always returns "\\" as "/" in windows, so everyone -// gets normalized because we can't have nice things. +/** + * The currently active debug mode names, and names to skip. + */ +exports.names = []; +exports.skips = []; -function normalize(dir) { - return path__WEBPACK_IMPORTED_MODULE_1___default.a.normalize(dir); -} +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ -function buildProjectGraph(projects) { - const projectGraph = new Map(); +exports.formatters = {}; - for (const project of projects.values()) { - const projectDeps = []; - const dependencies = project.allDependencies; +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ - for (const depName of Object.keys(dependencies)) { - if (projects.has(depName)) { - const dep = projects.get(depName); - const dependentProjectIsInWorkspace = project.isWorkspaceProject || project.json.name === 'kibana'; - project.ensureValidProjectDependency(dep, dependentProjectIsInWorkspace); - projectDeps.push(dep); - } - } +function selectColor(namespace) { + var hash = 0, i; - projectGraph.set(project.name, projectDeps); + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer } - return projectGraph; + return exports.colors[Math.abs(hash) % exports.colors.length]; } -function topologicallyBatchProjects(projectsToBatch, projectGraph, { - batchByWorkspace = false -} = {}) { - // We're going to be chopping stuff out of this list, so copy it. - const projectsLeftToBatch = new Set(projectsToBatch.keys()); - const batches = []; - if (batchByWorkspace) { - const workspaceRootProject = Array.from(projectsToBatch.values()).find(p => p.isWorkspaceRoot); +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ - if (!workspaceRootProject) { - throw new _errors__WEBPACK_IMPORTED_MODULE_3__["CliError"](`There was no yarn workspace root found.`); - } // Push in the workspace root first. +function createDebug(namespace) { + var prevTime; - batches.push([workspaceRootProject]); - projectsLeftToBatch.delete(workspaceRootProject.name); // In the next batch, push in all workspace projects. + function debug() { + // disabled? + if (!debug.enabled) return; - const workspaceBatch = []; + var self = debug; - for (const projectName of projectsLeftToBatch) { - const project = projectsToBatch.get(projectName); + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; - if (project.isWorkspaceProject) { - workspaceBatch.push(project); - projectsLeftToBatch.delete(projectName); - } + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; } - batches.push(workspaceBatch); - } + args[0] = exports.coerce(args[0]); - while (projectsLeftToBatch.size > 0) { - // Get all projects that have no remaining dependencies within the repo - // that haven't yet been picked. - const batch = []; + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } - for (const projectName of projectsLeftToBatch) { - const projectDeps = projectGraph.get(projectName); - const needsDependenciesBatched = projectDeps.some(dep => projectsLeftToBatch.has(dep.name)); + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); - if (!needsDependenciesBatched) { - batch.push(projectsToBatch.get(projectName)); + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; } - } // If we weren't able to find a project with no remaining dependencies, - // then we've encountered a cycle in the dependency graph. + return match; + }); + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); - const hasCycles = batch.length === 0; + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } - if (hasCycles) { - const cycleProjectNames = [...projectsLeftToBatch]; - const message = 'Encountered a cycle in the dependency graph. Projects in cycle are:\n' + cycleProjectNames.join(', '); - throw new _errors__WEBPACK_IMPORTED_MODULE_3__["CliError"](message); - } + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + debug.destroy = destroy; - batches.push(batch); - batch.forEach(project => projectsLeftToBatch.delete(project.name)); + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); } - return batches; -} -function includeTransitiveProjects(subsetOfProjects, allProjects, { - onlyProductionDependencies = false -} = {}) { - const projectsWithDependents = new Map(); // the current list of packages we are expanding using breadth-first-search + exports.instances.push(debug); - const toProcess = [...subsetOfProjects]; + return debug; +} - while (toProcess.length > 0) { - const project = toProcess.shift(); - const dependencies = onlyProductionDependencies ? project.productionDependencies : project.allDependencies; - Object.keys(dependencies).forEach(dep => { - if (allProjects.has(dep)) { - toProcess.push(allProjects.get(dep)); - } - }); - projectsWithDependents.set(project.name, project); +function destroy () { + var index = exports.instances.indexOf(this); + if (index !== -1) { + exports.instances.splice(index, 1); + return true; + } else { + return false; } - - return projectsWithDependents; } -/***/ }), -/* 503 */ -/***/ (function(module, exports, __webpack_require__) { - -// Approach: -// -// 1. Get the minimatch set -// 2. For each pattern in the set, PROCESS(pattern, false) -// 3. Store matches per-set, then uniq them -// -// PROCESS(pattern, inGlobStar) -// Get the first [n] items from pattern that are all strings -// Join these together. This is PREFIX. -// If there is no more remaining, then stat(PREFIX) and -// add to matches if it succeeds. END. -// -// If inGlobStar and PREFIX is symlink and points to dir -// set ENTRIES = [] -// else readdir(PREFIX) as ENTRIES -// If fail, END -// -// with ENTRIES -// If pattern[n] is GLOBSTAR -// // handle the case where the globstar match is empty -// // by pruning it out, and testing the resulting pattern -// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) -// // handle other cases. -// for ENTRY in ENTRIES (not dotfiles) -// // attach globstar + tail onto the entry -// // Mark that this entry is a globstar match -// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) -// -// else // not globstar -// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) -// Test ENTRY against pattern[n] -// If fails, continue -// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) -// -// Caveat: -// Cache all stats and readdirs results to minimize syscall. Since all -// we ever care about is existence and directory-ness, we can just keep -// `true` for files, and [children,...] for directories, or `false` for -// things that don't exist. - -module.exports = glob +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ -var fs = __webpack_require__(23) -var rp = __webpack_require__(504) -var minimatch = __webpack_require__(506) -var Minimatch = minimatch.Minimatch -var inherits = __webpack_require__(510) -var EE = __webpack_require__(399).EventEmitter -var path = __webpack_require__(16) -var assert = __webpack_require__(30) -var isAbsolute = __webpack_require__(512) -var globSync = __webpack_require__(513) -var common = __webpack_require__(514) -var alphasort = common.alphasort -var alphasorti = common.alphasorti -var setopts = common.setopts -var ownProp = common.ownProp -var inflight = __webpack_require__(515) -var util = __webpack_require__(29) -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored +function enable(namespaces) { + exports.save(namespaces); -var once = __webpack_require__(404) + exports.names = []; + exports.skips = []; -function glob (pattern, options, cb) { - if (typeof options === 'function') cb = options, options = {} - if (!options) options = {} + var i; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; - if (options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return globSync(pattern, options) + for (i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } } - return new Glob(pattern, options, cb) + for (i = 0; i < exports.instances.length; i++) { + var instance = exports.instances[i]; + instance.enabled = exports.enabled(instance.namespace); + } } -glob.sync = globSync -var GlobSync = glob.GlobSync = globSync.GlobSync +/** + * Disable debug output. + * + * @api public + */ -// old api surface -glob.glob = glob +function disable() { + exports.enable(''); +} -function extend (origin, add) { - if (add === null || typeof add !== 'object') { - return origin - } +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ - var keys = Object.keys(add) - var i = keys.length - while (i--) { - origin[keys[i]] = add[keys[i]] +function enabled(name) { + if (name[name.length - 1] === '*') { + return true; } - return origin + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; } -glob.hasMagic = function (pattern, options_) { - var options = extend({}, options_) - options.noprocess = true +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ - var g = new Glob(pattern, options) - var set = g.minimatch.set +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} - if (!pattern) - return false - if (set.length > 1) - return true +/***/ }), +/* 469 */ +/***/ (function(module, exports) { - for (var j = 0; j < set[0].length; j++) { - if (typeof set[0][j] !== 'string') - return true - } +/** + * Helpers. + */ - return false -} +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; -glob.Glob = Glob -inherits(Glob, EE) -function Glob (pattern, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ - if (options && options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return new GlobSync(pattern, options) +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; - if (!(this instanceof Glob)) - return new Glob(pattern, options, cb) - - setopts(this, pattern, options) - this._didRealPath = false +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - // process each pattern in the minimatch set - var n = this.minimatch.set.length +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} - // The matches are stored as {: true,...} so that - // duplicates are automagically pruned. - // Later, we do an Object.keys() on these. - // Keep them as a list so we can fill in when nonull is set. - this.matches = new Array(n) +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - if (typeof cb === 'function') { - cb = once(cb) - this.on('error', cb) - this.on('end', function (matches) { - cb(null, matches) - }) +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} - var self = this - this._processing = 0 - - this._emitQueue = [] - this._processQueue = [] - this.paused = false +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - if (this.noprocess) - return this +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} - if (n === 0) - return done() +/** + * Pluralization helper. + */ - var sync = true - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false, done) +function plural(ms, n, name) { + if (ms < n) { + return; } - sync = false - - function done () { - --self._processing - if (self._processing <= 0) { - if (sync) { - process.nextTick(function () { - self._finish() - }) - } else { - self._finish() - } - } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; } + return Math.ceil(ms / n) + ' ' + name + 's'; } -Glob.prototype._finish = function () { - assert(this instanceof Glob) - if (this.aborted) - return - if (this.realpath && !this._didRealpath) - return this._realpath() +/***/ }), +/* 470 */ +/***/ (function(module, exports, __webpack_require__) { - common.finish(this) - this.emit('end', this.found) -} +/** + * Module dependencies. + */ -Glob.prototype._realpath = function () { - if (this._didRealpath) - return +var tty = __webpack_require__(471); +var util = __webpack_require__(397); - this._didRealpath = true +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ - var n = this.matches.length - if (n === 0) - return this._finish() +exports = module.exports = __webpack_require__(468); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; - var self = this - for (var i = 0; i < this.matches.length; i++) - this._realpathSet(i, next) +/** + * Colors. + */ - function next () { - if (--n === 0) - self._finish() +exports.colors = [ 6, 2, 3, 4, 5, 1 ]; + +try { + var supportsColor = __webpack_require__(472); + if (supportsColor && supportsColor.level >= 2) { + exports.colors = [ + 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, + 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, + 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, + 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, + 205, 206, 207, 208, 209, 214, 215, 220, 221 + ]; } +} catch (err) { + // swallow - we only care if `supports-color` is available; it doesn't have to be. } -Glob.prototype._realpathSet = function (index, cb) { - var matchset = this.matches[index] - if (!matchset) - return cb() +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ - var found = Object.keys(matchset) - var self = this - var n = found.length +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); - if (n === 0) - return cb() + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); - var set = this.matches[index] = Object.create(null) - found.forEach(function (p, i) { - // If there's a problem with the stat, then it means that - // one or more of the links in the realpath couldn't be - // resolved. just return the abs value in that case. - p = self._makeAbs(p) - rp.realpath(p, self.realpathCache, function (er, real) { - if (!er) - set[real] = true - else if (er.syscall === 'stat') - set[p] = true - else - self.emit('error', er) // srsly wtf right here + obj[prop] = val; + return obj; +}, {}); - if (--n === 0) { - self.matches[index] = set - cb() - } - }) - }) +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(process.stderr.fd); } -Glob.prototype._mark = function (p) { - return common.mark(this, p) -} +/** + * Map %o to `util.inspect()`, all on a single line. + */ -Glob.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; -Glob.prototype.abort = function () { - this.aborted = true - this.emit('abort') -} +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ -Glob.prototype.pause = function () { - if (!this.paused) { - this.paused = true - this.emit('pause') - } -} +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; -Glob.prototype.resume = function () { - if (this.paused) { - this.emit('resume') - this.paused = false - if (this._emitQueue.length) { - var eq = this._emitQueue.slice(0) - this._emitQueue.length = 0 - for (var i = 0; i < eq.length; i ++) { - var e = eq[i] - this._emitMatch(e[0], e[1]) - } - } - if (this._processQueue.length) { - var pq = this._processQueue.slice(0) - this._processQueue.length = 0 - for (var i = 0; i < pq.length; i ++) { - var p = pq[i] - this._processing-- - this._process(p[0], p[1], p[2], p[3]) - } - } - } -} +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ -Glob.prototype._process = function (pattern, index, inGlobStar, cb) { - assert(this instanceof Glob) - assert(typeof cb === 'function') +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; - if (this.aborted) - return + if (useColors) { + var c = this.color; + var colorCode = '\u001b[3' + (c < 8 ? c : '8;5;' + c); + var prefix = ' ' + colorCode + ';1m' + name + ' ' + '\u001b[0m'; - this._processing++ - if (this.paused) { - this._processQueue.push([pattern, index, inGlobStar, cb]) - return + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; } +} - //console.error('PROCESS %d', this._processing, pattern) - - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } else { + return new Date().toISOString() + ' '; } - // now n is the index of the first one that is *not* a string. +} - // see if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index, cb) - return +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break +function log() { + return process.stderr.write(util.format.apply(util, arguments) + '\n'); +} - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; } +} - var remain = pattern.slice(n) +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix +function load() { + return process.env.DEBUG; +} - var abs = this._makeAbs(read) +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ - //if ignored, skip _processing - if (childrenIgnored(this, read)) - return cb() +function init (debug) { + debug.inspectOpts = {}; - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } } -Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }) -} +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ -Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { +exports.enable(load()); - // if the abs isn't a dir, then nothing can match! - if (!entries) - return cb() - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' +/***/ }), +/* 471 */ +/***/ (function(module, exports) { - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) - } - if (m) - matchedEntries.push(e) - } - } +module.exports = require("tty"); - //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) +/***/ }), +/* 472 */ +/***/ (function(module, exports, __webpack_require__) { - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return cb() +"use strict"; - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. +const os = __webpack_require__(364); +const hasFlag = __webpack_require__(394); - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) +const env = process.env; - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e - } +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; +} - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) - } - this._emitMatch(index, e) - } - // This was the last one, and no stats were needed - return cb() - } +function translateLevel(level) { + if (level === 0) { + return false; + } - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e - } - this._process([e].concat(remain), index, inGlobStar, cb) - } - cb() + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; } -Glob.prototype._emitMatch = function (index, e) { - if (this.aborted) - return +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } - if (isIgnored(this, e)) - return + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } - if (this.paused) { - this._emitQueue.push([index, e]) - return - } + if (hasFlag('color=256')) { + return 2; + } - var abs = isAbsolute(e) ? e : this._makeAbs(e) + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } - if (this.mark) - e = this._mark(e) + const min = forceColor ? 1 : 0; - if (this.absolute) - e = abs + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(process.versions.node.split('.')[0]) >= 8 && + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } - if (this.matches[index][e]) - return + return 1; + } - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return - } + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } - this.matches[index][e] = true + return min; + } - var st = this.statCache[abs] - if (st) - this.emit('stat', e, st) + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } - this.emit('match', e) -} + if (env.COLORTERM === 'truecolor') { + return 3; + } -Glob.prototype._readdirInGlobStar = function (abs, cb) { - if (this.aborted) - return + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false, cb) + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } - var lstatkey = 'lstat\0' + abs - var self = this - var lstatcb = inflight(lstatkey, lstatcb_) + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } - if (lstatcb) - fs.lstat(abs, lstatcb) + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } - function lstatcb_ (er, lstat) { - if (er && er.code === 'ENOENT') - return cb() + if ('COLORTERM' in env) { + return 1; + } - var isSym = lstat && lstat.isSymbolicLink() - self.symlinks[abs] = isSym + if (env.TERM === 'dumb') { + return min; + } - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) { - self.cache[abs] = 'FILE' - cb() - } else - self._readdir(abs, false, cb) - } + return min; } -Glob.prototype._readdir = function (abs, inGlobStar, cb) { - if (this.aborted) - return - - cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) - if (!cb) - return +function getSupportLevel(stream) { + const level = supportsColor(stream); + return translateLevel(level); +} - //console.error('RD %j %j', +inGlobStar, abs) - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs, cb) +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) +}; - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return cb() - if (Array.isArray(c)) - return cb(null, c) - } +/***/ }), +/* 473 */ +/***/ (function(module, exports) { - var self = this - fs.readdir(abs, readdirCb(this, abs, cb)) -} +module.exports = require("zlib"); -function readdirCb (self, abs, cb) { - return function (er, entries) { - if (er) - self._readdirError(abs, er, cb) - else - self._readdirEntries(abs, entries, cb) - } -} +/***/ }), +/* 474 */ +/***/ (function(module) { -Glob.prototype._readdirEntries = function (abs, entries, cb) { - if (this.aborted) - return +module.exports = JSON.parse("{\"name\":\"axios\",\"version\":\"0.19.2\",\"description\":\"Promise based HTTP client for the browser and node.js\",\"main\":\"index.js\",\"scripts\":{\"test\":\"grunt test && bundlesize\",\"start\":\"node ./sandbox/server.js\",\"build\":\"NODE_ENV=production grunt build\",\"preversion\":\"npm test\",\"version\":\"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json\",\"postversion\":\"git push && git push --tags\",\"examples\":\"node ./examples/server.js\",\"coveralls\":\"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js\",\"fix\":\"eslint --fix lib/**/*.js\"},\"repository\":{\"type\":\"git\",\"url\":\"https://github.com/axios/axios.git\"},\"keywords\":[\"xhr\",\"http\",\"ajax\",\"promise\",\"node\"],\"author\":\"Matt Zabriskie\",\"license\":\"MIT\",\"bugs\":{\"url\":\"https://github.com/axios/axios/issues\"},\"homepage\":\"https://github.com/axios/axios\",\"devDependencies\":{\"bundlesize\":\"^0.17.0\",\"coveralls\":\"^3.0.0\",\"es6-promise\":\"^4.2.4\",\"grunt\":\"^1.0.2\",\"grunt-banner\":\"^0.6.0\",\"grunt-cli\":\"^1.2.0\",\"grunt-contrib-clean\":\"^1.1.0\",\"grunt-contrib-watch\":\"^1.0.0\",\"grunt-eslint\":\"^20.1.0\",\"grunt-karma\":\"^2.0.0\",\"grunt-mocha-test\":\"^0.13.3\",\"grunt-ts\":\"^6.0.0-beta.19\",\"grunt-webpack\":\"^1.0.18\",\"istanbul-instrumenter-loader\":\"^1.0.0\",\"jasmine-core\":\"^2.4.1\",\"karma\":\"^1.3.0\",\"karma-chrome-launcher\":\"^2.2.0\",\"karma-coverage\":\"^1.1.1\",\"karma-firefox-launcher\":\"^1.1.0\",\"karma-jasmine\":\"^1.1.1\",\"karma-jasmine-ajax\":\"^0.1.13\",\"karma-opera-launcher\":\"^1.0.0\",\"karma-safari-launcher\":\"^1.0.0\",\"karma-sauce-launcher\":\"^1.2.0\",\"karma-sinon\":\"^1.0.5\",\"karma-sourcemap-loader\":\"^0.3.7\",\"karma-webpack\":\"^1.7.0\",\"load-grunt-tasks\":\"^3.5.2\",\"minimist\":\"^1.2.0\",\"mocha\":\"^5.2.0\",\"sinon\":\"^4.5.0\",\"typescript\":\"^2.8.1\",\"url-search-params\":\"^0.10.0\",\"webpack\":\"^1.13.1\",\"webpack-dev-server\":\"^1.14.1\"},\"browser\":{\"./lib/adapters/http.js\":\"./lib/adapters/xhr.js\"},\"typings\":\"./index.d.ts\",\"dependencies\":{\"follow-redirects\":\"1.5.10\"},\"bundlesize\":[{\"path\":\"./dist/axios.min.js\",\"threshold\":\"5kB\"}]}"); - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } - } +/***/ }), +/* 475 */ +/***/ (function(module, exports, __webpack_require__) { - this.cache[abs] = entries - return cb(null, entries) -} +"use strict"; -Glob.prototype._readdirError = function (f, er, cb) { - if (this.aborted) - return - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f) - this.cache[abs] = 'FILE' - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd) - error.path = this.cwd - error.code = er.code - this.emit('error', error) - this.abort() - } - break +var utils = __webpack_require__(442); - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break +/** + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * @returns {Object} New object resulting from merging config2 to config1 + */ +module.exports = function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + var config = {}; - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) { - this.emit('error', er) - // If the error is handled, then we abort - // if not, we threw out of here - this.abort() - } - if (!this.silent) - console.error('glob error', er) - break - } - - return cb() -} - -Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }) -} + var valueFromConfig2Keys = ['url', 'method', 'params', 'data']; + var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy']; + var defaultToConfig2Keys = [ + 'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer', + 'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', + 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', + 'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent', + 'httpsAgent', 'cancelToken', 'socketPath' + ]; + utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { + if (typeof config2[prop] !== 'undefined') { + config[prop] = config2[prop]; + } + }); -Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { - //console.error('pgs2', prefix, remain[0], entries) + utils.forEach(mergeDeepPropertiesKeys, function mergeDeepProperties(prop) { + if (utils.isObject(config2[prop])) { + config[prop] = utils.deepMerge(config1[prop], config2[prop]); + } else if (typeof config2[prop] !== 'undefined') { + config[prop] = config2[prop]; + } else if (utils.isObject(config1[prop])) { + config[prop] = utils.deepMerge(config1[prop]); + } else if (typeof config1[prop] !== 'undefined') { + config[prop] = config1[prop]; + } + }); - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return cb() + utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { + if (typeof config2[prop] !== 'undefined') { + config[prop] = config2[prop]; + } else if (typeof config1[prop] !== 'undefined') { + config[prop] = config1[prop]; + } + }); - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) + var axiosKeys = valueFromConfig2Keys + .concat(mergeDeepPropertiesKeys) + .concat(defaultToConfig2Keys); - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false, cb) + var otherKeys = Object + .keys(config2) + .filter(function filterAxiosKeys(key) { + return axiosKeys.indexOf(key) === -1; + }); - var isSym = this.symlinks[abs] - var len = entries.length + utils.forEach(otherKeys, function otherKeysDefaultToConfig2(prop) { + if (typeof config2[prop] !== 'undefined') { + config[prop] = config2[prop]; + } else if (typeof config1[prop] !== 'undefined') { + config[prop] = config1[prop]; + } + }); - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return cb() + return config; +}; - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true, cb) +/***/ }), +/* 476 */ +/***/ (function(module, exports, __webpack_require__) { - var below = gspref.concat(entries[i], remain) - this._process(below, index, true, cb) - } +"use strict"; - cb() -} -Glob.prototype._processSimple = function (prefix, index, cb) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var self = this - this._stat(prefix, function (er, exists) { - self._processSimple2(prefix, index, er, exists, cb) - }) +/** + * A `Cancel` is an object that is thrown when an operation is canceled. + * + * @class + * @param {string=} message The message. + */ +function Cancel(message) { + this.message = message; } -Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { - - //console.error('ps2', prefix, exists) - - if (!this.matches[index]) - this.matches[index] = Object.create(null) - - // If it doesn't exist, then just mark the lack of results - if (!exists) - return cb() - - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' - } - } - - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') - // Mark this as a match - this._emitMatch(index, prefix) - cb() -} +Cancel.prototype.toString = function toString() { + return 'Cancel' + (this.message ? ': ' + this.message : ''); +}; -// Returns either 'DIR', 'FILE', or false -Glob.prototype._stat = function (f, cb) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' +Cancel.prototype.__CANCEL__ = true; - if (f.length > this.maxLength) - return cb() +module.exports = Cancel; - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (Array.isArray(c)) - c = 'DIR' +/***/ }), +/* 477 */ +/***/ (function(module, exports, __webpack_require__) { - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return cb(null, c) +"use strict"; - if (needDir && c === 'FILE') - return cb() - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } +var Cancel = __webpack_require__(476); - var exists - var stat = this.statCache[abs] - if (stat !== undefined) { - if (stat === false) - return cb(null, stat) - else { - var type = stat.isDirectory() ? 'DIR' : 'FILE' - if (needDir && type === 'FILE') - return cb() - else - return cb(null, type, stat) - } +/** + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @class + * @param {Function} executor The executor function. + */ +function CancelToken(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); } - var self = this - var statcb = inflight('stat\0' + abs, lstatcb_) - if (statcb) - fs.lstat(abs, statcb) + var resolvePromise; + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); - function lstatcb_ (er, lstat) { - if (lstat && lstat.isSymbolicLink()) { - // If it's a symlink, then treat it as the target, unless - // the target does not exist, then treat it as a file. - return fs.stat(abs, function (er, stat) { - if (er) - self._stat2(f, abs, null, lstat, cb) - else - self._stat2(f, abs, er, stat, cb) - }) - } else { - self._stat2(f, abs, er, lstat, cb) + var token = this; + executor(function cancel(message) { + if (token.reason) { + // Cancellation has already been requested + return; } - } + + token.reason = new Cancel(message); + resolvePromise(token.reason); + }); } -Glob.prototype._stat2 = function (f, abs, er, stat, cb) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return cb() +/** + * Throws a `Cancel` if cancellation has been requested. + */ +CancelToken.prototype.throwIfRequested = function throwIfRequested() { + if (this.reason) { + throw this.reason; } +}; - var needDir = f.slice(-1) === '/' - this.statCache[abs] = stat - - if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) - return cb(null, false, stat) - - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' - this.cache[abs] = this.cache[abs] || c - - if (needDir && c === 'FILE') - return cb() +/** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ +CancelToken.source = function source() { + var cancel; + var token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token: token, + cancel: cancel + }; +}; - return cb(null, c, stat) -} +module.exports = CancelToken; /***/ }), -/* 504 */ +/* 478 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = realpath -realpath.realpath = realpath -realpath.sync = realpathSync -realpath.realpathSync = realpathSync -realpath.monkeypatch = monkeypatch -realpath.unmonkeypatch = unmonkeypatch - -var fs = __webpack_require__(23) -var origRealpath = fs.realpath -var origRealpathSync = fs.realpathSync - -var version = process.version -var ok = /^v[0-5]\./.test(version) -var old = __webpack_require__(505) - -function newError (er) { - return er && er.syscall === 'realpath' && ( - er.code === 'ELOOP' || - er.code === 'ENOMEM' || - er.code === 'ENAMETOOLONG' - ) -} +"use strict"; -function realpath (p, cache, cb) { - if (ok) { - return origRealpath(p, cache, cb) - } - if (typeof cache === 'function') { - cb = cache - cache = null - } - origRealpath(p, cache, function (er, result) { - if (newError(er)) { - old.realpath(p, cache, cb) - } else { - cb(er, result) - } - }) -} +/** + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * @returns {Function} + */ +module.exports = function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; +}; -function realpathSync (p, cache) { - if (ok) { - return origRealpathSync(p, cache) - } - try { - return origRealpathSync(p, cache) - } catch (er) { - if (newError(er)) { - return old.realpathSync(p, cache) - } else { - throw er - } - } -} +/***/ }), +/* 479 */ +/***/ (function(module, exports, __webpack_require__) { -function monkeypatch () { - fs.realpath = realpath - fs.realpathSync = realpathSync -} +"use strict"; -function unmonkeypatch () { - fs.realpath = origRealpath - fs.realpathSync = origRealpathSync -} +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = __webpack_require__(6); +tslib_1.__exportStar(__webpack_require__(480), exports); /***/ }), -/* 505 */ +/* 480 */ /***/ (function(module, exports, __webpack_require__) { -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var pathModule = __webpack_require__(16); -var isWindows = process.platform === 'win32'; -var fs = __webpack_require__(23); +"use strict"; -// JavaScript implementation of realpath, ported from node pre-v6 +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isAxiosRequestError = (error) => { + return error && error.config && error.response === undefined; +}; +exports.isAxiosResponseError = (error) => { + return error && error.response && error.response.status !== undefined; +}; -var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); -function rethrow() { - // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and - // is fairly slow to generate. - var callback; - if (DEBUG) { - var backtrace = new Error; - callback = debugCallback; - } else - callback = missingCallback; +/***/ }), +/* 481 */ +/***/ (function(module, exports, __webpack_require__) { - return callback; +"use strict"; - function debugCallback(err) { - if (err) { - backtrace.message = err.message; - err = backtrace; - missingCallback(err); +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +class KbnClientStatus { + constructor(requester) { + this.requester = requester; } - } - - function missingCallback(err) { - if (err) { - if (process.throwDeprecation) - throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs - else if (!process.noDeprecation) { - var msg = 'fs: missing callback ' + (err.stack || err.message); - if (process.traceDeprecation) - console.trace(msg); - else - console.error(msg); - } + /** + * Get the full server status + */ + async get() { + return await this.requester.request({ + method: 'GET', + path: 'api/status', + }); + } + /** + * Get the overall/merged state + */ + async getOverallState() { + const status = await this.get(); + return status.status.overall.state; } - } } +exports.KbnClientStatus = KbnClientStatus; -function maybeCallback(cb) { - return typeof cb === 'function' ? cb : rethrow(); -} -var normalize = pathModule.normalize; +/***/ }), +/* 482 */ +/***/ (function(module, exports, __webpack_require__) { -// Regexp that finds the next partion of a (partial) path -// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] -if (isWindows) { - var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; -} else { - var nextPartRe = /(.*?)(?:[\/]+|$)/g; -} +"use strict"; -// Regex to find the device root, including trailing slash. E.g. 'c:\\'. -if (isWindows) { - var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; -} else { - var splitRootRe = /^[\/]*/; +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const PLUGIN_STATUS_ID = /^plugin:(.+?)@/; +class KbnClientPlugins { + constructor(status) { + this.status = status; + } + /** + * Get a list of plugin ids that are enabled on the server + */ + async getEnabledIds() { + const pluginIds = []; + const apiResp = await this.status.get(); + for (const status of apiResp.status.statuses) { + if (status.id) { + const match = status.id.match(PLUGIN_STATUS_ID); + if (match) { + pluginIds.push(match[1]); + } + } + } + return pluginIds; + } } +exports.KbnClientPlugins = KbnClientPlugins; -exports.realpathSync = function realpathSync(p, cache) { - // make p is absolute - p = pathModule.resolve(p); - - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return cache[p]; - } - - var original = p, - seenLinks = {}, - knownHard = {}; - - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; - - start(); - - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstatSync(base); - knownHard[base] = true; - } - } +/***/ }), +/* 483 */ +/***/ (function(module, exports, __webpack_require__) { - // walk down the path, swapping out linked pathparts for their real - // values - // NB: p.length changes. - while (pos < p.length) { - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; +"use strict"; - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - continue; +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +class KbnClientVersion { + constructor(status) { + this.status = status; } - - var resolvedLink; - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // some known symbolic link. no need to stat again. - resolvedLink = cache[base]; - } else { - var stat = fs.lstatSync(base); - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - continue; - } - - // read the link if it wasn't read before - // dev/ino always return 0 on windows, so skip the check. - var linkTarget = null; - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - linkTarget = seenLinks[id]; + async get() { + if (this.versionCache !== undefined) { + return this.versionCache; } - } - if (linkTarget === null) { - fs.statSync(base); - linkTarget = fs.readlinkSync(base); - } - resolvedLink = pathModule.resolve(previous, linkTarget); - // track this, if given a cache. - if (cache) cache[base] = resolvedLink; - if (!isWindows) seenLinks[id] = linkTarget; + const status = await this.status.get(); + this.versionCache = status.version.number + (status.version.build_snapshot ? '-SNAPSHOT' : ''); + return this.versionCache; } +} +exports.KbnClientVersion = KbnClientVersion; - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); - } - - if (cache) cache[original] = p; - - return p; -}; - - -exports.realpath = function realpath(p, cache, cb) { - if (typeof cb !== 'function') { - cb = maybeCallback(cache); - cache = null; - } - // make p is absolute - p = pathModule.resolve(p); +/***/ }), +/* 484 */ +/***/ (function(module, exports, __webpack_require__) { - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return process.nextTick(cb.bind(null, null, cache[p])); - } +"use strict"; - var original = p, - seenLinks = {}, - knownHard = {}; +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const kbn_client_requester_1 = __webpack_require__(438); +class KbnClientSavedObjects { + constructor(log, requester) { + this.log = log; + this.requester = requester; + } + /** + * Run the saved objects migration + */ + async migrate() { + this.log.debug('Migrating saved objects'); + return await this.requester.request({ + description: 'migrate saved objects', + path: kbn_client_requester_1.uriencode `/internal/saved_objects/_migrate`, + method: 'POST', + body: {}, + }); + } + /** + * Get an object + */ + async get(options) { + this.log.debug('Gettings saved object: %j', options); + return await this.requester.request({ + description: 'get saved object', + path: kbn_client_requester_1.uriencode `/api/saved_objects/${options.type}/${options.id}`, + method: 'GET', + }); + } + /** + * Create a saved object + */ + async create(options) { + this.log.debug('Creating saved object: %j', options); + return await this.requester.request({ + description: 'update saved object', + path: options.id + ? kbn_client_requester_1.uriencode `/api/saved_objects/${options.type}/${options.id}` + : kbn_client_requester_1.uriencode `/api/saved_objects/${options.type}`, + query: { + overwrite: options.overwrite, + }, + method: 'POST', + body: { + attributes: options.attributes, + migrationVersion: options.migrationVersion, + references: options.references, + }, + }); + } + /** + * Update a saved object + */ + async update(options) { + this.log.debug('Updating saved object: %j', options); + return await this.requester.request({ + description: 'update saved object', + path: kbn_client_requester_1.uriencode `/api/saved_objects/${options.type}/${options.id}`, + query: { + overwrite: options.overwrite, + }, + method: 'PUT', + body: { + attributes: options.attributes, + migrationVersion: options.migrationVersion, + references: options.references, + }, + }); + } + /** + * Delete an object + */ + async delete(options) { + this.log.debug('Deleting saved object %s/%s', options); + return await this.requester.request({ + description: 'delete saved object', + path: kbn_client_requester_1.uriencode `/api/saved_objects/${options.type}/${options.id}`, + method: 'DELETE', + }); + } +} +exports.KbnClientSavedObjects = KbnClientSavedObjects; - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; - start(); +/***/ }), +/* 485 */ +/***/ (function(module, exports, __webpack_require__) { - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; +"use strict"; - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstat(base, function(err) { - if (err) return cb(err); - knownHard[base] = true; - LOOP(); - }); - } else { - process.nextTick(LOOP); +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const kbn_client_requester_1 = __webpack_require__(438); +class KbnClientUiSettings { + constructor(log, requester, defaults) { + this.log = log; + this.requester = requester; + this.defaults = defaults; } - } - - // walk down the path, swapping out linked pathparts for their real - // values - function LOOP() { - // stop if scanned past end of path - if (pos >= p.length) { - if (cache) cache[original] = p; - return cb(null, p); + async get(setting) { + var _a; + const all = await this.getAll(); + const value = (_a = all[setting]) === null || _a === void 0 ? void 0 : _a.userValue; + this.log.verbose('uiSettings.value: %j', value); + return value; } - - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; - - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - return process.nextTick(LOOP); + /** + * Gets defaultIndex from the config doc. + */ + async getDefaultIndex() { + return await this.get('defaultIndex'); } - - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // known symbolic link. no need to stat again. - return gotResolvedLink(cache[base]); + /** + * Unset a uiSetting + */ + async unset(setting) { + return await this.requester.request({ + path: kbn_client_requester_1.uriencode `/api/kibana/settings/${setting}`, + method: 'DELETE', + }); } - - return fs.lstat(base, gotStat); - } - - function gotStat(err, stat) { - if (err) return cb(err); - - // if not a symlink, skip to the next path part - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - return process.nextTick(LOOP); + /** + * Replace all uiSettings with the `doc` values, `doc` is merged + * with some defaults + */ + async replace(doc, { retries = 5 } = {}) { + this.log.debug('replacing kibana config doc: %j', doc); + const changes = { + ...this.defaults, + ...doc, + }; + for (const [name, { isOverridden }] of Object.entries(await this.getAll())) { + if (!isOverridden && !changes.hasOwnProperty(name)) { + changes[name] = null; + } + } + await this.requester.request({ + method: 'POST', + path: '/api/kibana/settings', + body: { changes }, + retries, + }); } - - // stat & read the link if not read before - // call gotTarget as soon as the link target is known - // dev/ino always return 0 on windows, so skip the check. - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - return gotTarget(null, seenLinks[id], base); - } + /** + * Add fields to the config doc (like setting timezone and defaultIndex) + */ + async update(updates) { + this.log.debug('applying update to kibana config: %j', updates); + await this.requester.request({ + path: '/api/kibana/settings', + method: 'POST', + body: { + changes: updates, + }, + }); } - fs.stat(base, function(err) { - if (err) return cb(err); + async getAll() { + const resp = await this.requester.request({ + path: '/api/kibana/settings', + method: 'GET', + }); + return resp.settings; + } +} +exports.KbnClientUiSettings = KbnClientUiSettings; - fs.readlink(base, function(err, target) { - if (!isWindows) seenLinks[id] = target; - gotTarget(err, target); - }); - }); - } - function gotTarget(err, target, base) { - if (err) return cb(err); +/***/ }), +/* 486 */ +/***/ (function(module, exports, __webpack_require__) { - var resolvedLink = pathModule.resolve(previous, target); - if (cache) cache[base] = resolvedLink; - gotResolvedLink(resolvedLink); - } +"use strict"; - function gotResolvedLink(resolvedLink) { - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); - } -}; +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = __webpack_require__(6); +tslib_1.__exportStar(__webpack_require__(487), exports); /***/ }), -/* 506 */ +/* 487 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = minimatch -minimatch.Minimatch = Minimatch - -var path = { sep: '/' } -try { - path = __webpack_require__(16) -} catch (er) {} - -var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} -var expand = __webpack_require__(507) - -var plTypes = { - '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, - '?': { open: '(?:', close: ')?' }, - '+': { open: '(?:', close: ')+' }, - '*': { open: '(?:', close: ')*' }, - '@': { open: '(?:', close: ')' } -} +"use strict"; -// any single thing other than / -// don't need to escape / when using new RegExp() -var qmark = '[^/]' - -// * => any number of characters -var star = qmark + '*?' +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = __webpack_require__(6); +const util_1 = __webpack_require__(397); +const axios_1 = tslib_1.__importDefault(__webpack_require__(440)); +function parseConfig(log) { + const configJson = process.env.KIBANA_CI_STATS_CONFIG; + if (!configJson) { + log.debug('KIBANA_CI_STATS_CONFIG environment variable not found, disabling CiStatsReporter'); + return; + } + let config; + try { + config = JSON.parse(configJson); + } + catch (_) { + // handled below + } + if (typeof config === 'object' && config !== null) { + return validateConfig(log, config); + } + log.warning('KIBANA_CI_STATS_CONFIG is invalid, stats will not be reported'); + return; +} +function validateConfig(log, config) { + const validApiUrl = typeof config.apiUrl === 'string' && config.apiUrl.length !== 0; + if (!validApiUrl) { + log.warning('KIBANA_CI_STATS_CONFIG is missing a valid api url, stats will not be reported'); + return; + } + const validApiToken = typeof config.apiToken === 'string' && config.apiToken.length !== 0; + if (!validApiToken) { + log.warning('KIBANA_CI_STATS_CONFIG is missing a valid api token, stats will not be reported'); + return; + } + const validId = typeof config.buildId === 'string' && config.buildId.length !== 0; + if (!validId) { + log.warning('KIBANA_CI_STATS_CONFIG is missing a valid build id, stats will not be reported'); + return; + } + return config; +} +class CiStatsReporter { + constructor(config, log) { + this.config = config; + this.log = log; + } + static fromEnv(log) { + return new CiStatsReporter(parseConfig(log), log); + } + isEnabled() { + return !!this.config; + } + async metrics(metrics) { + var _a, _b, _c, _d; + if (!this.config) { + return; + } + let attempt = 0; + const maxAttempts = 5; + const bodySummary = metrics + .map(({ group, id, value }) => `[${group}/${id}=${value}]`) + .join(' '); + while (true) { + attempt += 1; + try { + await axios_1.default.request({ + method: 'POST', + url: '/v1/metrics', + baseURL: this.config.apiUrl, + headers: { + Authorization: `token ${this.config.apiToken}`, + }, + data: { + buildId: this.config.buildId, + metrics, + }, + }); + return; + } + catch (error) { + if (!((_a = error) === null || _a === void 0 ? void 0 : _a.request)) { + // not an axios error, must be a usage error that we should notify user about + throw error; + } + if (((_b = error) === null || _b === void 0 ? void 0 : _b.response) && error.response.status !== 502) { + // error response from service was received so warn the user and move on + this.log.warning(`error recording metric [status=${error.response.status}] [resp=${util_1.inspect(error.response.data)}] ${bodySummary}`); + return; + } + if (attempt === maxAttempts) { + this.log.warning(`failed to reach kibana-ci-stats service too many times, unable to record metric ${bodySummary}`); + return; + } + // we failed to reach the backend and we have remaining attempts, lets retry after a short delay + const reason = ((_d = (_c = error) === null || _c === void 0 ? void 0 : _c.response) === null || _d === void 0 ? void 0 : _d.status) ? `${error.response.status} response` + : 'no response'; + this.log.warning(`failed to reach kibana-ci-stats service [reason=${reason}], retrying in ${attempt} seconds`); + await new Promise((resolve) => setTimeout(resolve, attempt * 1000)); + } + } + } +} +exports.CiStatsReporter = CiStatsReporter; -// ** when dots are allowed. Anything goes, except .. and . -// not (^ or / followed by one or two dots followed by $ or /), -// followed by anything, any number of times. -var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' -// not a ^ or / followed by a dot, -// followed by anything, any number of times. -var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' +/***/ }), +/* 488 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -// characters that need to be escaped in RegExp. -var reSpecials = charSet('().*{}+?[]^$\\!') +"use strict"; +__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__(489); +/* harmony import */ var _clean__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(581); +/* harmony import */ var _run__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(686); +/* harmony import */ var _watch__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(687); +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ -// "abc" -> { a:true, b:true, c:true } -function charSet (s) { - return s.split('').reduce(function (set, c) { - set[c] = true - return set - }, {}) -} -// normalizes slashes. -var slashSplit = /\/+/ -minimatch.filter = filter -function filter (pattern, options) { - options = options || {} - return function (p, i, list) { - return minimatch(p, pattern, options) - } -} -function ext (a, b) { - a = a || {} - b = b || {} - var t = {} - Object.keys(b).forEach(function (k) { - t[k] = b[k] - }) - Object.keys(a).forEach(function (k) { - t[k] = a[k] - }) - return t -} +const commands = { + bootstrap: _bootstrap__WEBPACK_IMPORTED_MODULE_0__["BootstrapCommand"], + clean: _clean__WEBPACK_IMPORTED_MODULE_1__["CleanCommand"], + run: _run__WEBPACK_IMPORTED_MODULE_2__["RunCommand"], + watch: _watch__WEBPACK_IMPORTED_MODULE_3__["WatchCommand"] +}; -minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return minimatch +/***/ }), +/* 489 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - var orig = minimatch +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BootstrapCommand", function() { return BootstrapCommand; }); +/* harmony import */ var _utils_link_project_executables__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(490); +/* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(500); +/* harmony import */ var _utils_parallelize__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(501); +/* harmony import */ var _utils_projects__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(502); +/* harmony import */ var _utils_project_checksums__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(575); +/* harmony import */ var _utils_bootstrap_cache_file__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(580); +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ - var m = function minimatch (p, pattern, options) { - return orig.minimatch(p, pattern, ext(def, options)) - } - m.Minimatch = function Minimatch (pattern, options) { - return new orig.Minimatch(pattern, ext(def, options)) - } - return m -} -Minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return Minimatch - return minimatch.defaults(def).Minimatch -} -function minimatch (p, pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') - } - if (!options) options = {} +const BootstrapCommand = { + description: 'Install dependencies and crosslink projects', + name: 'bootstrap', - // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - return false - } + async run(projects, projectGraph, { + options, + kbn + }) { + const batchedProjectsByWorkspace = Object(_utils_projects__WEBPACK_IMPORTED_MODULE_3__["topologicallyBatchProjects"])(projects, projectGraph, { + batchByWorkspace: true + }); + const batchedProjects = Object(_utils_projects__WEBPACK_IMPORTED_MODULE_3__["topologicallyBatchProjects"])(projects, projectGraph); + const extraArgs = [...(options['frozen-lockfile'] === true ? ['--frozen-lockfile'] : []), ...(options['prefer-offline'] === true ? ['--prefer-offline'] : [])]; - // "" only matches "" - if (pattern.trim() === '') return p === '' + for (const batch of batchedProjectsByWorkspace) { + for (const project of batch) { + if (project.isWorkspaceProject) { + _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].verbose(`Skipping workspace project: ${project.name}`); + continue; + } - return new Minimatch(pattern, options).match(p) -} + if (project.hasDependencies()) { + await project.installDependencies({ + extraArgs + }); + } + } + } -function Minimatch (pattern, options) { - if (!(this instanceof Minimatch)) { - return new Minimatch(pattern, options) - } + await Object(_utils_link_project_executables__WEBPACK_IMPORTED_MODULE_0__["linkProjectExecutables"])(projects, projectGraph); + /** + * At the end of the bootstrapping process we call all `kbn:bootstrap` scripts + * in the list of projects. We do this because some projects need to be + * transpiled before they can be used. Ideally we shouldn't do this unless we + * have to, as it will slow down the bootstrapping process. + */ - if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') - } + const checksums = await Object(_utils_project_checksums__WEBPACK_IMPORTED_MODULE_4__["getAllChecksums"])(kbn, _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"]); + const caches = new Map(); + let cachedProjectCount = 0; - if (!options) options = {} - pattern = pattern.trim() + for (const project of projects.values()) { + if (project.hasScript('kbn:bootstrap')) { + const file = new _utils_bootstrap_cache_file__WEBPACK_IMPORTED_MODULE_5__["BootstrapCacheFile"](kbn, project, checksums); + const valid = options.cache && file.isValid(); - // windows support: need to use /, not \ - if (path.sep !== '/') { - pattern = pattern.split(path.sep).join('/') - } + if (valid) { + _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].debug(`[${project.name}] cache up to date`); + } - this.options = options - this.set = [] - this.pattern = pattern - this.regexp = null - this.negate = false - this.comment = false - this.empty = false + caches.set(project, { + file, + valid + }); + cachedProjectCount += 1; + } + } - // make the set of regexps etc. - this.make() -} + if (cachedProjectCount > 0) { + _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].success(`${cachedProjectCount} bootsrap builds are cached`); + } -Minimatch.prototype.debug = function () {} + await Object(_utils_parallelize__WEBPACK_IMPORTED_MODULE_2__["parallelizeBatches"])(batchedProjects, async project => { + const cache = caches.get(project); -Minimatch.prototype.make = make -function make () { - // don't do it more than once. - if (this._made) return + if (cache && !cache.valid) { + _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].info(`[${project.name}] running [kbn:bootstrap] script`); + cache.file.delete(); + await project.runScriptStreaming('kbn:bootstrap'); + cache.file.write(); + _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].success(`[${project.name}] bootstrap complete`); + } + }); + } - var pattern = this.pattern - var options = this.options +}; - // empty patterns and comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - this.comment = true - return - } - if (!pattern) { - this.empty = true - return - } +/***/ }), +/* 490 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - // step 1: figure out negation, etc. - this.parseNegate() +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "linkProjectExecutables", function() { return linkProjectExecutables; }); +/* 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__(491); +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(500); +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ - // step 2: expand braces - var set = this.globSet = this.braceExpand() - if (options.debug) this.debug = console.error - this.debug(this.pattern, set) - // step 3: now we have a set, so turn each one into a series of path-portion - // matching patterns. - // These will be regexps, except in the case of "**", which is - // set to the GLOBSTAR object for globstar behavior, - // and will not contain any / characters - set = this.globParts = set.map(function (s) { - return s.split(slashSplit) - }) +/** + * Yarn does not link the executables from dependencies that are installed + * using `link:` https://github.com/yarnpkg/yarn/pull/5046 + * + * We simulate this functionality by walking through each project's project + * dependencies, and manually linking their executables if defined. The logic + * for linking was mostly adapted from lerna: https://github.com/lerna/lerna/blob/1d7eb9eeff65d5a7de64dea73613b1bf6bfa8d57/src/PackageUtilities.js#L348 + */ +async function linkProjectExecutables(projectsByName, projectGraph) { + _log__WEBPACK_IMPORTED_MODULE_2__["log"].debug(`Linking package executables`); - this.debug(this.pattern, set) + for (const [projectName, projectDeps] of projectGraph) { + const project = projectsByName.get(projectName); + const binsDir = Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(project.nodeModulesLocation, '.bin'); - // glob --> regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) + for (const projectDep of projectDeps) { + const executables = projectDep.getExecutables(); - this.debug(this.pattern, set) + for (const name of Object.keys(executables)) { + const srcPath = executables[name]; // existing logic from lerna -- ensure that the bin we are going to + // point to exists or ignore it - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }) + if (!(await Object(_fs__WEBPACK_IMPORTED_MODULE_1__["isFile"])(srcPath))) { + continue; + } - this.debug(this.pattern, set) + const dest = Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(binsDir, name); // Get relative project path with normalized path separators. - this.set = set + const projectRelativePath = Object(path__WEBPACK_IMPORTED_MODULE_0__["relative"])(project.path, srcPath).split(path__WEBPACK_IMPORTED_MODULE_0__["sep"]).join('/'); + _log__WEBPACK_IMPORTED_MODULE_2__["log"].debug(`[${project.name}] ${name} -> ${projectRelativePath}`); + await Object(_fs__WEBPACK_IMPORTED_MODULE_1__["mkdirp"])(Object(path__WEBPACK_IMPORTED_MODULE_0__["dirname"])(dest)); + await Object(_fs__WEBPACK_IMPORTED_MODULE_1__["createSymlink"])(srcPath, dest, 'exec'); + await Object(_fs__WEBPACK_IMPORTED_MODULE_1__["chmod"])(dest, '755'); + } + } + } } -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - var negate = false - var options = this.options - var negateOffset = 0 +/***/ }), +/* 491 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - if (options.nonegate) return +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readFile", function() { return readFile; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "chmod", function() { return chmod; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mkdirp", function() { return mkdirp; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unlink", function() { return unlink; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "copyDirectory", function() { return copyDirectory; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSymlink", function() { return isSymlink; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDirectory", function() { return isDirectory; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFile", function() { return isFile; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createSymlink", function() { return createSymlink; }); +/* harmony import */ var cmd_shim__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(492); +/* harmony import */ var cmd_shim__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(cmd_shim__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(349); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var ncp__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(499); +/* harmony import */ var ncp__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(ncp__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 util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(397); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_4__); +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate - negateOffset++ - } - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} -// Brace expansion: -// a{b,c}d -> abd acd -// a{b,}c -> abc ac -// a{0..3}d -> a0d a1d a2d a3d -// a{b,c{d,e}f}g -> abg acdfg acefg -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg -// -// Invalid sets are not expanded. -// a{2..}b -> a{2..}b -// a{b}c -> a{b}c -minimatch.braceExpand = function (pattern, options) { - return braceExpand(pattern, options) -} -Minimatch.prototype.braceExpand = braceExpand -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch) { - options = this.options - } else { - options = {} - } - } +const lstat = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.lstat); +const readFile = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.readFile); +const symlink = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.symlink); +const chmod = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.chmod); +const cmdShim = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(cmd_shim__WEBPACK_IMPORTED_MODULE_0___default.a); +const mkdir = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.mkdir); +const mkdirp = async path => await mkdir(path, { + recursive: true +}); +const unlink = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.unlink); +const copyDirectory = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(ncp__WEBPACK_IMPORTED_MODULE_2__["ncp"]); - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern +async function statTest(path, block) { + try { + return block((await lstat(path))); + } catch (e) { + if (e.code === 'ENOENT') { + return false; + } - if (typeof pattern === 'undefined') { - throw new TypeError('undefined pattern') + throw e; } +} +/** + * Test if a path points to a symlink. + * @param path + */ - if (options.nobrace || - !pattern.match(/\{.*\}/)) { - // shortcut. no need to expand. - return [pattern] - } - return expand(pattern) +async function isSymlink(path) { + return await statTest(path, stats => stats.isSymbolicLink()); } +/** + * Test if a path points to a directory. + * @param path + */ -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -Minimatch.prototype.parse = parse -var SUBPARSE = {} -function parse (pattern, isSub) { - if (pattern.length > 1024 * 64) { - throw new TypeError('pattern is too long') - } - - var options = this.options - - // shortcuts - if (!options.noglobstar && pattern === '**') return GLOBSTAR - if (pattern === '') return '' +async function isDirectory(path) { + return await statTest(path, stats => stats.isDirectory()); +} +/** + * Test if a path points to a regular file. + * @param path + */ - var re = '' - var hasMagic = !!options.nocase - var escaping = false - // ? => one single character - var patternListStack = [] - var negativeLists = [] - var stateChar - var inClass = false - var reClassStart = -1 - var classStart = -1 - // . and .. never match anything that doesn't start with ., - // even when options.dot is set. - var patternStart = pattern.charAt(0) === '.' ? '' // anything - // not (start or / followed by . or .. followed by / or end) - : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' - : '(?!\\.)' - var self = this +async function isFile(path) { + return await statTest(path, stats => stats.isFile()); +} +/** + * Create a symlink at dest that points to src. Adapted from + * https://github.com/lerna/lerna/blob/2f1b87d9e2295f587e4ac74269f714271d8ed428/src/FileSystemUtilities.js#L103. + * + * @param src + * @param dest + * @param type 'dir', 'file', 'junction', or 'exec'. 'exec' on + * windows will use the `cmd-shim` module since symlinks can't be used + * for executable files on windows. + */ - function clearStateChar () { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case '*': - re += star - hasMagic = true - break - case '?': - re += qmark - hasMagic = true - break - default: - re += '\\' + stateChar - break - } - self.debug('clearStateChar %j %j', stateChar, re) - stateChar = false +async function createSymlink(src, dest, type) { + if (process.platform === 'win32') { + if (type === 'exec') { + await cmdShim(src, dest); + } else { + await forceCreate(src, dest, type); } + } else { + const posixType = type === 'exec' ? 'file' : type; + const relativeSource = Object(path__WEBPACK_IMPORTED_MODULE_3__["relative"])(Object(path__WEBPACK_IMPORTED_MODULE_3__["dirname"])(dest), src); + await forceCreate(relativeSource, dest, posixType); } +} - for (var i = 0, len = pattern.length, c - ; (i < len) && (c = pattern.charAt(i)) - ; i++) { - this.debug('%s\t%s %s %j', pattern, i, re, c) - - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += '\\' + c - escaping = false - continue +async function forceCreate(src, dest, type) { + try { + // If something exists at `dest` we need to remove it first. + await unlink(dest); + } catch (error) { + if (error.code !== 'ENOENT') { + throw error; } + } - switch (c) { - case '/': - // completely not allowed, even escaped. - // Should already be path-split by now. - return false - - case '\\': - clearStateChar() - escaping = true - continue - - // the various stateChar values - // for the "extglob" stuff. - case '?': - case '*': - case '+': - case '@': - case '!': - this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) - - // all of those are literals inside a class, except that - // the glob [!a] means [^a] in regexp - if (inClass) { - this.debug(' in class') - if (c === '!' && i === classStart + 1) c = '^' - re += c - continue - } - - // if we already have a stateChar, then it means - // that there was something like ** or +? in there. - // Handle the stateChar, then proceed with this one. - self.debug('call clearStateChar %j', stateChar) - clearStateChar() - stateChar = c - // if extglob is disabled, then +(asdf|foo) isn't a thing. - // just clear the statechar *now*, rather than even diving into - // the patternList stuff. - if (options.noext) clearStateChar() - continue - - case '(': - if (inClass) { - re += '(' - continue - } - - if (!stateChar) { - re += '\\(' - continue - } - - patternListStack.push({ - type: stateChar, - start: i - 1, - reStart: re.length, - open: plTypes[stateChar].open, - close: plTypes[stateChar].close - }) - // negation is (?:(?!js)[^/]*) - re += stateChar === '!' ? '(?:(?!(?:' : '(?:' - this.debug('plType %j %j', stateChar, re) - stateChar = false - continue - - case ')': - if (inClass || !patternListStack.length) { - re += '\\)' - continue - } - - clearStateChar() - hasMagic = true - var pl = patternListStack.pop() - // negation is (?:(?!js)[^/]*) - // The others are (?:) - re += pl.close - if (pl.type === '!') { - negativeLists.push(pl) - } - pl.reEnd = re.length - continue - - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|' - escaping = false - continue - } - - clearStateChar() - re += '|' - continue + await symlink(src, dest, type); +} - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() +/***/ }), +/* 492 */ +/***/ (function(module, exports, __webpack_require__) { - if (inClass) { - re += '\\' + c - continue - } +// On windows, create a .cmd file. +// Read the #! in the file to see what it uses. The vast majority +// of the time, this will be either: +// "#!/usr/bin/env " +// or: +// "#! " +// +// Write a binroot/pkg.bin + ".cmd" file that has this line in it: +// @ %~dp0 %* - inClass = true - classStart = i - reClassStart = re.length - re += c - continue +module.exports = cmdShim +cmdShim.ifExists = cmdShimIfExists - case ']': - // a right bracket shall lose its special - // meaning and represent itself in - // a bracket expression if it occurs - // first in the list. -- POSIX.2 2.8.3.2 - if (i === classStart + 1 || !inClass) { - re += '\\' + c - escaping = false - continue - } +var fs = __webpack_require__(493) - // handle the case where we left a class open. - // "[z-a]" is valid, equivalent to "\[z-a\]" - if (inClass) { - // split where the last [ was, make sure we don't have - // an invalid re. if so, re-walk the contents of the - // would-be class to re-translate any characters that - // were passed through as-is - // TODO: It would probably be faster to determine this - // without a try/catch and a new RegExp, but it's tricky - // to do safely. For now, this is safe and works. - var cs = pattern.substring(classStart + 1, i) - try { - RegExp('[' + cs + ']') - } catch (er) { - // not a valid class! - var sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' - hasMagic = hasMagic || sp[1] - inClass = false - continue - } - } +var mkdir = __webpack_require__(497) + , path = __webpack_require__(4) + , toBatchSyntax = __webpack_require__(498) + , shebangExpr = /^#\!\s*(?:\/usr\/bin\/env)?\s*([^ \t]+=[^ \t]+\s+)*\s*([^ \t]+)(.*)$/ - // finish up the class. - hasMagic = true - inClass = false - re += c - continue +function cmdShimIfExists (from, to, cb) { + fs.stat(from, function (er) { + if (er) return cb() + cmdShim(from, to, cb) + }) +} - default: - // swallow any state char that wasn't consumed - clearStateChar() +// Try to unlink, but ignore errors. +// Any problems will surface later. +function rm (path, cb) { + fs.unlink(path, function(er) { + cb() + }) +} - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\' - } +function cmdShim (from, to, cb) { + fs.stat(from, function (er, stat) { + if (er) + return cb(er) - re += c + cmdShim_(from, to, cb) + }) +} - } // switch - } // for +function cmdShim_ (from, to, cb) { + var then = times(2, next, cb) + rm(to, then) + rm(to + ".cmd", then) - // handle the case where we left a class open. - // "[abc" is valid, equivalent to "\[abc" - if (inClass) { - // split where the last [ was, and escape it - // this is a huge pita. We now have to re-walk - // the contents of the would-be class to re-translate - // any characters that were passed through as-is - cs = pattern.substr(classStart + 1) - sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] - hasMagic = hasMagic || sp[1] + function next(er) { + writeShim(from, to, cb) } +} - // handle the case where we had a +( thing at the *end* - // of the pattern. - // each pattern list stack adds 3 chars, and we need to go through - // and escape any | chars that were passed through as-is for the regexp. - // Go through and escape them, taking care not to double-escape any - // | chars that were already escaped. - for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { - var tail = re.slice(pl.reStart + pl.open.length) - this.debug('setting tail', re, pl) - // maybe some even number of \, then maybe 1 \, followed by a | - tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { - if (!$2) { - // the | isn't already escaped, so escape it. - $2 = '\\' - } - - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return $1 + $1 + $2 + '|' +function writeShim (from, to, cb) { + // make a cmd file and a sh script + // First, check if the bin is a #! of some sort. + // If not, then assume it's something that'll be compiled, or some other + // sort of script, and just call it directly. + mkdir(path.dirname(to), function (er) { + if (er) + return cb(er) + fs.readFile(from, "utf8", function (er, data) { + if (er) return writeShim_(from, to, null, null, cb) + var firstLine = data.trim().split(/\r*\n/)[0] + , shebang = firstLine.match(shebangExpr) + if (!shebang) return writeShim_(from, to, null, null, null, cb) + var vars = shebang[1] || "" + , prog = shebang[2] + , args = shebang[3] || "" + return writeShim_(from, to, prog, args, vars, cb) }) + }) +} - this.debug('tail=%j\n %s', tail, tail, pl, re) - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type - - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail - } - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' +function writeShim_ (from, to, prog, args, variables, cb) { + var shTarget = path.relative(path.dirname(to), from) + , target = shTarget.split("/").join("\\") + , longProg + , shProg = prog && prog.split("\\").join("/") + , shLongProg + , pwshProg = shProg && "\"" + shProg + "$exe\"" + , pwshLongProg + shTarget = shTarget.split("\\").join("/") + args = args || "" + variables = variables || "" + if (!prog) { + prog = "\"%~dp0\\" + target + "\"" + shProg = "\"$basedir/" + shTarget + "\"" + pwshProg = shProg + args = "" + target = "" + shTarget = "" + } else { + longProg = "\"%~dp0\\" + prog + ".exe\"" + shLongProg = "\"$basedir/" + prog + "\"" + pwshLongProg = "\"$basedir/" + prog + "$exe\"" + target = "\"%~dp0\\" + target + "\"" + shTarget = "\"$basedir/" + shTarget + "\"" } - // only need to apply the nodot start if the re starts with - // something that could conceivably capture a dot - var addPatternStart = false - switch (re.charAt(0)) { - case '.': - case '[': - case '(': addPatternStart = true + // @SETLOCAL + // + // @IF EXIST "%~dp0\node.exe" ( + // @SET "_prog=%~dp0\node.exe" + // ) ELSE ( + // @SET "_prog=node" + // @SET PATHEXT=%PATHEXT:;.JS;=;% + // ) + // + // "%_prog%" "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* + // @ENDLOCAL + var cmd + if (longProg) { + shLongProg = shLongProg.trim(); + args = args.trim(); + var variableDeclarationsAsBatch = toBatchSyntax.convertToSetCommands(variables) + cmd = "@SETLOCAL\r\n" + + variableDeclarationsAsBatch + + "\r\n" + + "@IF EXIST " + longProg + " (\r\n" + + " @SET \"_prog=" + longProg.replace(/(^")|("$)/g, '') + "\"\r\n" + + ") ELSE (\r\n" + + " @SET \"_prog=" + prog.replace(/(^")|("$)/g, '') + "\"\r\n" + + " @SET PATHEXT=%PATHEXT:;.JS;=;%\r\n" + + ")\r\n" + + "\r\n" + + "\"%_prog%\" " + args + " " + target + " %*\r\n" + + '@ENDLOCAL\r\n' + } else { + cmd = "@" + prog + " " + args + " " + target + " %*\r\n" } - // Hack to work around lack of negative lookbehind in JS - // A pattern like: *.!(x).!(y|z) needs to ensure that a name - // like 'a.xyz.yz' doesn't match. So, the first negative - // lookahead, has to look ALL the way ahead, to the end of - // the pattern. - for (var n = negativeLists.length - 1; n > -1; n--) { - var nl = negativeLists[n] - - var nlBefore = re.slice(0, nl.reStart) - var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) - var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) - var nlAfter = re.slice(nl.reEnd) - - nlLast += nlAfter - - // Handle nested stuff like *(*.js|!(*.json)), where open parens - // mean that we should *not* include the ) in the bit that is considered - // "after" the negated section. - var openParensBefore = nlBefore.split('(').length - 1 - var cleanAfter = nlAfter - for (i = 0; i < openParensBefore; i++) { - cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') - } - nlAfter = cleanAfter + // #!/bin/sh + // basedir=`dirname "$0"` + // + // case `uname` in + // *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; + // esac + // + // if [ -x "$basedir/node.exe" ]; then + // "$basedir/node.exe" "$basedir/node_modules/npm/bin/npm-cli.js" "$@" + // ret=$? + // else + // node "$basedir/node_modules/npm/bin/npm-cli.js" "$@" + // ret=$? + // fi + // exit $ret - var dollar = '' - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$' - } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast - re = newRe - } + var sh = "#!/bin/sh\n" - // if the re is not "" at this point, then we need to make sure - // it doesn't match against an empty path part. - // Otherwise a/* will match a/, which it should not. - if (re !== '' && hasMagic) { - re = '(?=.)' + re - } + sh = sh + + "basedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\")\n" + + "\n" + + "case `uname` in\n" + + " *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w \"$basedir\"`;;\n" + + "esac\n" + + "\n" - if (addPatternStart) { - re = patternStart + re + if (shLongProg) { + sh = sh + + "if [ -x "+shLongProg+" ]; then\n" + + " " + variables + shLongProg + " " + args + " " + shTarget + " \"$@\"\n" + + " ret=$?\n" + + "else \n" + + " " + variables + shProg + " " + args + " " + shTarget + " \"$@\"\n" + + " ret=$?\n" + + "fi\n" + + "exit $ret\n" + } else { + sh = sh + + shProg + " " + args + " " + shTarget + " \"$@\"\n" + + "exit $?\n" } - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] - } - - // skip the regexp for non-magical patterns - // unescape anything in it, though, so that it'll be - // an exact match against a file etc. - if (!hasMagic) { - return globUnescape(pattern) + // #!/usr/bin/env pwsh + // $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + // + // $ret=0 + // $exe = "" + // if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + // # Fix case when both the Windows and Linux builds of Node + // # are installed in the same directory + // $exe = ".exe" + // } + // if (Test-Path "$basedir/node") { + // & "$basedir/node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args + // $ret=$LASTEXITCODE + // } else { + // & "node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args + // $ret=$LASTEXITCODE + // } + // exit $ret + var pwsh = "#!/usr/bin/env pwsh\n" + + "$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent\n" + + "\n" + + "$exe=\"\"\n" + + "if ($PSVersionTable.PSVersion -lt \"6.0\" -or $IsWindows) {\n" + + " # Fix case when both the Windows and Linux builds of Node\n" + + " # are installed in the same directory\n" + + " $exe=\".exe\"\n" + + "}\n" + if (shLongProg) { + pwsh = pwsh + + "$ret=0\n" + + "if (Test-Path " + pwshLongProg + ") {\n" + + " & " + pwshLongProg + " " + args + " " + shTarget + " $args\n" + + " $ret=$LASTEXITCODE\n" + + "} else {\n" + + " & " + pwshProg + " " + args + " " + shTarget + " $args\n" + + " $ret=$LASTEXITCODE\n" + + "}\n" + + "exit $ret\n" + } else { + pwsh = pwsh + + "& " + pwshProg + " " + args + " " + shTarget + " $args\n" + + "exit $LASTEXITCODE\n" } - var flags = options.nocase ? 'i' : '' - try { - var regExp = new RegExp('^' + re + '$', flags) - } catch (er) { - // If it was an invalid regular expression, then it can't match - // anything. This trick looks for a character after the end of - // the string, which is of course impossible, except in multi-line - // mode, but it's not a /m regex. - return new RegExp('$.') + var then = times(3, next, cb) + fs.writeFile(to + ".ps1", pwsh, "utf8", then) + fs.writeFile(to + ".cmd", cmd, "utf8", then) + fs.writeFile(to, sh, "utf8", then) + function next () { + chmodShim(to, cb) } - - regExp._glob = pattern - regExp._src = re - - return regExp } -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() +function chmodShim (to, cb) { + var then = times(2, cb, cb) + fs.chmod(to, "0755", then) + fs.chmod(to + ".cmd", "0755", then) + fs.chmod(to + ".ps1", "0755", then) } -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp - - // at this point, this.set is a 2d array of partial - // pattern strings, or "**". - // - // It's better to use .match(). This function shouldn't - // be used, really, but it's pretty convenient sometimes, - // when you just want to work with a regex. - var set = this.set - - if (!set.length) { - this.regexp = false - return this.regexp +function times(n, ok, cb) { + var errState = null + return function(er) { + if (!errState) { + if (er) + cb(errState = er) + else if (--n === 0) + ok() + } } - var options = this.options +} - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - var flags = options.nocase ? 'i' : '' - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|') +/***/ }), +/* 493 */ +/***/ (function(module, exports, __webpack_require__) { - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$' +var fs = __webpack_require__(349) +var polyfills = __webpack_require__(494) +var legacy = __webpack_require__(495) +var clone = __webpack_require__(496) - // can match anything, as long as it's not this. - if (this.negate) re = '^(?!' + re + ').*$' +var util = __webpack_require__(397) - try { - this.regexp = new RegExp(re, flags) - } catch (ex) { - this.regexp = false - } - return this.regexp -} +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue +var previousSymbol -minimatch.match = function (list, pattern, options) { - options = options || {} - var mm = new Minimatch(pattern, options) - list = list.filter(function (f) { - return mm.match(f) - }) - if (mm.options.nonull && !list.length) { - list.push(pattern) - } - return list +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue = Symbol.for('graceful-fs.queue') + // This is used in testing by future versions + previousSymbol = Symbol.for('graceful-fs.previous') +} else { + gracefulQueue = '___graceful-fs.queue' + previousSymbol = '___graceful-fs.previous' } -Minimatch.prototype.match = match -function match (f, partial) { - this.debug('match', f, this.pattern) - // short-circuit in the case of busted things. - // comments, etc. - if (this.comment) return false - if (this.empty) return f === '' - - if (f === '/' && partial) return true - - var options = this.options +function noop () {} - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/') +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) } - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, 'split', f) +// Once time initialization +if (!global[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = [] + Object.defineProperty(global, gracefulQueue, { + get: function() { + return queue + } + }) - // just ONE of the pattern sets in this.set needs to match - // in order for it to be valid. If negating, then just one - // match means that we have failed. - // Either way, return on the first hit. + // Patch fs.close/closeSync to shared queue version, because we need + // to retry() whenever a close happens *anywhere* in the program. + // This is essential when multiple graceful-fs instances are + // in play at the same time. + fs.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs, fd, function (err) { + // This function uses the graceful-fs shared queue + if (!err) { + retry() + } - var set = this.set - this.debug(this.pattern, 'set', set) + if (typeof cb === 'function') + cb.apply(this, arguments) + }) + } - // Find the basename of the path by looking for the last non-empty segment - var filename - var i - for (i = f.length - 1; i >= 0; i--) { - filename = f[i] - if (filename) break - } + Object.defineProperty(close, previousSymbol, { + value: fs$close + }) + return close + })(fs.close) - for (i = 0; i < set.length; i++) { - var pattern = set[i] - var file = f - if (options.matchBase && pattern.length === 1) { - file = [filename] - } - var hit = this.matchOne(file, pattern, partial) - if (hit) { - if (options.flipNegate) return true - return !this.negate + fs.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs, arguments) + retry() } - } - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }) + return closeSync + })(fs.closeSync) + + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(global[gracefulQueue]) + __webpack_require__(371).equal(global[gracefulQueue].length, 0) + }) + } } -// set partial to true to test if, for example, -// "/a/b" matches the start of "/*/b/*/d" -// Partial means, if you run out of file before you run -// out of pattern, then that's fine, as long as all -// the parts match. -Minimatch.prototype.matchOne = function (file, pattern, partial) { - var options = this.options +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; +} - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch - this.debug('matchOne', file.length, pattern.length) + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null - for (var fi = 0, - pi = 0, - fl = file.length, - pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi++, pi++) { - this.debug('matchOne loop') - var p = pattern[pi] - var f = file[fi] + return go$readFile(path, options, cb) - this.debug(pattern, p, f) + function go$readFile (path, options, cb) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } + } - // should be impossible. - // some invalid regexp stuff in the set. - if (p === false) return false + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null - if (p === GLOBSTAR) { - this.debug('GLOBSTAR', [pattern, p, f]) + return go$writeFile(path, data, options, cb) - // "**" - // a/**/b/**/c would match the following: - // a/b/x/y/z/c - // a/x/y/z/b/c - // a/b/x/b/x/c - // a/b/c - // To do this, take the rest of the pattern after - // the **, and see if it would match the file remainder. - // If so, return success. - // If not, the ** "swallows" a segment, and try again. - // This is recursively awful. - // - // a/**/b/**/c matching a/b/x/y/z/c - // - a matches a - // - doublestar - // - matchOne(b/x/y/z/c, b/**/c) - // - b matches b - // - doublestar - // - matchOne(x/y/z/c, c) -> no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi - var pr = pi + 1 - if (pr === pl) { - this.debug('** at the end') - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for (; fi < fl; fi++) { - if (file[fi] === '.' || file[fi] === '..' || - (!options.dot && file[fi].charAt(0) === '.')) return false + function go$writeFile (path, data, options, cb) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() } - return true - } - - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] + }) + } + } - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug('globstar found match!', fr, fl, swallowee) - // found a match. - return true - } else { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee === '.' || swallowee === '..' || - (!options.dot && swallowee.charAt(0) === '.')) { - this.debug('dot detected!', file, fr, pattern, pr) - break - } + return go$appendFile(path, data, options, cb) - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ + function go$appendFile (path, data, options, cb) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() } - } - - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - if (partial) { - // ran out of file - this.debug('\n>>> no match, partial?', file, fr, pattern, pr) - if (fr === fl) return true - } - return false + }) } + } - // something other than ** - // non-magic patterns just have to match exactly - // patterns with magic have been turned into regexps. - var hit - if (typeof p === 'string') { - if (options.nocase) { - hit = f.toLowerCase() === p.toLowerCase() - } else { - hit = f === p - } - this.debug('string match', p, f, hit) + var fs$readdir = fs.readdir + fs.readdir = readdir + function readdir (path, options, cb) { + var args = [path] + if (typeof options !== 'function') { + args.push(options) } else { - hit = f.match(p) - this.debug('pattern match', p, f, hit) + cb = options } + args.push(go$readdir$cb) - if (!hit) return false - } - - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* - - // now either we fell off the end of the pattern, or we're done. - if (fi === fl && pi === pl) { - // ran out of pattern and filename at the same time. - // an exact hit! - return true - } else if (fi === fl) { - // ran out of file, but still had pattern left. - // this is ok if we're doing the match as part of - // a glob fs traversal. - return partial - } else if (pi === pl) { - // ran out of pattern, still have file left. - // this is only acceptable if we're on the very last - // empty segment of a file with a trailing slash. - // a/* should match a/b/ - var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') - return emptyFileEnd - } + return go$readdir(args) - // should be unreachable. - throw new Error('wtf?') -} + function go$readdir$cb (err, files) { + if (files && files.sort) + files.sort() -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, '$1') -} + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readdir, [args]]) -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') -} + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + } + } + function go$readdir (args) { + return fs$readdir.apply(fs, args) + } -/***/ }), -/* 507 */ -/***/ (function(module, exports, __webpack_require__) { + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream + } -var concatMap = __webpack_require__(508); -var balanced = __webpack_require__(509); + var fs$ReadStream = fs.ReadStream + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open + } -module.exports = expandTop; + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; - -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} - -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); -} - -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); -} - - -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; - - var parts = []; - var m = balanced('{', '}', str); - - if (!m) - return str.split(','); + Object.defineProperty(fs, 'ReadStream', { + get: function () { + return ReadStream + }, + set: function (val) { + ReadStream = val + }, + enumerable: true, + configurable: true + }) + Object.defineProperty(fs, 'WriteStream', { + get: function () { + return WriteStream + }, + set: function (val) { + WriteStream = val + }, + enumerable: true, + configurable: true + }) - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); + // legacy names + var FileReadStream = ReadStream + Object.defineProperty(fs, 'FileReadStream', { + get: function () { + return FileReadStream + }, + set: function (val) { + FileReadStream = val + }, + enumerable: true, + configurable: true + }) + var FileWriteStream = WriteStream + Object.defineProperty(fs, 'FileWriteStream', { + get: function () { + return FileWriteStream + }, + set: function (val) { + FileWriteStream = val + }, + enumerable: true, + configurable: true + }) - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) } - parts.push.apply(parts, p); - - return parts; -} - -function expandTop(str) { - if (!str) - return []; + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + that.read() + } + }) } - return expand(escapeBraces(str), true).map(unescapeBraces); -} - -function identity(e) { - return e; -} - -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); -} - -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} - -function expand(str, isTop) { - var expansions = []; - - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; - - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); - } - return [str]; + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) } - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; - }); + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) } - } + }) } - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. - - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; + function createReadStream (path, options) { + return new fs.ReadStream(path, options) + } - var N; + function createWriteStream (path, options) { + return new fs.WriteStream(path, options) + } - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null - N = []; + return go$open(path, flags, mode, cb) - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } + function go$open (path, flags, mode, cb) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() } - } - N.push(c); - } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); - } - - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); + }) } } - return expansions; + return fs } +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + global[gracefulQueue].push(elem) +} - -/***/ }), -/* 508 */ -/***/ (function(module, exports) { - -module.exports = function (xs, fn) { - var res = []; - for (var i = 0; i < xs.length; i++) { - var x = fn(xs[i], i); - if (isArray(x)) res.push.apply(res, x); - else res.push(x); - } - return res; -}; - -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; +function retry () { + var elem = global[gracefulQueue].shift() + if (elem) { + debug('RETRY', elem[0].name, elem[1]) + elem[0].apply(null, elem[1]) + } +} /***/ }), -/* 509 */ +/* 494 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +var constants = __webpack_require__(411) -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); +var origCwd = process.cwd +var cwd = null - var r = range(a, b, str); +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd } +try { + process.cwd() +} catch (er) {} -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; +var chdir = process.chdir +process.chdir = function(d) { + cwd = null + chdir.call(process, d) } -balanced.range = range; -function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; - - if (ai >= 0 && bi > 0) { - begs = []; - left = str.length; - - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; - } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; - } +module.exports = patch - bi = str.indexOf(b, i + 1); - } +function patch (fs) { + // (re-)implement some things that are known busted or missing. - i = ai < bi && ai >= 0 ? ai : bi; - } + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) + } - if (begs.length) { - result = [ left, right ]; - } + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) } - return result; -} + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) -/***/ }), -/* 510 */ -/***/ (function(module, exports, __webpack_require__) { + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) -try { - var util = __webpack_require__(29); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - /* istanbul ignore next */ - module.exports = __webpack_require__(511); -} + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) -/***/ }), -/* 511 */ -/***/ (function(module, exports) { + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) + + // if lchmod/lchown do not exist, then make them no-ops + if (!fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor + fs.lchmodSync = function () {} + } + if (!fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) } + fs.lchownSync = function () {} } -} - - -/***/ }), -/* 512 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = (function (fs$rename) { return function (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + }})(fs.rename) + } -function posix(path) { - return path.charAt(0) === '/'; -} + // if read() returns EAGAIN, then just try it again. + fs.read = (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } -function win32(path) { - // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 - var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; - var result = splitDeviceRe.exec(path); - var device = result[1] || ''; - var isUnc = Boolean(device && device.charAt(1) !== ':'); - - // UNC paths are always absolute - return Boolean(result[2] || isUnc); -} - -module.exports = process.platform === 'win32' ? win32 : posix; -module.exports.posix = posix; -module.exports.win32 = win32; + // This ensures `util.promisify` works as it does for native `fs.read`. + read.__proto__ = fs$read + return read + })(fs.read) + fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } + }})(fs.readSync) -/***/ }), -/* 513 */ -/***/ (function(module, exports, __webpack_require__) { + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } -module.exports = globSync -globSync.GlobSync = GlobSync + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) -var fs = __webpack_require__(23) -var rp = __webpack_require__(504) -var minimatch = __webpack_require__(506) -var Minimatch = minimatch.Minimatch -var Glob = __webpack_require__(503).Glob -var util = __webpack_require__(29) -var path = __webpack_require__(16) -var assert = __webpack_require__(30) -var isAbsolute = __webpack_require__(512) -var common = __webpack_require__(514) -var alphasort = common.alphasort -var alphasorti = common.alphasorti -var setopts = common.setopts -var ownProp = common.ownProp -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + } -function globSync (pattern, options) { - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK")) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } - return new GlobSync(pattern, options).found -} + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } -function GlobSync (pattern, options) { - if (!pattern) - throw new Error('must provide pattern') + } else { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} + } + } - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } - if (!(this instanceof GlobSync)) - return new GlobSync(pattern, options) + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } - setopts(this, pattern, options) - if (this.noprocess) - return this + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } - var n = this.minimatch.set.length - this.matches = new Array(n) - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false) + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } } - this._finish() -} -GlobSync.prototype._finish = function () { - assert(this instanceof GlobSync) - if (this.realpath) { - var self = this - this.matches.forEach(function (matchset, index) { - var set = self.matches[index] = Object.create(null) - for (var p in matchset) { - try { - p = self._makeAbs(p) - var real = rp.realpathSync(p, self.realpathCache) - set[real] = true - } catch (er) { - if (er.syscall === 'stat') - set[self._makeAbs(p)] = true - else - throw er + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 } + if (cb) cb.apply(this, arguments) } - }) + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) + } } - common.finish(this) -} - - -GlobSync.prototype._process = function (pattern, index, inGlobStar) { - assert(this instanceof GlobSync) - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + return stats; + } } - // now n is the index of the first one that is *not* a string. - // See if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index) - return + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break + if (er.code === "ENOSYS") + return true - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } + + return false } +} - var remain = pattern.slice(n) - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix +/***/ }), +/* 495 */ +/***/ (function(module, exports, __webpack_require__) { - var abs = this._makeAbs(read) +var Stream = __webpack_require__(382).Stream - //if ignored, skip processing - if (childrenIgnored(this, read)) - return +module.exports = legacy - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar) -} +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream + } + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); -GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { - var entries = this._readdir(abs, inGlobStar) + Stream.call(this); - // if the abs isn't a dir, then nothing can match! - if (!entries) - return + var self = this; - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) - } - if (m) - matchedEntries.push(e) - } - } + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return + options = options || {}; - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) + if (this.encoding) this.setEncoding(this.encoding); - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix.slice(-1) !== '/') - e = prefix + '/' + e - else - e = prefix + e + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); } - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) + if (this.start > this.end) { + throw new Error('start must be <= end'); } - this._emitMatch(index, e) + + this.pos = this.start; } - // This was the last one, and no stats were needed - return - } - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) - newPattern = [prefix, e] - else - newPattern = [e] - this._process(newPattern.concat(remain), index, inGlobStar) - } -} + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } -GlobSync.prototype._emitMatch = function (index, e) { - if (isIgnored(this, e)) - return + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } - var abs = this._makeAbs(e) + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); - if (this.mark) - e = this._mark(e) + Stream.call(this); - if (this.absolute) { - e = abs - } + this.path = path; + this.fd = null; + this.writable = true; - if (this.matches[index][e]) - return + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return - } + options = options || {}; - this.matches[index][e] = true + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } - if (this.stat) - this._stat(e) -} + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.start < 0) { + throw new Error('start must be >= zero'); + } + this.pos = this.start; + } -GlobSync.prototype._readdirInGlobStar = function (abs) { - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false) + this.busy = false; + this._queue = []; - var entries - var lstat - var stat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - if (er.code === 'ENOENT') { - // lstat failed, doesn't exist - return null + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); } } +} - var isSym = lstat && lstat.isSymbolicLink() - this.symlinks[abs] = isSym - - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) - this.cache[abs] = 'FILE' - else - entries = this._readdir(abs, false) - return entries -} +/***/ }), +/* 496 */ +/***/ (function(module, exports, __webpack_require__) { -GlobSync.prototype._readdir = function (abs, inGlobStar) { - var entries +"use strict"; - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs) - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return null +module.exports = clone - if (Array.isArray(c)) - return c - } +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj - try { - return this._readdirEntries(abs, fs.readdirSync(abs)) - } catch (er) { - this._readdirError(abs, er) - return null - } -} - -GlobSync.prototype._readdirEntries = function (abs, entries) { - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } - } + if (obj instanceof Object) + var copy = { __proto__: obj.__proto__ } + else + var copy = Object.create(null) - this.cache[abs] = entries + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) - // mark and cache dir-ness - return entries + return copy } -GlobSync.prototype._readdirError = function (f, er) { - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f) - this.cache[abs] = 'FILE' - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd) - error.path = this.cwd - error.code = er.code - throw error - } - break - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break +/***/ }), +/* 497 */ +/***/ (function(module, exports, __webpack_require__) { - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) - throw er - if (!this.silent) - console.error('glob error', er) - break - } -} +var path = __webpack_require__(4); +var fs = __webpack_require__(349); +var _0777 = parseInt('0777', 8); -GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - var entries = this._readdir(abs, inGlobStar) +function mkdirP (p, opts, f, made) { + if (typeof opts === 'function') { + f = opts; + opts = {}; + } + else if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 & (~process.umask()); + } + if (!made) made = null; + + var cb = f || function () {}; + p = path.resolve(p); + + xfs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + if (path.dirname(p) === p) return cb(er); + mkdirP(path.dirname(p), opts, function (er, made) { + if (er) cb(er, made); + else mkdirP(p, opts, cb, made); + }); + break; - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); +} - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) +mkdirP.sync = function sync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 & (~process.umask()); + } + if (!made) made = null; - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false) + p = path.resolve(p); - var len = entries.length - var isSym = this.symlinks[abs] + try { + xfs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } + catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue + return made; +}; - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true) - var below = gspref.concat(entries[i], remain) - this._process(below, index, true) - } -} +/***/ }), +/* 498 */ +/***/ (function(module, exports) { -GlobSync.prototype._processSimple = function (prefix, index) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var exists = this._stat(prefix) +exports.replaceDollarWithPercentPair = replaceDollarWithPercentPair +exports.convertToSetCommand = convertToSetCommand +exports.convertToSetCommands = convertToSetCommands + +function convertToSetCommand(key, value) { + var line = "" + key = key || "" + key = key.trim() + value = value || "" + value = value.trim() + if(key && value && value.length > 0) { + line = "@SET " + key + "=" + replaceDollarWithPercentPair(value) + "\r\n" + } + return line +} + +function extractVariableValuePairs(declarations) { + var pairs = {} + declarations.map(function(declaration) { + var split = declaration.split("=") + pairs[split[0]]=split[1] + }) + return pairs +} + +function convertToSetCommands(variableString) { + var variableValuePairs = extractVariableValuePairs(variableString.split(" ")) + var variableDeclarationsAsBatch = "" + Object.keys(variableValuePairs).forEach(function (key) { + variableDeclarationsAsBatch += convertToSetCommand(key, variableValuePairs[key]) + }) + return variableDeclarationsAsBatch +} + +function replaceDollarWithPercentPair(value) { + var dollarExpressions = /\$\{?([^\$@#\?\- \t{}:]+)\}?/g + var result = "" + var startIndex = 0 + value = value || "" + do { + var match = dollarExpressions.exec(value) + if(match) { + var betweenMatches = value.substring(startIndex, match.index) || "" + result += betweenMatches + "%" + match[1] + "%" + startIndex = dollarExpressions.lastIndex + } + } while (dollarExpressions.lastIndex > 0) + result += value.substr(startIndex) + return result +} + + - if (!this.matches[index]) - this.matches[index] = Object.create(null) - // If it doesn't exist, then just mark the lack of results - if (!exists) - return +/***/ }), +/* 499 */ +/***/ (function(module, exports, __webpack_require__) { - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' - } - } +var fs = __webpack_require__(349), + path = __webpack_require__(4); - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') +module.exports = ncp; +ncp.ncp = ncp; - // Mark this as a match - this._emitMatch(index, prefix) -} +function ncp (source, dest, options, callback) { + var cback = callback; -// Returns either 'DIR', 'FILE', or false -GlobSync.prototype._stat = function (f) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' + if (!callback) { + cback = options; + options = {}; + } - if (f.length > this.maxLength) - return false + var basePath = process.cwd(), + currentPath = path.resolve(basePath, source), + targetPath = path.resolve(basePath, dest), + filter = options.filter, + rename = options.rename, + transform = options.transform, + clobber = options.clobber !== false, + modified = options.modified, + dereference = options.dereference, + errs = null, + started = 0, + finished = 0, + running = 0, + limit = options.limit || ncp.limit || 16; - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] + limit = (limit < 1) ? 1 : (limit > 512) ? 512 : limit; - if (Array.isArray(c)) - c = 'DIR' + startCopy(currentPath); + + function startCopy(source) { + started++; + if (filter) { + if (filter instanceof RegExp) { + if (!filter.test(source)) { + return cb(true); + } + } + else if (typeof filter === 'function') { + if (!filter(source)) { + return cb(true); + } + } + } + return getStats(source); + } - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return c + function getStats(source) { + var stat = dereference ? fs.stat : fs.lstat; + if (running >= limit) { + return setImmediate(function () { + getStats(source); + }); + } + running++; + stat(source, function (err, stats) { + var item = {}; + if (err) { + return onError(err); + } - if (needDir && c === 'FILE') - return false + // We need to get the mode from the stats object and preserve it. + item.name = source; + item.mode = stats.mode; + item.mtime = stats.mtime; //modified time + item.atime = stats.atime; //access time - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. + if (stats.isDirectory()) { + return onDir(item); + } + else if (stats.isFile()) { + return onFile(item); + } + else if (stats.isSymbolicLink()) { + // Symlinks don't really need to know about the mode. + return onLink(source); + } + }); } - var exists - var stat = this.statCache[abs] - if (!stat) { - var lstat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return false - } + function onFile(file) { + var target = file.name.replace(currentPath, targetPath); + if(rename) { + target = rename(target); } - - if (lstat && lstat.isSymbolicLink()) { - try { - stat = fs.statSync(abs) - } catch (er) { - stat = lstat + isWritable(target, function (writable) { + if (writable) { + return copyFile(file, target); + } + if(clobber) { + rmFile(target, function () { + copyFile(file, target); + }); + } + if (modified) { + var stat = dereference ? fs.stat : fs.lstat; + stat(target, function(err, stats) { + //if souce modified time greater to target modified time copy file + if (file.mtime.getTime()>stats.mtime.getTime()) + copyFile(file, target); + else return cb(); + }); + } + else { + return cb(); } + }); + } + + function copyFile(file, target) { + var readStream = fs.createReadStream(file.name), + writeStream = fs.createWriteStream(target, { mode: file.mode }); + + readStream.on('error', onError); + writeStream.on('error', onError); + + if(transform) { + transform(readStream, writeStream, file); } else { - stat = lstat + writeStream.on('open', function() { + readStream.pipe(writeStream); + }); } + writeStream.once('finish', function() { + if (modified) { + //target file modified date sync. + fs.utimesSync(target, file.atime, file.mtime); + cb(); + } + else cb(); + }); } - this.statCache[abs] = stat - - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' + function rmFile(file, done) { + fs.unlink(file, function (err) { + if (err) { + return onError(err); + } + return done(); + }); + } - this.cache[abs] = this.cache[abs] || c + function onDir(dir) { + var target = dir.name.replace(currentPath, targetPath); + isWritable(target, function (writable) { + if (writable) { + return mkDir(dir, target); + } + copyDir(dir.name); + }); + } - if (needDir && c === 'FILE') - return false + function mkDir(dir, target) { + fs.mkdir(target, dir.mode, function (err) { + if (err) { + return onError(err); + } + copyDir(dir.name); + }); + } - return c -} + function copyDir(dir) { + fs.readdir(dir, function (err, items) { + if (err) { + return onError(err); + } + items.forEach(function (item) { + startCopy(path.join(dir, item)); + }); + return cb(); + }); + } -GlobSync.prototype._mark = function (p) { - return common.mark(this, p) -} + function onLink(link) { + var target = link.replace(currentPath, targetPath); + fs.readlink(link, function (err, resolvedPath) { + if (err) { + return onError(err); + } + checkLink(resolvedPath, target); + }); + } -GlobSync.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} + function checkLink(resolvedPath, target) { + if (dereference) { + resolvedPath = path.resolve(basePath, resolvedPath); + } + isWritable(target, function (writable) { + if (writable) { + return makeLink(resolvedPath, target); + } + fs.readlink(target, function (err, targetDest) { + if (err) { + return onError(err); + } + if (dereference) { + targetDest = path.resolve(basePath, targetDest); + } + if (targetDest === resolvedPath) { + return cb(); + } + return rmFile(target, function () { + makeLink(resolvedPath, target); + }); + }); + }); + } + function makeLink(linkPath, target) { + fs.symlink(linkPath, target, function (err) { + if (err) { + return onError(err); + } + return cb(); + }); + } -/***/ }), -/* 514 */ -/***/ (function(module, exports, __webpack_require__) { - -exports.alphasort = alphasort -exports.alphasorti = alphasorti -exports.setopts = setopts -exports.ownProp = ownProp -exports.makeAbs = makeAbs -exports.finish = finish -exports.mark = mark -exports.isIgnored = isIgnored -exports.childrenIgnored = childrenIgnored - -function ownProp (obj, field) { - return Object.prototype.hasOwnProperty.call(obj, field) -} - -var path = __webpack_require__(16) -var minimatch = __webpack_require__(506) -var isAbsolute = __webpack_require__(512) -var Minimatch = minimatch.Minimatch - -function alphasorti (a, b) { - return a.toLowerCase().localeCompare(b.toLowerCase()) -} - -function alphasort (a, b) { - return a.localeCompare(b) -} - -function setupIgnores (self, options) { - self.ignore = options.ignore || [] - - if (!Array.isArray(self.ignore)) - self.ignore = [self.ignore] - - if (self.ignore.length) { - self.ignore = self.ignore.map(ignoreMap) - } -} - -// ignore patterns are always in dot:true mode. -function ignoreMap (pattern) { - var gmatcher = null - if (pattern.slice(-3) === '/**') { - var gpattern = pattern.replace(/(\/\*\*)+$/, '') - gmatcher = new Minimatch(gpattern, { dot: true }) - } - - return { - matcher: new Minimatch(pattern, { dot: true }), - gmatcher: gmatcher + function isWritable(path, done) { + fs.lstat(path, function (err) { + if (err) { + if (err.code === 'ENOENT') return done(true); + return done(false); + } + return done(false); + }); } -} - -function setopts (self, pattern, options) { - if (!options) - options = {} - // base-matching: just use globstar for that. - if (options.matchBase && -1 === pattern.indexOf("/")) { - if (options.noglobstar) { - throw new Error("base matching requires globstar") + function onError(err) { + if (options.stopOnError) { + return cback(err); } - pattern = "**/" + pattern - } - - self.silent = !!options.silent - self.pattern = pattern - self.strict = options.strict !== false - self.realpath = !!options.realpath - self.realpathCache = options.realpathCache || Object.create(null) - self.follow = !!options.follow - self.dot = !!options.dot - self.mark = !!options.mark - self.nodir = !!options.nodir - if (self.nodir) - self.mark = true - self.sync = !!options.sync - self.nounique = !!options.nounique - self.nonull = !!options.nonull - self.nosort = !!options.nosort - self.nocase = !!options.nocase - self.stat = !!options.stat - self.noprocess = !!options.noprocess - self.absolute = !!options.absolute - - self.maxLength = options.maxLength || Infinity - self.cache = options.cache || Object.create(null) - self.statCache = options.statCache || Object.create(null) - self.symlinks = options.symlinks || Object.create(null) - - setupIgnores(self, options) - - self.changedCwd = false - var cwd = process.cwd() - if (!ownProp(options, "cwd")) - self.cwd = cwd - else { - self.cwd = path.resolve(options.cwd) - self.changedCwd = self.cwd !== cwd - } - - self.root = options.root || path.resolve(self.cwd, "/") - self.root = path.resolve(self.root) - if (process.platform === "win32") - self.root = self.root.replace(/\\/g, "/") - - // TODO: is an absolute `cwd` supposed to be resolved against `root`? - // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') - self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) - if (process.platform === "win32") - self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") - self.nomount = !!options.nomount - - // disable comments and negation in Minimatch. - // Note that they are not supported in Glob itself anyway. - options.nonegate = true - options.nocomment = true - - self.minimatch = new Minimatch(pattern, options) - self.options = self.minimatch.options -} - -function finish (self) { - var nou = self.nounique - var all = nou ? [] : Object.create(null) - - for (var i = 0, l = self.matches.length; i < l; i ++) { - var matches = self.matches[i] - if (!matches || Object.keys(matches).length === 0) { - if (self.nonull) { - // do like the shell, and spit out the literal glob - var literal = self.minimatch.globSet[i] - if (nou) - all.push(literal) - else - all[literal] = true - } - } else { - // had matches - var m = Object.keys(matches) - if (nou) - all.push.apply(all, m) - else - m.forEach(function (m) { - all[m] = true - }) + else if (!errs && options.errs) { + errs = fs.createWriteStream(options.errs); } - } - - if (!nou) - all = Object.keys(all) - - if (!self.nosort) - all = all.sort(self.nocase ? alphasorti : alphasort) - - // at *some* point we statted all of these - if (self.mark) { - for (var i = 0; i < all.length; i++) { - all[i] = self._mark(all[i]) + else if (!errs) { + errs = []; } - if (self.nodir) { - all = all.filter(function (e) { - var notDir = !(/\/$/.test(e)) - var c = self.cache[e] || self.cache[makeAbs(self, e)] - if (notDir && c) - notDir = c !== 'DIR' && !Array.isArray(c) - return notDir - }) + if (typeof errs.write === 'undefined') { + errs.push(err); } + else { + errs.write(err.stack + '\n\n'); + } + return cb(); } - if (self.ignore.length) - all = all.filter(function(m) { - return !isIgnored(self, m) - }) - - self.found = all -} - -function mark (self, p) { - var abs = makeAbs(self, p) - var c = self.cache[abs] - var m = p - if (c) { - var isDir = c === 'DIR' || Array.isArray(c) - var slash = p.slice(-1) === '/' - - if (isDir && !slash) - m += '/' - else if (!isDir && slash) - m = m.slice(0, -1) - - if (m !== p) { - var mabs = makeAbs(self, m) - self.statCache[mabs] = self.statCache[abs] - self.cache[mabs] = self.cache[abs] + function cb(skipped) { + if (!skipped) running--; + finished++; + if ((started === finished) && (running === 0)) { + if (cback !== undefined ) { + return errs ? cback(errs) : cback(null); + } } } - - return m } -// lotta situps... -function makeAbs (self, f) { - var abs = f - if (f.charAt(0) === '/') { - abs = path.join(self.root, f) - } else if (isAbsolute(f) || f === '') { - abs = f - } else if (self.changedCwd) { - abs = path.resolve(self.cwd, f) - } else { - abs = path.resolve(f) - } - - if (process.platform === 'win32') - abs = abs.replace(/\\/g, '/') - return abs -} -// Return true, if pattern ends with globstar '**', for the accompanying parent directory. -// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents -function isIgnored (self, path) { - if (!self.ignore.length) - return false +/***/ }), +/* 500 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - return self.ignore.some(function(item) { - return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) - }) -} +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "log", function() { return log; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Log", function() { return Log; }); +/* harmony import */ var _kbn_dev_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); +/* harmony import */ var _kbn_dev_utils__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_kbn_dev_utils__WEBPACK_IMPORTED_MODULE_0__); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LogLevel", function() { return _kbn_dev_utils__WEBPACK_IMPORTED_MODULE_0__["LogLevel"]; }); -function childrenIgnored (self, path) { - if (!self.ignore.length) - return false +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; } - return self.ignore.some(function(item) { - return !!(item.gmatcher && item.gmatcher.match(path)) - }) -} +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ -/***/ }), -/* 515 */ -/***/ (function(module, exports, __webpack_require__) { +class Log extends _kbn_dev_utils__WEBPACK_IMPORTED_MODULE_0__["ToolingLog"] { + constructor() { + super(); -var wrappy = __webpack_require__(405) -var reqs = Object.create(null) -var once = __webpack_require__(404) + _defineProperty(this, "logLevel", void 0); -module.exports = wrappy(inflight) + this.setLogLevel('info'); + } -function inflight (key, cb) { - if (reqs[key]) { - reqs[key].push(cb) - return null - } else { - reqs[key] = [cb] - return makeres(key) + setLogLevel(level) { + this.logLevel = Object(_kbn_dev_utils__WEBPACK_IMPORTED_MODULE_0__["parseLogLevel"])(level); + this.setWriters([new _kbn_dev_utils__WEBPACK_IMPORTED_MODULE_0__["ToolingLogTextWriter"]({ + level: this.logLevel.name, + writeTo: process.stdout + })]); } -} -function makeres (key) { - return once(function RES () { - var cbs = reqs[key] - var len = cbs.length - var args = slice(arguments) + wouldLogLevel(level) { + return this.logLevel.flags[level]; + } - // XXX It's somewhat ambiguous whether a new callback added in this - // pass should be queued for later execution if something in the - // list of callbacks throws, or if it should just be discarded. - // However, it's such an edge case that it hardly matters, and either - // choice is likely as surprising as the other. - // As it happens, we do go ahead and schedule it for later execution. - try { - for (var i = 0; i < len; i++) { - cbs[i].apply(null, args) - } - } finally { - if (cbs.length > len) { - // added more in the interim. - // de-zalgo, just in case, but don't call again. - cbs.splice(0, len) - process.nextTick(function () { - RES.apply(null, args) - }) - } else { - delete reqs[key] - } - } - }) } -function slice (args) { - var length = args.length - var array = [] - - for (var i = 0; i < length; i++) array[i] = args[i] - return array -} +const log = new Log(); /***/ }), -/* 516 */ +/* 501 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CliError", function() { return CliError; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parallelizeBatches", function() { return parallelizeBatches; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parallelize", function() { return parallelize; }); /* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with @@ -47570,39 +44042,65 @@ __webpack_require__.r(__webpack_exports__); * specific language governing permissions and limitations * under the License. */ -class CliError extends Error { - constructor(message, meta = {}) { - super(message); - this.meta = meta; +async function parallelizeBatches(batches, fn) { + for (const batch of batches) { + // We need to make sure the entire batch has completed before we can move on + // to the next batch + await parallelize(batch, fn); + } +} +async function parallelize(items, fn, concurrency = 4) { + if (items.length === 0) { + return; } + return new Promise((resolve, reject) => { + let activePromises = 0; + const values = items.slice(0); + + async function scheduleItem(item) { + activePromises++; + + try { + await fn(item); + activePromises--; + + if (values.length > 0) { + // We have more work to do, so we schedule the next promise + scheduleItem(values.shift()); + } else if (activePromises === 0) { + // We have no more values left, and all items have completed, so we've + // completed all the work. + resolve(); + } + } catch (error) { + reject(error); + } + } + + values.splice(0, concurrency).map(scheduleItem); + }); } /***/ }), -/* 517 */ +/* 502 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Project", function() { return Project; }); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(chalk__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(23); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(16); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(29); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(516); -/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(34); -/* harmony import */ var _package_json__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(518); -/* harmony import */ var _scripts__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(563); -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { 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; } - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getProjects", function() { return getProjects; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buildProjectGraph", function() { return buildProjectGraph; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "topologicallyBatchProjects", function() { return topologicallyBatchProjects; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "includeTransitiveProjects", function() { return includeTransitiveProjects; }); +/* harmony import */ var glob__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(503); +/* harmony import */ var glob__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(glob__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 util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(397); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(516); +/* harmony import */ var _project__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(517); +/* harmony import */ var _workspaces__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(573); /* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with @@ -47627,6243 +44125,8760 @@ function _defineProperty(obj, key, value) { if (key in obj) { Object.definePrope +const glob = Object(util__WEBPACK_IMPORTED_MODULE_2__["promisify"])(glob__WEBPACK_IMPORTED_MODULE_0___default.a); +/** a Map of project names to Project instances */ +async function getProjects(rootPath, projectsPathsPatterns, { + include = [], + exclude = [] +} = {}) { + const projects = new Map(); + const workspaceProjectsPaths = await Object(_workspaces__WEBPACK_IMPORTED_MODULE_5__["workspacePackagePaths"])(rootPath); -class Project { - static async fromPath(path) { - const pkgJson = await Object(_package_json__WEBPACK_IMPORTED_MODULE_6__["readPackageJson"])(path); - return new Project(pkgJson, path); - } - /** parsed package.json */ + for (const pattern of projectsPathsPatterns) { + const pathsToProcess = await packagesFromGlobPattern({ + pattern, + rootPath + }); + for (const filePath of pathsToProcess) { + const projectConfigPath = normalize(filePath); + const projectDir = path__WEBPACK_IMPORTED_MODULE_1___default.a.dirname(projectConfigPath); + const project = await _project__WEBPACK_IMPORTED_MODULE_4__["Project"].fromPath(projectDir); - constructor(packageJson, projectPath) { - _defineProperty(this, "json", void 0); + if (workspaceProjectsPaths.indexOf(filePath) >= 0) { + project.isWorkspaceProject = true; + } - _defineProperty(this, "packageJsonLocation", void 0); + const excludeProject = exclude.includes(project.name) || include.length > 0 && !include.includes(project.name); - _defineProperty(this, "nodeModulesLocation", void 0); + if (excludeProject) { + continue; + } - _defineProperty(this, "targetLocation", void 0); + if (projects.has(project.name)) { + throw new _errors__WEBPACK_IMPORTED_MODULE_3__["CliError"](`There are multiple projects with the same name [${project.name}]`, { + name: project.name, + paths: [project.path, projects.get(project.name).path] + }); + } - _defineProperty(this, "path", void 0); + projects.set(project.name, project); + } + } - _defineProperty(this, "version", void 0); + return projects; +} - _defineProperty(this, "allDependencies", void 0); +function packagesFromGlobPattern({ + pattern, + rootPath +}) { + const globOptions = { + cwd: rootPath, + // Should throw in case of unusual errors when reading the file system + strict: true, + // Always returns absolute paths for matched files + absolute: true, + // Do not match ** against multiple filenames + // (This is only specified because we currently don't have a need for it.) + noglobstar: true + }; + return glob(path__WEBPACK_IMPORTED_MODULE_1___default.a.join(pattern, 'package.json'), globOptions); +} // https://github.com/isaacs/node-glob/blob/master/common.js#L104 +// glob always returns "\\" as "/" in windows, so everyone +// gets normalized because we can't have nice things. - _defineProperty(this, "productionDependencies", void 0); - _defineProperty(this, "devDependencies", void 0); +function normalize(dir) { + return path__WEBPACK_IMPORTED_MODULE_1___default.a.normalize(dir); +} - _defineProperty(this, "scripts", void 0); +function buildProjectGraph(projects) { + const projectGraph = new Map(); - _defineProperty(this, "isWorkspaceRoot", false); + for (const project of projects.values()) { + const projectDeps = []; + const dependencies = project.allDependencies; - _defineProperty(this, "isWorkspaceProject", false); + for (const depName of Object.keys(dependencies)) { + if (projects.has(depName)) { + const dep = projects.get(depName); + const dependentProjectIsInWorkspace = project.isWorkspaceProject || project.json.name === 'kibana'; + project.ensureValidProjectDependency(dep, dependentProjectIsInWorkspace); + projectDeps.push(dep); + } + } - this.json = Object.freeze(packageJson); - this.path = projectPath; - this.packageJsonLocation = path__WEBPACK_IMPORTED_MODULE_2___default.a.resolve(this.path, 'package.json'); - this.nodeModulesLocation = path__WEBPACK_IMPORTED_MODULE_2___default.a.resolve(this.path, 'node_modules'); - this.targetLocation = path__WEBPACK_IMPORTED_MODULE_2___default.a.resolve(this.path, 'target'); - this.version = this.json.version; - this.productionDependencies = this.json.dependencies || {}; - this.devDependencies = this.json.devDependencies || {}; - this.allDependencies = _objectSpread({}, this.devDependencies, {}, this.productionDependencies); - this.isWorkspaceRoot = this.json.hasOwnProperty('workspaces'); - this.scripts = this.json.scripts || {}; + projectGraph.set(project.name, projectDeps); } - get name() { - return this.json.name; - } + return projectGraph; +} +function topologicallyBatchProjects(projectsToBatch, projectGraph, { + batchByWorkspace = false +} = {}) { + // We're going to be chopping stuff out of this list, so copy it. + const projectsLeftToBatch = new Set(projectsToBatch.keys()); + const batches = []; - ensureValidProjectDependency(project, dependentProjectIsInWorkspace) { - const versionInPackageJson = this.allDependencies[project.name]; - let expectedVersionInPackageJson; + if (batchByWorkspace) { + const workspaceRootProject = Array.from(projectsToBatch.values()).find(p => p.isWorkspaceRoot); - if (dependentProjectIsInWorkspace) { - expectedVersionInPackageJson = project.json.version; - } else { - const relativePathToProject = normalizePath(path__WEBPACK_IMPORTED_MODULE_2___default.a.relative(this.path, project.path)); - expectedVersionInPackageJson = `link:${relativePathToProject}`; - } // No issues! + if (!workspaceRootProject) { + throw new _errors__WEBPACK_IMPORTED_MODULE_3__["CliError"](`There was no yarn workspace root found.`); + } // Push in the workspace root first. - if (versionInPackageJson === expectedVersionInPackageJson) { - return; - } + batches.push([workspaceRootProject]); + projectsLeftToBatch.delete(workspaceRootProject.name); // In the next batch, push in all workspace projects. - let problemMsg; + const workspaceBatch = []; - if (Object(_package_json__WEBPACK_IMPORTED_MODULE_6__["isLinkDependency"])(versionInPackageJson) && dependentProjectIsInWorkspace) { - problemMsg = `but should be using a workspace`; - } else if (Object(_package_json__WEBPACK_IMPORTED_MODULE_6__["isLinkDependency"])(versionInPackageJson)) { - problemMsg = `using 'link:', but the path is wrong`; - } else { - problemMsg = `but it's not using the local package`; - } + for (const projectName of projectsLeftToBatch) { + const project = projectsToBatch.get(projectName); - throw new _errors__WEBPACK_IMPORTED_MODULE_4__["CliError"](`[${this.name}] depends on [${project.name}] ${problemMsg}. Update its package.json to the expected value below.`, { - actual: `"${project.name}": "${versionInPackageJson}"`, - expected: `"${project.name}": "${expectedVersionInPackageJson}"`, - package: `${this.name} (${this.packageJsonLocation})` - }); - } + if (project.isWorkspaceProject) { + workspaceBatch.push(project); + projectsLeftToBatch.delete(projectName); + } + } - getBuildConfig() { - return this.json.kibana && this.json.kibana.build || {}; + batches.push(workspaceBatch); } - /** - * Returns the directory that should be copied into the Kibana build artifact. - * This config can be specified to only include the project's build artifacts - * instead of everything located in the project directory. - */ + while (projectsLeftToBatch.size > 0) { + // Get all projects that have no remaining dependencies within the repo + // that haven't yet been picked. + const batch = []; - getIntermediateBuildDirectory() { - return path__WEBPACK_IMPORTED_MODULE_2___default.a.resolve(this.path, this.getBuildConfig().intermediateBuildDirectory || '.'); - } - - getCleanConfig() { - return this.json.kibana && this.json.kibana.clean || {}; - } + for (const projectName of projectsLeftToBatch) { + const projectDeps = projectGraph.get(projectName); + const needsDependenciesBatched = projectDeps.some(dep => projectsLeftToBatch.has(dep.name)); - hasScript(name) { - return name in this.scripts; - } + if (!needsDependenciesBatched) { + batch.push(projectsToBatch.get(projectName)); + } + } // If we weren't able to find a project with no remaining dependencies, + // then we've encountered a cycle in the dependency graph. - getExecutables() { - const raw = this.json.bin; - if (!raw) { - return {}; - } + const hasCycles = batch.length === 0; - if (typeof raw === 'string') { - return { - [this.name]: path__WEBPACK_IMPORTED_MODULE_2___default.a.resolve(this.path, raw) - }; + if (hasCycles) { + const cycleProjectNames = [...projectsLeftToBatch]; + const message = 'Encountered a cycle in the dependency graph. Projects in cycle are:\n' + cycleProjectNames.join(', '); + throw new _errors__WEBPACK_IMPORTED_MODULE_3__["CliError"](message); } - if (typeof raw === 'object') { - const binsConfig = {}; + batches.push(batch); + batch.forEach(project => projectsLeftToBatch.delete(project.name)); + } - for (const binName of Object.keys(raw)) { - binsConfig[binName] = path__WEBPACK_IMPORTED_MODULE_2___default.a.resolve(this.path, raw[binName]); - } + return batches; +} +function includeTransitiveProjects(subsetOfProjects, allProjects, { + onlyProductionDependencies = false +} = {}) { + const projectsWithDependents = new Map(); // the current list of packages we are expanding using breadth-first-search - return binsConfig; - } + const toProcess = [...subsetOfProjects]; - throw new _errors__WEBPACK_IMPORTED_MODULE_4__["CliError"](`[${this.name}] has an invalid "bin" field in its package.json, ` + `expected an object or a string`, { - binConfig: Object(util__WEBPACK_IMPORTED_MODULE_3__["inspect"])(raw), - package: `${this.name} (${this.packageJsonLocation})` + while (toProcess.length > 0) { + const project = toProcess.shift(); + const dependencies = onlyProductionDependencies ? project.productionDependencies : project.allDependencies; + Object.keys(dependencies).forEach(dep => { + if (allProjects.has(dep)) { + toProcess.push(allProjects.get(dep)); + } }); + projectsWithDependents.set(project.name, project); } - async runScript(scriptName, args = []) { - _log__WEBPACK_IMPORTED_MODULE_5__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.bold(`\n\nRunning script [${chalk__WEBPACK_IMPORTED_MODULE_0___default.a.green(scriptName)}] in [${chalk__WEBPACK_IMPORTED_MODULE_0___default.a.green(this.name)}]:\n`)); - return Object(_scripts__WEBPACK_IMPORTED_MODULE_7__["runScriptInPackage"])(scriptName, args, this); - } - - runScriptStreaming(scriptName, args = []) { - return Object(_scripts__WEBPACK_IMPORTED_MODULE_7__["runScriptInPackageStreaming"])(scriptName, args, this); - } - - hasDependencies() { - return Object.keys(this.allDependencies).length > 0; - } + return projectsWithDependents; +} - async installDependencies({ - extraArgs - }) { - _log__WEBPACK_IMPORTED_MODULE_5__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.bold(`\n\nInstalling dependencies in [${chalk__WEBPACK_IMPORTED_MODULE_0___default.a.green(this.name)}]:\n`)); - await Object(_scripts__WEBPACK_IMPORTED_MODULE_7__["installInDir"])(this.path, extraArgs); - await this.removeExtraneousNodeModules(); - } - /** - * Yarn workspaces symlinks workspace projects to the root node_modules, even - * when there is no depenency on the project. This results in unnecicary, and - * often duplicated code in the build archives. - */ +/***/ }), +/* 503 */ +/***/ (function(module, exports, __webpack_require__) { +// Approach: +// +// 1. Get the minimatch set +// 2. For each pattern in the set, PROCESS(pattern, false) +// 3. Store matches per-set, then uniq them +// +// PROCESS(pattern, inGlobStar) +// Get the first [n] items from pattern that are all strings +// Join these together. This is PREFIX. +// If there is no more remaining, then stat(PREFIX) and +// add to matches if it succeeds. END. +// +// If inGlobStar and PREFIX is symlink and points to dir +// set ENTRIES = [] +// else readdir(PREFIX) as ENTRIES +// If fail, END +// +// with ENTRIES +// If pattern[n] is GLOBSTAR +// // handle the case where the globstar match is empty +// // by pruning it out, and testing the resulting pattern +// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) +// // handle other cases. +// for ENTRY in ENTRIES (not dotfiles) +// // attach globstar + tail onto the entry +// // Mark that this entry is a globstar match +// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) +// +// else // not globstar +// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) +// Test ENTRY against pattern[n] +// If fails, continue +// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) +// +// Caveat: +// Cache all stats and readdirs results to minimize syscall. Since all +// we ever care about is existence and directory-ness, we can just keep +// `true` for files, and [children,...] for directories, or `false` for +// things that don't exist. - async removeExtraneousNodeModules() { - // this is only relevant for the root workspace - if (!this.isWorkspaceRoot) { - return; - } +module.exports = glob - const workspacesInfo = await Object(_scripts__WEBPACK_IMPORTED_MODULE_7__["yarnWorkspacesInfo"])(this.path); - const unusedWorkspaces = new Set(Object.keys(workspacesInfo)); // check for any cross-project dependency +var fs = __webpack_require__(349) +var rp = __webpack_require__(504) +var minimatch = __webpack_require__(506) +var Minimatch = minimatch.Minimatch +var inherits = __webpack_require__(510) +var EE = __webpack_require__(373).EventEmitter +var path = __webpack_require__(4) +var assert = __webpack_require__(371) +var isAbsolute = __webpack_require__(512) +var globSync = __webpack_require__(513) +var common = __webpack_require__(514) +var alphasort = common.alphasort +var alphasorti = common.alphasorti +var setopts = common.setopts +var ownProp = common.ownProp +var inflight = __webpack_require__(515) +var util = __webpack_require__(397) +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored - for (const name of Object.keys(workspacesInfo)) { - const workspace = workspacesInfo[name]; - workspace.workspaceDependencies.forEach(w => unusedWorkspaces.delete(w)); - } +var once = __webpack_require__(378) - unusedWorkspaces.forEach(name => { - const { - dependencies, - devDependencies - } = this.json; - const nodeModulesPath = path__WEBPACK_IMPORTED_MODULE_2___default.a.resolve(this.nodeModulesLocation, name); - const isDependency = dependencies && dependencies.hasOwnProperty(name); - const isDevDependency = devDependencies && devDependencies.hasOwnProperty(name); +function glob (pattern, options, cb) { + if (typeof options === 'function') cb = options, options = {} + if (!options) options = {} - if (!isDependency && !isDevDependency && fs__WEBPACK_IMPORTED_MODULE_1___default.a.existsSync(nodeModulesPath)) { - _log__WEBPACK_IMPORTED_MODULE_5__["log"].write(`No dependency on ${name}, removing link in node_modules`); - fs__WEBPACK_IMPORTED_MODULE_1___default.a.unlinkSync(nodeModulesPath); - } - }); + if (options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return globSync(pattern, options) } -} // We normalize all path separators to `/` in generated files - -function normalizePath(path) { - return path.replace(/[\\\/]+/g, '/'); + return new Glob(pattern, options, cb) } -/***/ }), -/* 518 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +glob.sync = globSync +var GlobSync = glob.GlobSync = globSync.GlobSync -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readPackageJson", function() { return readPackageJson; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "writePackageJson", function() { return writePackageJson; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isLinkDependency", function() { return isLinkDependency; }); -/* harmony import */ var read_pkg__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(519); -/* harmony import */ var read_pkg__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(read_pkg__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var write_pkg__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(545); -/* harmony import */ var write_pkg__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(write_pkg__WEBPACK_IMPORTED_MODULE_1__); -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ +// old api surface +glob.glob = glob +function extend (origin, add) { + if (add === null || typeof add !== 'object') { + return origin + } -function readPackageJson(cwd) { - return read_pkg__WEBPACK_IMPORTED_MODULE_0___default()({ - cwd, - normalize: false - }); -} -function writePackageJson(path, json) { - return write_pkg__WEBPACK_IMPORTED_MODULE_1___default()(path, json); + var keys = Object.keys(add) + var i = keys.length + while (i--) { + origin[keys[i]] = add[keys[i]] + } + return origin } -const isLinkDependency = depVersion => depVersion.startsWith('link:'); - -/***/ }), -/* 519 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +glob.hasMagic = function (pattern, options_) { + var options = extend({}, options_) + options.noprocess = true -const {promisify} = __webpack_require__(29); -const fs = __webpack_require__(23); -const path = __webpack_require__(16); -const parseJson = __webpack_require__(520); + var g = new Glob(pattern, options) + var set = g.minimatch.set -const readFileAsync = promisify(fs.readFile); + if (!pattern) + return false -module.exports = async options => { - options = { - cwd: process.cwd(), - normalize: true, - ...options - }; + if (set.length > 1) + return true - const filePath = path.resolve(options.cwd, 'package.json'); - const json = parseJson(await readFileAsync(filePath, 'utf8')); + for (var j = 0; j < set[0].length; j++) { + if (typeof set[0][j] !== 'string') + return true + } - if (options.normalize) { - __webpack_require__(521)(json); - } + return false +} - return json; -}; +glob.Glob = Glob +inherits(Glob, EE) +function Glob (pattern, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } -module.exports.sync = options => { - options = { - cwd: process.cwd(), - normalize: true, - ...options - }; + if (options && options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return new GlobSync(pattern, options) + } - const filePath = path.resolve(options.cwd, 'package.json'); - const json = parseJson(fs.readFileSync(filePath, 'utf8')); + if (!(this instanceof Glob)) + return new Glob(pattern, options, cb) - if (options.normalize) { - __webpack_require__(521)(json); - } + setopts(this, pattern, options) + this._didRealPath = false - return json; -}; + // process each pattern in the minimatch set + var n = this.minimatch.set.length + // The matches are stored as {: true,...} so that + // duplicates are automagically pruned. + // Later, we do an Object.keys() on these. + // Keep them as a list so we can fill in when nonull is set. + this.matches = new Array(n) -/***/ }), -/* 520 */ -/***/ (function(module, exports, __webpack_require__) { + if (typeof cb === 'function') { + cb = once(cb) + this.on('error', cb) + this.on('end', function (matches) { + cb(null, matches) + }) + } -"use strict"; + var self = this + this._processing = 0 -const errorEx = __webpack_require__(429); -const fallback = __webpack_require__(431); -const {default: LinesAndColumns} = __webpack_require__(432); -const {codeFrameColumns} = __webpack_require__(433); + this._emitQueue = [] + this._processQueue = [] + this.paused = false -const JSONError = errorEx('JSONError', { - fileName: errorEx.append('in %s'), - codeFrame: errorEx.append('\n\n%s\n') -}); + if (this.noprocess) + return this -module.exports = (string, reviver, filename) => { - if (typeof reviver === 'string') { - filename = reviver; - reviver = null; - } + if (n === 0) + return done() - try { - try { - return JSON.parse(string, reviver); - } catch (error) { - fallback(string, reviver); - throw error; - } - } catch (error) { - error.message = error.message.replace(/\n/g, ''); - const indexMatch = error.message.match(/in JSON at position (\d+) while parsing near/); + var sync = true + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false, done) + } + sync = false - const jsonError = new JSONError(error); - if (filename) { - jsonError.fileName = filename; - } + function done () { + --self._processing + if (self._processing <= 0) { + if (sync) { + process.nextTick(function () { + self._finish() + }) + } else { + self._finish() + } + } + } +} - if (indexMatch && indexMatch.length > 0) { - const lines = new LinesAndColumns(string); - const index = Number(indexMatch[1]); - const location = lines.locationForIndex(index); +Glob.prototype._finish = function () { + assert(this instanceof Glob) + if (this.aborted) + return - const codeFrame = codeFrameColumns( - string, - {start: {line: location.line + 1, column: location.column + 1}}, - {highlightCode: true} - ); + if (this.realpath && !this._didRealpath) + return this._realpath() - jsonError.codeFrame = codeFrame; - } + common.finish(this) + this.emit('end', this.found) +} - throw jsonError; - } -}; +Glob.prototype._realpath = function () { + if (this._didRealpath) + return + this._didRealpath = true -/***/ }), -/* 521 */ -/***/ (function(module, exports, __webpack_require__) { + var n = this.matches.length + if (n === 0) + return this._finish() -module.exports = normalize + var self = this + for (var i = 0; i < this.matches.length; i++) + this._realpathSet(i, next) -var fixer = __webpack_require__(522) -normalize.fixer = fixer + function next () { + if (--n === 0) + self._finish() + } +} -var makeWarning = __webpack_require__(543) +Glob.prototype._realpathSet = function (index, cb) { + var matchset = this.matches[index] + if (!matchset) + return cb() -var fieldsToFix = ['name','version','description','repository','modules','scripts' - ,'files','bin','man','bugs','keywords','readme','homepage','license'] -var otherThingsToFix = ['dependencies','people', 'typos'] + var found = Object.keys(matchset) + var self = this + var n = found.length -var thingsToFix = fieldsToFix.map(function(fieldName) { - return ucFirst(fieldName) + "Field" -}) -// two ways to do this in CoffeeScript on only one line, sub-70 chars: -// thingsToFix = fieldsToFix.map (name) -> ucFirst(name) + "Field" -// thingsToFix = (ucFirst(name) + "Field" for name in fieldsToFix) -thingsToFix = thingsToFix.concat(otherThingsToFix) + if (n === 0) + return cb() -function normalize (data, warn, strict) { - if(warn === true) warn = null, strict = true - if(!strict) strict = false - if(!warn || data.private) warn = function(msg) { /* noop */ } + var set = this.matches[index] = Object.create(null) + found.forEach(function (p, i) { + // If there's a problem with the stat, then it means that + // one or more of the links in the realpath couldn't be + // resolved. just return the abs value in that case. + p = self._makeAbs(p) + rp.realpath(p, self.realpathCache, function (er, real) { + if (!er) + set[real] = true + else if (er.syscall === 'stat') + set[p] = true + else + self.emit('error', er) // srsly wtf right here - if (data.scripts && - data.scripts.install === "node-gyp rebuild" && - !data.scripts.preinstall) { - data.gypfile = true - } - fixer.warn = function() { warn(makeWarning.apply(null, arguments)) } - thingsToFix.forEach(function(thingName) { - fixer["fix" + ucFirst(thingName)](data, strict) + if (--n === 0) { + self.matches[index] = set + cb() + } + }) }) - data._id = data.name + "@" + data.version } -function ucFirst (string) { - return string.charAt(0).toUpperCase() + string.slice(1); +Glob.prototype._mark = function (p) { + return common.mark(this, p) } +Glob.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} -/***/ }), -/* 522 */ -/***/ (function(module, exports, __webpack_require__) { +Glob.prototype.abort = function () { + this.aborted = true + this.emit('abort') +} -var semver = __webpack_require__(523) -var validateLicense = __webpack_require__(524); -var hostedGitInfo = __webpack_require__(529) -var isBuiltinModule = __webpack_require__(532).isCore -var depTypes = ["dependencies","devDependencies","optionalDependencies"] -var extractDescription = __webpack_require__(541) -var url = __webpack_require__(452) -var typos = __webpack_require__(542) +Glob.prototype.pause = function () { + if (!this.paused) { + this.paused = true + this.emit('pause') + } +} -var fixer = module.exports = { - // default warning function - warn: function() {}, - - fixRepositoryField: function(data) { - if (data.repositories) { - this.warn("repositories"); - data.repository = data.repositories[0] - } - if (!data.repository) return this.warn("missingRepository") - if (typeof data.repository === "string") { - data.repository = { - type: "git", - url: data.repository +Glob.prototype.resume = function () { + if (this.paused) { + this.emit('resume') + this.paused = false + if (this._emitQueue.length) { + var eq = this._emitQueue.slice(0) + this._emitQueue.length = 0 + for (var i = 0; i < eq.length; i ++) { + var e = eq[i] + this._emitMatch(e[0], e[1]) } } - var r = data.repository.url || "" - if (r) { - var hosted = hostedGitInfo.fromUrl(r) - if (hosted) { - r = data.repository.url - = hosted.getDefaultRepresentation() == "shortcut" ? hosted.https() : hosted.toString() + if (this._processQueue.length) { + var pq = this._processQueue.slice(0) + this._processQueue.length = 0 + for (var i = 0; i < pq.length; i ++) { + var p = pq[i] + this._processing-- + this._process(p[0], p[1], p[2], p[3]) } } + } +} - if (r.match(/github.com\/[^\/]+\/[^\/]+\.git\.git$/)) { - this.warn("brokenGitUrl", r) - } +Glob.prototype._process = function (pattern, index, inGlobStar, cb) { + assert(this instanceof Glob) + assert(typeof cb === 'function') + + if (this.aborted) + return + + this._processing++ + if (this.paused) { + this._processQueue.push([pattern, index, inGlobStar, cb]) + return } -, fixTypos: function(data) { - Object.keys(typos.topLevel).forEach(function (d) { - if (data.hasOwnProperty(d)) { - this.warn("typo", d, typos.topLevel[d]) - } - }, this) + //console.error('PROCESS %d', this._processing, pattern) + + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ } + // now n is the index of the first one that is *not* a string. -, fixScriptsField: function(data) { - if (!data.scripts) return - if (typeof data.scripts !== "object") { - this.warn("nonObjectScripts") - delete data.scripts + // see if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index, cb) return - } - Object.keys(data.scripts).forEach(function (k) { - if (typeof data.scripts[k] !== "string") { - this.warn("nonStringScript") - delete data.scripts[k] - } else if (typos.script[k] && !data.scripts[typos.script[k]]) { - this.warn("typo", k, typos.script[k], "scripts") - } - }, this) - } -, fixFilesField: function(data) { - var files = data.files - if (files && !Array.isArray(files)) { - this.warn("nonArrayFiles") - delete data.files - } else if (data.files) { - data.files = data.files.filter(function(file) { - if (!file || typeof file !== "string") { - this.warn("invalidFilename", file) - return false - } else { - return true - } - }, this) - } + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break } -, fixBinField: function(data) { - if (!data.bin) return; - if (typeof data.bin === "string") { - var b = {} - var match - if (match = data.name.match(/^@[^/]+[/](.*)$/)) { - b[match[1]] = data.bin + var remain = pattern.slice(n) + + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix + + var abs = this._makeAbs(read) + + //if ignored, skip _processing + if (childrenIgnored(this, read)) + return cb() + + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) +} + +Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} + +Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return cb() + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) } else { - b[data.name] = data.bin + m = e.match(pn) } - data.bin = b + if (m) + matchedEntries.push(e) } } -, fixManField: function(data) { - if (!data.man) return; - if (typeof data.man === "string") { - data.man = [ data.man ] - } - } -, fixBundleDependenciesField: function(data) { - var bdd = "bundledDependencies" - var bd = "bundleDependencies" - if (data[bdd] && !data[bd]) { - data[bd] = data[bdd] - delete data[bdd] - } - if (data[bd] && !Array.isArray(data[bd])) { - this.warn("nonArrayBundleDependencies") - delete data[bd] - } else if (data[bd]) { - data[bd] = data[bd].filter(function(bd) { - if (!bd || typeof bd !== 'string') { - this.warn("nonStringBundleDependency", bd) - return false - } else { - if (!data.dependencies) { - data.dependencies = {} - } - if (!data.dependencies.hasOwnProperty(bd)) { - this.warn("nonDependencyBundleDependency", bd) - data.dependencies[bd] = "*" - } - return true - } - }, this) - } - } + //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) -, fixDependencies: function(data, strict) { - var loose = !strict - objectifyDeps(data, this.warn) - addOptionalDepsToDeps(data, this.warn) - this.fixBundleDependenciesField(data) + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return cb() - ;['dependencies','devDependencies'].forEach(function(deps) { - if (!(deps in data)) return - if (!data[deps] || typeof data[deps] !== "object") { - this.warn("nonObjectDependencies", deps) - delete data[deps] - return + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e } - Object.keys(data[deps]).forEach(function (d) { - var r = data[deps][d] - if (typeof r !== 'string') { - this.warn("nonStringDependency", d, JSON.stringify(r)) - delete data[deps][d] - } - var hosted = hostedGitInfo.fromUrl(data[deps][d]) - if (hosted) data[deps][d] = hosted.toString() - }, this) - }, this) - } -, fixModulesField: function (data) { - if (data.modules) { - this.warn("deprecatedModules") - delete data.modules + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) } + // This was the last one, and no stats were needed + return cb() } -, fixKeywordsField: function (data) { - if (typeof data.keywords === "string") { - data.keywords = data.keywords.split(/,\s+/) - } - if (data.keywords && !Array.isArray(data.keywords)) { - delete data.keywords - this.warn("nonArrayKeywords") - } else if (data.keywords) { - data.keywords = data.keywords.filter(function(kw) { - if (typeof kw !== "string" || !kw) { - this.warn("nonStringKeyword"); - return false - } else { - return true - } - }, this) + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e } + this._process([e].concat(remain), index, inGlobStar, cb) } + cb() +} -, fixVersionField: function(data, strict) { - // allow "loose" semver 1.0 versions in non-strict mode - // enforce strict semver 2.0 compliance in strict mode - var loose = !strict - if (!data.version) { - data.version = "" - return true - } - if (!semver.valid(data.version, loose)) { - throw new Error('Invalid version: "'+ data.version + '"') - } - data.version = semver.clean(data.version, loose) - return true - } +Glob.prototype._emitMatch = function (index, e) { + if (this.aborted) + return -, fixPeople: function(data) { - modifyPeople(data, unParsePerson) - modifyPeople(data, parsePerson) - } + if (isIgnored(this, e)) + return -, fixNameField: function(data, options) { - if (typeof options === "boolean") options = {strict: options} - else if (typeof options === "undefined") options = {} - var strict = options.strict - if (!data.name && !strict) { - data.name = "" - return - } - if (typeof data.name !== "string") { - throw new Error("name field must be a string.") - } - if (!strict) - data.name = data.name.trim() - ensureValidName(data.name, strict, options.allowLegacyCase) - if (isBuiltinModule(data.name)) - this.warn("conflictingName", data.name) + if (this.paused) { + this._emitQueue.push([index, e]) + return } + var abs = isAbsolute(e) ? e : this._makeAbs(e) -, fixDescriptionField: function (data) { - if (data.description && typeof data.description !== 'string') { - this.warn("nonStringDescription") - delete data.description - } - if (data.readme && !data.description) - data.description = extractDescription(data.readme) - if(data.description === undefined) delete data.description; - if (!data.description) this.warn("missingDescription") - } + if (this.mark) + e = this._mark(e) -, fixReadmeField: function (data) { - if (!data.readme) { - this.warn("missingReadme") - data.readme = "ERROR: No README data found!" - } - } + if (this.absolute) + e = abs -, fixBugsField: function(data) { - if (!data.bugs && data.repository && data.repository.url) { - var hosted = hostedGitInfo.fromUrl(data.repository.url) - if(hosted && hosted.bugs()) { - data.bugs = {url: hosted.bugs()} - } - } - else if(data.bugs) { - var emailRe = /^.+@.*\..+$/ - if(typeof data.bugs == "string") { - if(emailRe.test(data.bugs)) - data.bugs = {email:data.bugs} - else if(url.parse(data.bugs).protocol) - data.bugs = {url: data.bugs} - else - this.warn("nonEmailUrlBugsString") - } - else { - bugsTypos(data.bugs, this.warn) - var oldBugs = data.bugs - data.bugs = {} - if(oldBugs.url) { - if(typeof(oldBugs.url) == "string" && url.parse(oldBugs.url).protocol) - data.bugs.url = oldBugs.url - else - this.warn("nonUrlBugsUrlField") - } - if(oldBugs.email) { - if(typeof(oldBugs.email) == "string" && emailRe.test(oldBugs.email)) - data.bugs.email = oldBugs.email - else - this.warn("nonEmailBugsEmailField") - } - } - if(!data.bugs.email && !data.bugs.url) { - delete data.bugs - this.warn("emptyNormalizedBugs") - } - } + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return } -, fixHomepageField: function(data) { - if (!data.homepage && data.repository && data.repository.url) { - var hosted = hostedGitInfo.fromUrl(data.repository.url) - if (hosted && hosted.docs()) data.homepage = hosted.docs() - } - if (!data.homepage) return + this.matches[index][e] = true - if(typeof data.homepage !== "string") { - this.warn("nonUrlHomepage") - return delete data.homepage - } - if(!url.parse(data.homepage).protocol) { - data.homepage = "http://" + data.homepage - } - } + var st = this.statCache[abs] + if (st) + this.emit('stat', e, st) -, fixLicenseField: function(data) { - if (!data.license) { - return this.warn("missingLicense") - } else{ - if ( - typeof(data.license) !== 'string' || - data.license.length < 1 || - data.license.trim() === '' - ) { - this.warn("invalidLicense") - } else { - if (!validateLicense(data.license).validForNewPackages) - this.warn("invalidLicense") - } - } - } + this.emit('match', e) } -function isValidScopedPackageName(spec) { - if (spec.charAt(0) !== '@') return false +Glob.prototype._readdirInGlobStar = function (abs, cb) { + if (this.aborted) + return - var rest = spec.slice(1).split('/') - if (rest.length !== 2) return false + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false, cb) - return rest[0] && rest[1] && - rest[0] === encodeURIComponent(rest[0]) && - rest[1] === encodeURIComponent(rest[1]) -} + var lstatkey = 'lstat\0' + abs + var self = this + var lstatcb = inflight(lstatkey, lstatcb_) -function isCorrectlyEncodedName(spec) { - return !spec.match(/[\/@\s\+%:]/) && - spec === encodeURIComponent(spec) -} + if (lstatcb) + fs.lstat(abs, lstatcb) -function ensureValidName (name, strict, allowLegacyCase) { - if (name.charAt(0) === "." || - !(isValidScopedPackageName(name) || isCorrectlyEncodedName(name)) || - (strict && (!allowLegacyCase) && name !== name.toLowerCase()) || - name.toLowerCase() === "node_modules" || - name.toLowerCase() === "favicon.ico") { - throw new Error("Invalid name: " + JSON.stringify(name)) + function lstatcb_ (er, lstat) { + if (er && er.code === 'ENOENT') + return cb() + + var isSym = lstat && lstat.isSymbolicLink() + self.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) { + self.cache[abs] = 'FILE' + cb() + } else + self._readdir(abs, false, cb) } } -function modifyPeople (data, fn) { - if (data.author) data.author = fn(data.author) - ;["maintainers", "contributors"].forEach(function (set) { - if (!Array.isArray(data[set])) return; - data[set] = data[set].map(fn) - }) - return data -} +Glob.prototype._readdir = function (abs, inGlobStar, cb) { + if (this.aborted) + return -function unParsePerson (person) { - if (typeof person === "string") return person - var name = person.name || "" - var u = person.url || person.web - var url = u ? (" ("+u+")") : "" - var e = person.email || person.mail - var email = e ? (" <"+e+">") : "" - return name+email+url -} + cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) + if (!cb) + return -function parsePerson (person) { - if (typeof person !== "string") return person - var name = person.match(/^([^\(<]+)/) - var url = person.match(/\(([^\)]+)\)/) - var email = person.match(/<([^>]+)>/) - var obj = {} - if (name && name[0].trim()) obj.name = name[0].trim() - if (email) obj.email = email[1]; - if (url) obj.url = url[1]; - return obj -} + //console.error('RD %j %j', +inGlobStar, abs) + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs, cb) -function addOptionalDepsToDeps (data, warn) { - var o = data.optionalDependencies - if (!o) return; - var d = data.dependencies || {} - Object.keys(o).forEach(function (k) { - d[k] = o[k] - }) - data.dependencies = d -} + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return cb() -function depObjectify (deps, type, warn) { - if (!deps) return {} - if (typeof deps === "string") { - deps = deps.trim().split(/[\n\r\s\t ,]+/) + if (Array.isArray(c)) + return cb(null, c) } - if (!Array.isArray(deps)) return deps - warn("deprecatedArrayDependencies", type) - var o = {} - deps.filter(function (d) { - return typeof d === "string" - }).forEach(function(d) { - d = d.trim().split(/(:?[@\s><=])/) - var dn = d.shift() - var dv = d.join("") - dv = dv.trim() - dv = dv.replace(/^@/, "") - o[dn] = dv - }) - return o -} -function objectifyDeps (data, warn) { - depTypes.forEach(function (type) { - if (!data[type]) return; - data[type] = depObjectify(data[type], type, warn) - }) + var self = this + fs.readdir(abs, readdirCb(this, abs, cb)) } -function bugsTypos(bugs, warn) { - if (!bugs) return - Object.keys(bugs).forEach(function (k) { - if (typos.bugs[k]) { - warn("typo", k, typos.bugs[k], "bugs") - bugs[typos.bugs[k]] = bugs[k] - delete bugs[k] - } - }) +function readdirCb (self, abs, cb) { + return function (er, entries) { + if (er) + self._readdirError(abs, er, cb) + else + self._readdirEntries(abs, entries, cb) + } } +Glob.prototype._readdirEntries = function (abs, entries, cb) { + if (this.aborted) + return -/***/ }), -/* 523 */ -/***/ (function(module, exports) { - -exports = module.exports = SemVer - -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) + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } } -} else { - debug = function () {} -} -// 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' + this.cache[abs] = entries + return cb(null, entries) +} -var MAX_LENGTH = 256 -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991 +Glob.prototype._readdirError = function (f, er, cb) { + if (this.aborted) + return -// Max safe segment length for coercion. -var MAX_SAFE_COMPONENT_LENGTH = 16 + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + this.emit('error', error) + this.abort() + } + break -// The actual regexps go on exports.re -var re = exports.re = [] -var src = exports.src = [] -var R = 0 + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) { + this.emit('error', er) + // If the error is handled, then we abort + // if not, we threw out of here + this.abort() + } + if (!this.silent) + console.error('glob error', er) + break + } -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. + return cb() +} -var NUMERICIDENTIFIER = R++ -src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' -var NUMERICIDENTIFIERLOOSE = R++ -src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' +Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. -var NONNUMERICIDENTIFIER = R++ -src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' +Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + //console.error('pgs2', prefix, remain[0], entries) -// ## Main Version -// Three dot-separated numeric identifiers. + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return cb() -var MAINVERSION = R++ -src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')' + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) -var MAINVERSIONLOOSE = R++ -src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')' + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false, cb) -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. + var isSym = this.symlinks[abs] + var len = entries.length -var PRERELEASEIDENTIFIER = R++ -src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + - '|' + src[NONNUMERICIDENTIFIER] + ')' + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return cb() -var PRERELEASEIDENTIFIERLOOSE = R++ -src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + - '|' + src[NONNUMERICIDENTIFIER] + ')' + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true, cb) -var PRERELEASE = R++ -src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + - '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' + var below = gspref.concat(entries[i], remain) + this._process(below, index, true, cb) + } -var PRERELEASELOOSE = R++ -src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' + cb() +} -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. +Glob.prototype._processSimple = function (prefix, index, cb) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var self = this + this._stat(prefix, function (er, exists) { + self._processSimple2(prefix, index, er, exists, cb) + }) +} +Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { -var BUILDIDENTIFIER = R++ -src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' + //console.error('ps2', prefix, exists) -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. + if (!this.matches[index]) + this.matches[index] = Object.create(null) -var BUILD = R++ -src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + - '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' + // If it doesn't exist, then just mark the lack of results + if (!exists) + return cb() -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } -// 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. + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') -var FULL = R++ -var FULLPLAIN = 'v?' + src[MAINVERSION] + - src[PRERELEASE] + '?' + - src[BUILD] + '?' + // Mark this as a match + this._emitMatch(index, prefix) + cb() +} -src[FULL] = '^' + FULLPLAIN + '$' +// Returns either 'DIR', 'FILE', or false +Glob.prototype._stat = function (f, cb) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' -// 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. -var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + - src[PRERELEASELOOSE] + '?' + - src[BUILD] + '?' + if (f.length > this.maxLength) + return cb() -var LOOSE = R++ -src[LOOSE] = '^' + LOOSEPLAIN + '$' + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] -var GTLT = R++ -src[GTLT] = '((?:<|>)?=?)' + if (Array.isArray(c)) + c = 'DIR' -// 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. -var XRANGEIDENTIFIERLOOSE = R++ -src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' -var XRANGEIDENTIFIER = R++ -src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return cb(null, c) -var XRANGEPLAIN = R++ -src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:' + src[PRERELEASE] + ')?' + - src[BUILD] + '?' + - ')?)?' + if (needDir && c === 'FILE') + return cb() -var XRANGEPLAINLOOSE = R++ -src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[PRERELEASELOOSE] + ')?' + - src[BUILD] + '?' + - ')?)?' + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } -var XRANGE = R++ -src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' -var XRANGELOOSE = R++ -src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' + var exists + var stat = this.statCache[abs] + if (stat !== undefined) { + if (stat === false) + return cb(null, stat) + else { + var type = stat.isDirectory() ? 'DIR' : 'FILE' + if (needDir && type === 'FILE') + return cb() + else + return cb(null, type, stat) + } + } -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -var COERCE = R++ -src[COERCE] = '(?:^|[^\\d])' + - '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:$|[^\\d])' + var self = this + var statcb = inflight('stat\0' + abs, lstatcb_) + if (statcb) + fs.lstat(abs, statcb) -// Tilde ranges. -// Meaning is "reasonably at or greater than" -var LONETILDE = R++ -src[LONETILDE] = '(?:~>?)' + function lstatcb_ (er, lstat) { + if (lstat && lstat.isSymbolicLink()) { + // If it's a symlink, then treat it as the target, unless + // the target does not exist, then treat it as a file. + return fs.stat(abs, function (er, stat) { + if (er) + self._stat2(f, abs, null, lstat, cb) + else + self._stat2(f, abs, er, stat, cb) + }) + } else { + self._stat2(f, abs, er, lstat, cb) + } + } +} -var TILDETRIM = R++ -src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' -re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') -var tildeTrimReplace = '$1~' +Glob.prototype._stat2 = function (f, abs, er, stat, cb) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return cb() + } -var TILDE = R++ -src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' -var TILDELOOSE = R++ -src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' + var needDir = f.slice(-1) === '/' + this.statCache[abs] = stat -// Caret ranges. -// Meaning is "at least and backwards compatible with" -var LONECARET = R++ -src[LONECARET] = '(?:\\^)' + if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) + return cb(null, false, stat) -var CARETTRIM = R++ -src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' -re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') -var caretTrimReplace = '$1^' + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + this.cache[abs] = this.cache[abs] || c -var CARET = R++ -src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' -var CARETLOOSE = R++ -src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' + if (needDir && c === 'FILE') + return cb() -// A simple gt/lt/eq thing, or just "" to indicate "any version" -var COMPARATORLOOSE = R++ -src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' -var COMPARATOR = R++ -src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' + return cb(null, c, stat) +} -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -var COMPARATORTRIM = R++ -src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + - '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' -// this one has to use the /g flag -re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') -var comparatorTrimReplace = '$1$2$3' +/***/ }), +/* 504 */ +/***/ (function(module, exports, __webpack_require__) { -// 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. -var HYPHENRANGE = R++ -src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAIN] + ')' + - '\\s*$' +module.exports = realpath +realpath.realpath = realpath +realpath.sync = realpathSync +realpath.realpathSync = realpathSync +realpath.monkeypatch = monkeypatch +realpath.unmonkeypatch = unmonkeypatch -var HYPHENRANGELOOSE = R++ -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$' +var fs = __webpack_require__(349) +var origRealpath = fs.realpath +var origRealpathSync = fs.realpathSync -// Star ranges basically just allow anything at all. -var STAR = R++ -src[STAR] = '(<|>)?=?\\s*\\*' +var version = process.version +var ok = /^v[0-5]\./.test(version) +var old = __webpack_require__(505) -// 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]) - } +function newError (er) { + return er && er.syscall === 'realpath' && ( + er.code === 'ELOOP' || + er.code === 'ENOMEM' || + er.code === 'ENAMETOOLONG' + ) } -exports.parse = parse -function parse (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (version instanceof SemVer) { - return version - } - - if (typeof version !== 'string') { - return null +function realpath (p, cache, cb) { + if (ok) { + return origRealpath(p, cache, cb) } - if (version.length > MAX_LENGTH) { - return null + if (typeof cache === 'function') { + cb = cache + cache = null } + origRealpath(p, cache, function (er, result) { + if (newError(er)) { + old.realpath(p, cache, cb) + } else { + cb(er, result) + } + }) +} - var r = options.loose ? re[LOOSE] : re[FULL] - if (!r.test(version)) { - return null +function realpathSync (p, cache) { + if (ok) { + return origRealpathSync(p, cache) } try { - return new SemVer(version, options) + return origRealpathSync(p, cache) } catch (er) { - return null + if (newError(er)) { + return old.realpathSync(p, cache) + } else { + throw er + } } } -exports.valid = valid -function valid (version, options) { - var v = parse(version, options) - return v ? v.version : null +function monkeypatch () { + fs.realpath = realpath + fs.realpathSync = realpathSync } -exports.clean = clean -function clean (version, options) { - var s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null +function unmonkeypatch () { + fs.realpath = origRealpath + fs.realpathSync = origRealpathSync } -exports.SemVer = SemVer - -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) - } - - if (version.length > MAX_LENGTH) { - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') - } - - if (!(this instanceof SemVer)) { - return new SemVer(version, options) - } - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose +/***/ }), +/* 505 */ +/***/ (function(module, exports, __webpack_require__) { - var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - if (!m) { - throw new TypeError('Invalid Version: ' + version) - } +var pathModule = __webpack_require__(4); +var isWindows = process.platform === 'win32'; +var fs = __webpack_require__(349); - this.raw = version +// JavaScript implementation of realpath, ported from node pre-v6 - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] +var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } +function rethrow() { + // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and + // is fairly slow to generate. + var callback; + if (DEBUG) { + var backtrace = new Error; + callback = debugCallback; + } else + callback = missingCallback; - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } + return callback; - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') + function debugCallback(err) { + if (err) { + backtrace.message = err.message; + err = backtrace; + missingCallback(err); + } } - // 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 - } + function missingCallback(err) { + if (err) { + if (process.throwDeprecation) + throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs + else if (!process.noDeprecation) { + var msg = 'fs: missing callback ' + (err.stack || err.message); + if (process.traceDeprecation) + console.trace(msg); + else + console.error(msg); } - return id - }) + } } +} - this.build = m[5] ? m[5].split('.') : [] - this.format() +function maybeCallback(cb) { + return typeof cb === 'function' ? cb : rethrow(); } -SemVer.prototype.format = function () { - this.version = this.major + '.' + this.minor + '.' + this.patch - if (this.prerelease.length) { - this.version += '-' + this.prerelease.join('.') - } - return this.version +var normalize = pathModule.normalize; + +// Regexp that finds the next partion of a (partial) path +// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] +if (isWindows) { + var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; +} else { + var nextPartRe = /(.*?)(?:[\/]+|$)/g; } -SemVer.prototype.toString = function () { - return this.version +// Regex to find the device root, including trailing slash. E.g. 'c:\\'. +if (isWindows) { + var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; +} else { + var splitRootRe = /^[\/]*/; } -SemVer.prototype.compare = function (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) +exports.realpathSync = function realpathSync(p, cache) { + // make p is absolute + p = pathModule.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return cache[p]; } - return this.compareMain(other) || this.comparePre(other) -} + var original = p, + seenLinks = {}, + knownHard = {}; -SemVer.prototype.compareMain = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) -} + start(); -SemVer.prototype.comparePre = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; - // 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 + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstatSync(base); + knownHard[base] = true; + } } - 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) + // walk down the path, swapping out linked pathparts for their real + // values + // NB: p.length changes. + while (pos < p.length) { + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + continue; } - } 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) + var resolvedLink; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // some known symbolic link. no need to stat again. + resolvedLink = cache[base]; + } else { + var stat = fs.lstatSync(base); + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + continue; } - this.inc('pre', identifier) - break - 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) + // read the link if it wasn't read before + // dev/ino always return 0 on windows, so skip the check. + var linkTarget = null; + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + linkTarget = seenLinks[id]; } } - 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] - } + if (linkTarget === null) { + fs.statSync(base); + linkTarget = fs.readlinkSync(base); } - break + resolvedLink = pathModule.resolve(previous, linkTarget); + // track this, if given a cache. + if (cache) cache[base] = resolvedLink; + if (!isWindows) seenLinks[id] = linkTarget; + } - default: - throw new Error('invalid increment argument: ' + release) + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); } - 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 - } + if (cache) cache[original] = p; - try { - return new SemVer(version, loose).inc(release, identifier).version - } catch (er) { - return null - } -} + return p; +}; -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 - } -} -exports.compareIdentifiers = compareIdentifiers +exports.realpath = function realpath(p, cache, cb) { + if (typeof cb !== 'function') { + cb = maybeCallback(cache); + cache = null; + } -var numeric = /^[0-9]+$/ -function compareIdentifiers (a, b) { - var anum = numeric.test(a) - var bnum = numeric.test(b) + // make p is absolute + p = pathModule.resolve(p); - if (anum && bnum) { - a = +a - b = +b + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return process.nextTick(cb.bind(null, null, cache[p])); } - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 -} + var original = p, + seenLinks = {}, + knownHard = {}; -exports.rcompareIdentifiers = rcompareIdentifiers -function rcompareIdentifiers (a, b) { - return compareIdentifiers(b, a) -} + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; -exports.major = major -function major (a, loose) { - return new SemVer(a, loose).major -} + start(); -exports.minor = minor -function minor (a, loose) { - return new SemVer(a, loose).minor -} + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; -exports.patch = patch -function patch (a, loose) { - return new SemVer(a, loose).patch -} + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstat(base, function(err) { + if (err) return cb(err); + knownHard[base] = true; + LOOP(); + }); + } else { + process.nextTick(LOOP); + } + } -exports.compare = compare -function compare (a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)) -} + // walk down the path, swapping out linked pathparts for their real + // values + function LOOP() { + // stop if scanned past end of path + if (pos >= p.length) { + if (cache) cache[original] = p; + return cb(null, p); + } -exports.compareLoose = compareLoose -function compareLoose (a, b) { - return compare(a, b, true) -} + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; -exports.rcompare = rcompare -function rcompare (a, b, loose) { - return compare(b, a, loose) -} + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + return process.nextTick(LOOP); + } -exports.sort = sort -function sort (list, loose) { - return list.sort(function (a, b) { - return exports.compare(a, b, loose) - }) -} - -exports.rsort = rsort -function rsort (list, loose) { - return list.sort(function (a, b) { - return exports.rcompare(a, b, loose) - }) -} - -exports.gt = gt -function gt (a, b, loose) { - return compare(a, b, loose) > 0 -} + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // known symbolic link. no need to stat again. + return gotResolvedLink(cache[base]); + } -exports.lt = lt -function lt (a, b, loose) { - return compare(a, b, loose) < 0 -} + return fs.lstat(base, gotStat); + } -exports.eq = eq -function eq (a, b, loose) { - return compare(a, b, loose) === 0 -} + function gotStat(err, stat) { + if (err) return cb(err); -exports.neq = neq -function neq (a, b, loose) { - return compare(a, b, loose) !== 0 -} + // if not a symlink, skip to the next path part + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + return process.nextTick(LOOP); + } -exports.gte = gte -function gte (a, b, loose) { - return compare(a, b, loose) >= 0 -} + // stat & read the link if not read before + // call gotTarget as soon as the link target is known + // dev/ino always return 0 on windows, so skip the check. + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + return gotTarget(null, seenLinks[id], base); + } + } + fs.stat(base, function(err) { + if (err) return cb(err); -exports.lte = lte -function lte (a, b, loose) { - return compare(a, b, loose) <= 0 -} + fs.readlink(base, function(err, target) { + if (!isWindows) seenLinks[id] = target; + gotTarget(err, target); + }); + }); + } -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 + function gotTarget(err, target, base) { + if (err) return cb(err); - case '!==': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a !== b + var resolvedLink = pathModule.resolve(previous, target); + if (cache) cache[base] = resolvedLink; + gotResolvedLink(resolvedLink); + } - case '': - case '=': - case '==': - return eq(a, b, loose) + function gotResolvedLink(resolvedLink) { + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } +}; - case '!=': - return neq(a, b, loose) - case '>': - return gt(a, b, loose) +/***/ }), +/* 506 */ +/***/ (function(module, exports, __webpack_require__) { - case '>=': - return gte(a, b, loose) +module.exports = minimatch +minimatch.Minimatch = Minimatch - case '<': - return lt(a, b, loose) +var path = { sep: '/' } +try { + path = __webpack_require__(4) +} catch (er) {} - case '<=': - return lte(a, b, loose) +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = __webpack_require__(507) - default: - throw new TypeError('Invalid operator: ' + op) - } +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } } -exports.Comparator = Comparator -function Comparator (comp, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value - } - } +// * => any number of characters +var star = qmark + '*?' - if (!(this instanceof Comparator)) { - return new Comparator(comp, options) - } +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') - debug('comp', this) +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) } -var ANY = {} -Comparator.prototype.parse = function (comp) { - var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var m = comp.match(r) - - if (!m) { - throw new TypeError('Invalid comparator: ' + comp) - } - - this.operator = m[1] - if (this.operator === '=') { - this.operator = '' - } +// normalizes slashes. +var slashSplit = /\/+/ - // 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) +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) } } -Comparator.prototype.toString = function () { - return this.value +function ext (a, b) { + a = a || {} + b = b || {} + var t = {} + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + return t } -Comparator.prototype.test = function (version) { - debug('Comparator.test', version, this.options.loose) +minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch - if (this.semver === ANY) { - return true + var orig = minimatch + + var m = function minimatch (p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)) } - if (typeof version === 'string') { - version = new SemVer(version, this.options) + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) } - return cmp(version, this.operator, this.semver, this.options) + return m } -Comparator.prototype.intersects = function (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } +Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch + return minimatch.defaults(def).Minimatch +} - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } +function minimatch (p, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') } - var rangeTmp + if (!options) options = {} - if (this.operator === '') { - rangeTmp = new Range(comp.value, options) - return satisfies(this.value, rangeTmp, options) - } else if (comp.operator === '') { - rangeTmp = new Range(this.value, options) - return satisfies(comp.semver, rangeTmp, options) + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false } - 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 === '>')) + // "" only matches "" + if (pattern.trim() === '') return p === '' - return sameDirectionIncreasing || sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || oppositeDirectionsGreaterThan + return new Minimatch(pattern, options).match(p) } -exports.Range = Range -function Range (range, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) } - if (range instanceof Range) { - if (range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease) { - return range - } else { - return new Range(range.raw, options) - } + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') } - if (range instanceof Comparator) { - return new Range(range.value, options) - } + if (!options) options = {} + pattern = pattern.trim() - if (!(this instanceof Range)) { - return new Range(range, options) + // windows support: need to use /, not \ + if (path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') } this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease - - // 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 (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range) - } + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false - this.format() + // make the set of regexps etc. + this.make() } -Range.prototype.format = function () { - this.range = this.set.map(function (comps) { - return comps.join(' ').trim() - }).join('||').trim() - return this.range -} +Minimatch.prototype.debug = function () {} -Range.prototype.toString = function () { - return this.range -} +Minimatch.prototype.make = make +function make () { + // don't do it more than once. + if (this._made) return -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[HYPHENRANGELOOSE] : re[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[COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range, re[COMPARATORTRIM]) + var pattern = this.pattern + var options = this.options - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace) + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace) + // step 1: figure out negation, etc. + this.parseNegate() - // normalize spaces - range = range.split(/\s+/).join(' ') + // step 2: expand braces + var set = this.globSet = this.braceExpand() - // At this point, the range is completely trimmed and - // ready to be split into comparators. + if (options.debug) this.debug = console.error - var compRe = loose ? re[COMPARATORLOOSE] : re[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) + this.debug(this.pattern, set) - return set -} + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) -Range.prototype.intersects = function (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') - } + this.debug(this.pattern, set) - return this.set.some(function (thisComparators) { - return thisComparators.every(function (thisComparator) { - return range.set.some(function (rangeComparators) { - return rangeComparators.every(function (rangeComparator) { - return thisComparator.intersects(rangeComparator, options) - }) - }) - }) - }) -} + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) -// 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(' ') + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 }) -} -// 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 -} + this.debug(this.pattern, set) -function isX (id) { - return !id || id.toLowerCase() === 'x' || id === '*' + this.set = set } -// ~, ~> --> * (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(' ') -} +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 -function replaceTilde (comp, options) { - var r = options.loose ? re[TILDELOOSE] : re[TILDE] - return comp.replace(r, function (_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr) - var ret + if (options.nonegate) return - 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' - } + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ + } - debug('tilde return', ret) - return ret - }) + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate } -// ^ --> * (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(' ') +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) } -function replaceCaret (comp, options) { - debug('caret', comp, options) - var r = options.loose ? re[CARETLOOSE] : re[CARET] - return comp.replace(r, function (_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr) - var ret +Minimatch.prototype.braceExpand = braceExpand - 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' - } +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options } 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' - } - } - - debug('caret return', ret) - return ret - }) -} - -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[XRANGELOOSE] : re[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 = '' - } - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<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 - } - } 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 - } else if (xm) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (xp) { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + options = {} } + } - debug('xRange return', ret) - - return ret - }) -} - -// 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[STAR], '') -} + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern -// This function is passed to string.replace(re[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 + if (typeof pattern === 'undefined') { + throw new TypeError('undefined pattern') } - 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.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] } - return (from + ' ' + to).trim() + return expand(pattern) } -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function (version) { - if (!version) { - return false +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + if (pattern.length > 1024 * 64) { + throw new TypeError('pattern is too long') } - if (typeof version === 'string') { - version = new SemVer(version, this.options) - } + var options = this.options - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false -} + // shortcuts + if (!options.noglobstar && pattern === '**') return GLOBSTAR + if (pattern === '') return '' -function testSet (set, version, options) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var negativeLists = [] + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this + + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false } } - 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 - } + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) - 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 - } - } + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue } - // Version has a -pre, but it's not one of the ones we like. - return false - } + switch (c) { + case '/': + // completely not allowed, even escaped. + // Should already be path-split by now. + return false - return true -} + case '\\': + clearStateChar() + escaping = true + continue -exports.satisfies = satisfies -function satisfies (version, range, options) { - try { - range = new Range(range, options) - } catch (er) { - return false - } - return range.test(version) -} + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) -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 -} + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } -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 -} + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue -exports.minVersion = minVersion -function minVersion (range, loose) { - range = new Range(range, loose) + case '(': + if (inClass) { + re += '(' + continue + } - var minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } + if (!stateChar) { + re += '\\(' + continue + } - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue - minver = null - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } - 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) - } - }) - } + clearStateChar() + hasMagic = true + var pl = patternListStack.pop() + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(pl) + } + pl.reEnd = re.length + continue - if (minver && range.test(minver)) { - return minver - } + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } - return null -} + clearStateChar() + re += '|' + continue -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 - } -} + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() -// 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) -} + if (inClass) { + re += '\\' + c + continue + } -// 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) -} + inClass = true + classStart = i + reClassStart = re.length + re += c + continue -exports.outside = outside -function outside (version, range, hilo, options) { - version = new SemVer(version, options) - range = new Range(range, options) + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } - 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 ">"') - } + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + if (inClass) { + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } + } - // If it satisifes the range it is not outside - if (satisfies(version, range, options)) { - return false - } + // finish up the class. + hasMagic = true + inClass = false + re += c + continue - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. + default: + // swallow any state char that wasn't consumed + clearStateChar() - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } - var high = null - var low = null + re += c - 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 + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' }) - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } + this.debug('tail=%j\n %s', tail, tail, pl, re) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type - // 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 - } + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail } - return true -} - -exports.prerelease = prerelease -function prerelease (version, options) { - var parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null -} -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) { - if (version instanceof SemVer) { - return version + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' } - if (typeof version !== 'string') { - return null + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '.': + case '[': + case '(': addPatternStart = true } - var match = version.match(re[COERCE]) + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n] - if (match == null) { - return null + var nlBefore = re.slice(0, nl.reStart) + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + var nlAfter = re.slice(nl.reEnd) + + nlLast += nlAfter + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1 + var cleanAfter = nlAfter + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter + + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe } - return parse(match[1] + - '.' + (match[2] || '0') + - '.' + (match[3] || '0')) -} + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re + } + if (addPatternStart) { + re = patternStart + re + } -/***/ }), -/* 524 */ -/***/ (function(module, exports, __webpack_require__) { + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } -var parse = __webpack_require__(525); -var correct = __webpack_require__(527); + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } -var genericWarning = ( - 'license should be ' + - 'a valid SPDX license expression (without "LicenseRef"), ' + - '"UNLICENSED", or ' + - '"SEE LICENSE IN "' -); + var flags = options.nocase ? 'i' : '' + try { + var regExp = new RegExp('^' + re + '$', flags) + } catch (er) { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } -var fileReferenceRE = /^SEE LICEN[CS]E IN (.+)$/; + regExp._glob = pattern + regExp._src = re -function startsWith(prefix, string) { - return string.slice(0, prefix.length) === prefix; + return regExp } -function usesLicenseRef(ast) { - if (ast.hasOwnProperty('license')) { - var license = ast.license; - return ( - startsWith('LicenseRef', license) || - startsWith('DocumentRef', license) - ); - } else { - return ( - usesLicenseRef(ast.left) || - usesLicenseRef(ast.right) - ); - } +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() } -module.exports = function(argument) { - var ast; +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp - try { - ast = parse(argument); - } catch (e) { - var match - if ( - argument === 'UNLICENSED' || - argument === 'UNLICENCED' - ) { - return { - validForOldPackages: true, - validForNewPackages: true, - unlicensed: true - }; - } else if (match = fileReferenceRE.exec(argument)) { - return { - validForOldPackages: true, - validForNewPackages: true, - inFile: match[1] - }; - } else { - var result = { - validForOldPackages: false, - validForNewPackages: false, - warnings: [genericWarning] - }; - var corrected = correct(argument); - if (corrected) { - result.warnings.push( - 'license is similar to the valid expression "' + corrected + '"' - ); - } - return result; - } - } + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set - if (usesLicenseRef(ast)) { - return { - validForNewPackages: false, - validForOldPackages: false, - spdx: true, - warnings: [genericWarning] - }; - } else { - return { - validForNewPackages: true, - validForOldPackages: true, - spdx: true - }; + if (!set.length) { + this.regexp = false + return this.regexp } -}; + var options = this.options + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' -/***/ }), -/* 525 */ -/***/ (function(module, exports, __webpack_require__) { + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') -var parser = __webpack_require__(526).parser + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' -module.exports = function (argument) { - return parser.parse(argument) + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' + + try { + this.regexp = new RegExp(re, flags) + } catch (ex) { + this.regexp = false + } + return this.regexp } +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} -/***/ }), -/* 526 */ -/***/ (function(module, exports, __webpack_require__) { +Minimatch.prototype.match = match +function match (f, partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' -/* WEBPACK VAR INJECTION */(function(module) {/* parser generated by jison 0.4.17 */ -/* - Returns a Parser object of the following structure: + if (f === '/' && partial) return true - Parser: { - yy: {} + var options = this.options + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') } - Parser.prototype: { - yy: {}, - trace: function(), - symbols_: {associative list: name ==> number}, - terminals_: {associative list: number ==> name}, - productions_: [...], - performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$), - table: [...], - defaultActions: {...}, - parseError: function(str, hash), - parse: function(input), + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) - lexer: { - EOF: 1, - parseError: function(str, hash), - setInput: function(input), - input: function(), - unput: function(str), - more: function(), - less: function(n), - pastInput: function(), - upcomingInput: function(), - showPosition: function(), - test_match: function(regex_match_array, rule_index), - next: function(), - lex: function(), - begin: function(condition), - popState: function(), - _currentRules: function(), - topState: function(), - pushState: function(condition), + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. - options: { - ranges: boolean (optional: true ==> token location info will include a .range[] member) - flex: boolean (optional: true ==> flex-like lexing behaviour where the rules are tested exhaustively to find the longest match) - backtrack_lexer: boolean (optional: true ==> lexer regexes are tested in order and for each matching regex the action code is invoked; the lexer terminates the scan when a token is returned by the action code) - }, + var set = this.set + this.debug(this.pattern, 'set', set) - performAction: function(yy, yy_, $avoiding_name_collisions, YY_START), - rules: [...], - conditions: {associative list: name ==> set}, + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate } } + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} - token location info (@$, _$, etc.): { - first_line: n, - last_line: n, - first_column: n, - last_column: n, - range: [start_number, end_number] (where the numbers are indexes into the input string, regular zero-based) - } +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) - the parseError function receives a 'hash' object with these members for lexer and parser errors: { - text: (matched text) - token: (the produced terminal token, if any) - line: (yylineno) - } - while parser (grammar) errors will also provide these members, i.e. parser errors deliver a superset of attributes: { - loc: (yylloc) - expected: (string describing the set of expected tokens) - recoverable: (boolean: TRUE when the parser has a error recovery rule available for this particular error) - } -*/ -var spdxparse = (function(){ -var o=function(k,v,o,l){for(o=o||{},l=k.length;l--;o[k[l]]=v);return o},$V0=[1,5],$V1=[1,6],$V2=[1,7],$V3=[1,4],$V4=[1,9],$V5=[1,10],$V6=[5,14,15,17],$V7=[5,12,14,15,17]; -var parser = {trace: function trace() { }, -yy: {}, -symbols_: {"error":2,"start":3,"expression":4,"EOS":5,"simpleExpression":6,"LICENSE":7,"PLUS":8,"LICENSEREF":9,"DOCUMENTREF":10,"COLON":11,"WITH":12,"EXCEPTION":13,"AND":14,"OR":15,"OPEN":16,"CLOSE":17,"$accept":0,"$end":1}, -terminals_: {2:"error",5:"EOS",7:"LICENSE",8:"PLUS",9:"LICENSEREF",10:"DOCUMENTREF",11:"COLON",12:"WITH",13:"EXCEPTION",14:"AND",15:"OR",16:"OPEN",17:"CLOSE"}, -productions_: [0,[3,2],[6,1],[6,2],[6,1],[6,3],[4,1],[4,3],[4,3],[4,3],[4,3]], -performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate /* action[1] */, $$ /* vstack */, _$ /* lstack */) { -/* this == yyval */ + this.debug('matchOne', file.length, pattern.length) -var $0 = $$.length - 1; -switch (yystate) { -case 1: -return this.$ = $$[$0-1] -break; -case 2: case 4: case 5: -this.$ = {license: yytext} -break; -case 3: -this.$ = {license: $$[$0-1], plus: true} -break; -case 6: -this.$ = $$[$0] -break; -case 7: -this.$ = {exception: $$[$0]} -this.$.license = $$[$0-2].license -if ($$[$0-2].hasOwnProperty('plus')) { - this.$.plus = $$[$0-2].plus -} -break; -case 8: -this.$ = {conjunction: 'and', left: $$[$0-2], right: $$[$0]} -break; -case 9: -this.$ = {conjunction: 'or', left: $$[$0-2], right: $$[$0]} -break; -case 10: -this.$ = $$[$0-1] -break; -} -}, -table: [{3:1,4:2,6:3,7:$V0,9:$V1,10:$V2,16:$V3},{1:[3]},{5:[1,8],14:$V4,15:$V5},o($V6,[2,6],{12:[1,11]}),{4:12,6:3,7:$V0,9:$V1,10:$V2,16:$V3},o($V7,[2,2],{8:[1,13]}),o($V7,[2,4]),{11:[1,14]},{1:[2,1]},{4:15,6:3,7:$V0,9:$V1,10:$V2,16:$V3},{4:16,6:3,7:$V0,9:$V1,10:$V2,16:$V3},{13:[1,17]},{14:$V4,15:$V5,17:[1,18]},o($V7,[2,3]),{9:[1,19]},o($V6,[2,8]),o([5,15,17],[2,9],{14:$V4}),o($V6,[2,7]),o($V6,[2,10]),o($V7,[2,5])], -defaultActions: {8:[2,1]}, -parseError: function parseError(str, hash) { - if (hash.recoverable) { - this.trace(str); - } else { - function _parseError (msg, hash) { - this.message = msg; - this.hash = hash; - } - _parseError.prototype = Error; + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] - throw new _parseError(str, hash); - } -}, -parse: function parse(input) { - var self = this, stack = [0], tstack = [], vstack = [null], lstack = [], table = this.table, yytext = '', yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1; - var args = lstack.slice.call(arguments, 1); - var lexer = Object.create(this.lexer); - var sharedState = { yy: {} }; - for (var k in this.yy) { - if (Object.prototype.hasOwnProperty.call(this.yy, k)) { - sharedState.yy[k] = this.yy[k]; + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false } - } - lexer.setInput(input, sharedState.yy); - sharedState.yy.lexer = lexer; - sharedState.yy.parser = this; - if (typeof lexer.yylloc == 'undefined') { - lexer.yylloc = {}; - } - var yyloc = lexer.yylloc; - lstack.push(yyloc); - var ranges = lexer.options && lexer.options.ranges; - if (typeof sharedState.yy.parseError === 'function') { - this.parseError = sharedState.yy.parseError; - } else { - this.parseError = Object.getPrototypeOf(this).parseError; - } - function popStack(n) { - stack.length = stack.length - 2 * n; - vstack.length = vstack.length - n; - lstack.length = lstack.length - n; - } - _token_stack: - var lex = function () { - var token; - token = lexer.lex() || EOF; - if (typeof token !== 'number') { - token = self.symbols_[token] || token; - } - return token; - }; - var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected; - while (true) { - state = stack[stack.length - 1]; - if (this.defaultActions[state]) { - action = this.defaultActions[state]; + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true } else { - if (symbol === null || typeof symbol == 'undefined') { - symbol = lex(); - } - action = table[state] && table[state][symbol]; - } - if (typeof action === 'undefined' || !action.length || !action[0]) { - var errStr = ''; - expected = []; - for (p in table[state]) { - if (this.terminals_[p] && p > TERROR) { - expected.push('\'' + this.terminals_[p] + '\''); - } - } - if (lexer.showPosition) { - errStr = 'Parse error on line ' + (yylineno + 1) + ':\n' + lexer.showPosition() + '\nExpecting ' + expected.join(', ') + ', got \'' + (this.terminals_[symbol] || symbol) + '\''; - } else { - errStr = 'Parse error on line ' + (yylineno + 1) + ': Unexpected ' + (symbol == EOF ? 'end of input' : '\'' + (this.terminals_[symbol] || symbol) + '\''); - } - this.parseError(errStr, { - text: lexer.match, - token: this.terminals_[symbol] || symbol, - line: lexer.yylineno, - loc: yyloc, - expected: expected - }); - } - if (action[0] instanceof Array && action.length > 1) { - throw new Error('Parse Error: multiple actions possible at state: ' + state + ', token: ' + symbol); - } - switch (action[0]) { - case 1: - stack.push(symbol); - vstack.push(lexer.yytext); - lstack.push(lexer.yylloc); - stack.push(action[1]); - symbol = null; - if (!preErrorSymbol) { - yyleng = lexer.yyleng; - yytext = lexer.yytext; - yylineno = lexer.yylineno; - yyloc = lexer.yylloc; - if (recovering > 0) { - recovering--; - } - } else { - symbol = preErrorSymbol; - preErrorSymbol = null; - } - break; - case 2: - len = this.productions_[action[1]][1]; - yyval.$ = vstack[vstack.length - len]; - yyval._$ = { - first_line: lstack[lstack.length - (len || 1)].first_line, - last_line: lstack[lstack.length - 1].last_line, - first_column: lstack[lstack.length - (len || 1)].first_column, - last_column: lstack[lstack.length - 1].last_column - }; - if (ranges) { - yyval._$.range = [ - lstack[lstack.length - (len || 1)].range[0], - lstack[lstack.length - 1].range[1] - ]; - } - r = this.performAction.apply(yyval, [ - yytext, - yyleng, - yylineno, - sharedState.yy, - action[1], - vstack, - lstack - ].concat(args)); - if (typeof r !== 'undefined') { - return r; - } - if (len) { - stack = stack.slice(0, -1 * len * 2); - vstack = vstack.slice(0, -1 * len); - lstack = lstack.slice(0, -1 * len); - } - stack.push(this.productions_[action[1]][0]); - vstack.push(yyval.$); - lstack.push(yyval._$); - newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; - stack.push(newState); - break; - case 3: - return true; + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false } - return true; -}}; -/* generated by jison-lex 0.3.4 */ -var lexer = (function(){ -var lexer = ({ -EOF:1, + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase() + } else { + hit = f === p + } + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } -parseError:function parseError(str, hash) { - if (this.yy.parser) { - this.yy.parser.parseError(str, hash); - } else { - throw new Error(str); - } - }, + if (!hit) return false + } -// resets the lexer, sets new input -setInput:function (input, yy) { - this.yy = yy || this.yy || {}; - this._input = input; - this._more = this._backtrack = this.done = false; - this.yylineno = this.yyleng = 0; - this.yytext = this.matched = this.match = ''; - this.conditionStack = ['INITIAL']; - this.yylloc = { - first_line: 1, - first_column: 0, - last_line: 1, - last_column: 0 - }; - if (this.options.ranges) { - this.yylloc.range = [0,0]; - } - this.offset = 0; - return this; - }, + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* -// consumes and returns one char from the input -input:function () { - var ch = this._input[0]; - this.yytext += ch; - this.yyleng++; - this.offset++; - this.match += ch; - this.matched += ch; - var lines = ch.match(/(?:\r\n?|\n).*/g); - if (lines) { - this.yylineno++; - this.yylloc.last_line++; - } else { - this.yylloc.last_column++; - } - if (this.options.ranges) { - this.yylloc.range[1]++; - } + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') + return emptyFileEnd + } - this._input = this._input.slice(1); - return ch; - }, + // should be unreachable. + throw new Error('wtf?') +} -// unshifts one char (or a string) into the input -unput:function (ch) { - var len = ch.length; - var lines = ch.split(/(?:\r\n?|\n)/g); +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} - this._input = ch + this._input; - this.yytext = this.yytext.substr(0, this.yytext.length - len); - //this.yyleng -= len; - this.offset -= len; - var oldLines = this.match.split(/(?:\r\n?|\n)/g); - this.match = this.match.substr(0, this.match.length - 1); - this.matched = this.matched.substr(0, this.matched.length - 1); +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} - if (lines.length - 1) { - this.yylineno -= lines.length - 1; - } - var r = this.yylloc.range; - this.yylloc = { - first_line: this.yylloc.first_line, - last_line: this.yylineno + 1, - first_column: this.yylloc.first_column, - last_column: lines ? - (lines.length === oldLines.length ? this.yylloc.first_column : 0) - + oldLines[oldLines.length - lines.length].length - lines[0].length : - this.yylloc.first_column - len - }; +/***/ }), +/* 507 */ +/***/ (function(module, exports, __webpack_require__) { - if (this.options.ranges) { - this.yylloc.range = [r[0], r[0] + this.yyleng - len]; - } - this.yyleng = this.yytext.length; - return this; - }, +var concatMap = __webpack_require__(508); +var balanced = __webpack_require__(509); -// When called from action, caches matched text and appends it on next action -more:function () { - this._more = true; - return this; - }, +module.exports = expandTop; -// When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead. -reject:function () { - if (this.options.backtrack_lexer) { - this._backtrack = true; - } else { - return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n' + this.showPosition(), { - text: "", - token: null, - line: this.yylineno - }); +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; - } - return this; - }, +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} -// retain first n characters of the match -less:function (n) { - this.unput(this.match.slice(n)); - }, +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} -// displays already matched input, i.e. for error messages -pastInput:function () { - var past = this.matched.substr(0, this.matched.length - this.match.length); - return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, ""); - }, +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} -// displays upcoming input, i.e. for error messages -upcomingInput:function () { - var next = this.match; - if (next.length < 20) { - next += this._input.substr(0, 20-next.length); - } - return (next.substr(0,20) + (next.length > 20 ? '...' : '')).replace(/\n/g, ""); - }, -// displays the character position where the lexing error occurred, i.e. for error messages -showPosition:function () { - var pre = this.pastInput(); - var c = new Array(pre.length + 1).join("-"); - return pre + this.upcomingInput() + "\n" + c + "^"; - }, +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; -// test the lexed token: return FALSE when not a match, otherwise return token -test_match:function (match, indexed_rule) { - var token, - lines, - backup; + var parts = []; + var m = balanced('{', '}', str); - if (this.options.backtrack_lexer) { - // save context - backup = { - yylineno: this.yylineno, - yylloc: { - first_line: this.yylloc.first_line, - last_line: this.last_line, - first_column: this.yylloc.first_column, - last_column: this.yylloc.last_column - }, - yytext: this.yytext, - match: this.match, - matches: this.matches, - matched: this.matched, - yyleng: this.yyleng, - offset: this.offset, - _more: this._more, - _input: this._input, - yy: this.yy, - conditionStack: this.conditionStack.slice(0), - done: this.done - }; - if (this.options.ranges) { - backup.yylloc.range = this.yylloc.range.slice(0); - } - } + if (!m) + return str.split(','); - lines = match[0].match(/(?:\r\n?|\n).*/g); - if (lines) { - this.yylineno += lines.length; - } - this.yylloc = { - first_line: this.yylloc.last_line, - last_line: this.yylineno + 1, - first_column: this.yylloc.last_column, - last_column: lines ? - lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : - this.yylloc.last_column + match[0].length - }; - this.yytext += match[0]; - this.match += match[0]; - this.matches = match; - this.yyleng = this.yytext.length; - if (this.options.ranges) { - this.yylloc.range = [this.offset, this.offset += this.yyleng]; - } - this._more = false; - this._backtrack = false; - this._input = this._input.slice(match[0].length); - this.matched += match[0]; - token = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]); - if (this.done && this._input) { - this.done = false; - } - if (token) { - return token; - } else if (this._backtrack) { - // recover context - for (var k in backup) { - this[k] = backup[k]; - } - return false; // rule action called reject() implying the next rule should be tested instead. - } - return false; - }, + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); -// return next match in input -next:function () { - if (this.done) { - return this.EOF; - } - if (!this._input) { - this.done = true; - } + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } - var token, - match, - tempMatch, - index; - if (!this._more) { - this.yytext = ''; - this.match = ''; - } - var rules = this._currentRules(); - for (var i = 0; i < rules.length; i++) { - tempMatch = this._input.match(this.rules[rules[i]]); - if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { - match = tempMatch; - index = i; - if (this.options.backtrack_lexer) { - token = this.test_match(tempMatch, rules[i]); - if (token !== false) { - return token; - } else if (this._backtrack) { - match = false; - continue; // rule action called reject() implying a rule MISmatch. - } else { - // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace) - return false; - } - } else if (!this.options.flex) { - break; - } - } - } - if (match) { - token = this.test_match(match, rules[index]); - if (token !== false) { - return token; - } - // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace) - return false; - } - if (this._input === "") { - return this.EOF; - } else { - return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { - text: "", - token: null, - line: this.yylineno - }); - } - }, + parts.push.apply(parts, p); -// return next match that has a token -lex:function lex() { - var r = this.next(); - if (r) { - return r; - } else { - return this.lex(); + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function identity(e) { + return e; +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } } - }, + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } -// activates a new lexer condition state (pushes the new lexer condition state onto the condition stack) -begin:function begin(condition) { - this.conditionStack.push(condition); - }, + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } -// pop the previously active lexer condition state off the condition stack -popState:function popState() { - var n = this.conditionStack.length - 1; - if (n > 0) { - return this.conditionStack.pop(); - } else { - return this.conditionStack[0]; + return expansions; +} + + + +/***/ }), +/* 508 */ +/***/ (function(module, exports) { + +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + + +/***/ }), +/* 509 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + + if (ai >= 0 && bi > 0) { + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; } - }, -// produce the lexer rule set which is active for the currently active lexer condition state -_currentRules:function _currentRules() { - if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) { - return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules; - } else { - return this.conditions["INITIAL"].rules; + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} + + +/***/ }), +/* 510 */ +/***/ (function(module, exports, __webpack_require__) { + +try { + var util = __webpack_require__(397); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __webpack_require__(511); +} + + +/***/ }), +/* 511 */ +/***/ (function(module, exports) { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true } - }, + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} -// return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available -topState:function topState(n) { - n = this.conditionStack.length - 1 - Math.abs(n || 0); - if (n >= 0) { - return this.conditionStack[n]; - } else { - return "INITIAL"; + +/***/ }), +/* 512 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +function posix(path) { + return path.charAt(0) === '/'; +} + +function win32(path) { + // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 + var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; + var result = splitDeviceRe.exec(path); + var device = result[1] || ''; + var isUnc = Boolean(device && device.charAt(1) !== ':'); + + // UNC paths are always absolute + return Boolean(result[2] || isUnc); +} + +module.exports = process.platform === 'win32' ? win32 : posix; +module.exports.posix = posix; +module.exports.win32 = win32; + + +/***/ }), +/* 513 */ +/***/ (function(module, exports, __webpack_require__) { + +module.exports = globSync +globSync.GlobSync = GlobSync + +var fs = __webpack_require__(349) +var rp = __webpack_require__(504) +var minimatch = __webpack_require__(506) +var Minimatch = minimatch.Minimatch +var Glob = __webpack_require__(503).Glob +var util = __webpack_require__(397) +var path = __webpack_require__(4) +var assert = __webpack_require__(371) +var isAbsolute = __webpack_require__(512) +var common = __webpack_require__(514) +var alphasort = common.alphasort +var alphasorti = common.alphasorti +var setopts = common.setopts +var ownProp = common.ownProp +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored + +function globSync (pattern, options) { + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + return new GlobSync(pattern, options).found +} + +function GlobSync (pattern, options) { + if (!pattern) + throw new Error('must provide pattern') + + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + if (!(this instanceof GlobSync)) + return new GlobSync(pattern, options) + + setopts(this, pattern, options) + + if (this.noprocess) + return this + + var n = this.minimatch.set.length + this.matches = new Array(n) + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false) + } + this._finish() +} + +GlobSync.prototype._finish = function () { + assert(this instanceof GlobSync) + if (this.realpath) { + var self = this + this.matches.forEach(function (matchset, index) { + var set = self.matches[index] = Object.create(null) + for (var p in matchset) { + try { + p = self._makeAbs(p) + var real = rp.realpathSync(p, self.realpathCache) + set[real] = true + } catch (er) { + if (er.syscall === 'stat') + set[self._makeAbs(p)] = true + else + throw er } - }, + } + }) + } + common.finish(this) +} -// alias for begin(condition) -pushState:function pushState(condition) { - this.begin(condition); - }, -// return the number of states currently on the stack -stateStackSize:function stateStackSize() { - return this.conditionStack.length; - }, -options: {}, -performAction: function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) { -var YYSTATE=YY_START; -switch($avoiding_name_collisions) { -case 0:return 5 -break; -case 1:/* skip whitespace */ -break; -case 2:return 8 -break; -case 3:return 16 -break; -case 4:return 17 -break; -case 5:return 11 -break; -case 6:return 10 -break; -case 7:return 9 -break; -case 8:return 14 -break; -case 9:return 15 -break; -case 10:return 12 -break; -case 11:return 7 -break; -case 12:return 7 -break; -case 13:return 7 -break; -case 14:return 7 -break; -case 15:return 7 -break; -case 16:return 7 -break; -case 17:return 7 -break; -case 18:return 7 -break; -case 19:return 7 -break; -case 20:return 7 -break; -case 21:return 7 -break; -case 22:return 7 -break; -case 23:return 7 -break; -case 24:return 13 -break; -case 25:return 13 -break; -case 26:return 13 -break; -case 27:return 13 -break; -case 28:return 13 -break; -case 29:return 13 -break; -case 30:return 13 -break; -case 31:return 13 -break; -case 32:return 7 -break; -case 33:return 13 -break; -case 34:return 7 -break; -case 35:return 13 -break; -case 36:return 7 -break; -case 37:return 13 -break; -case 38:return 13 -break; -case 39:return 7 -break; -case 40:return 13 -break; -case 41:return 13 -break; -case 42:return 13 -break; -case 43:return 13 -break; -case 44:return 13 -break; -case 45:return 7 -break; -case 46:return 13 -break; -case 47:return 7 -break; -case 48:return 7 -break; -case 49:return 7 -break; -case 50:return 7 -break; -case 51:return 7 -break; -case 52:return 7 -break; -case 53:return 7 -break; -case 54:return 7 -break; -case 55:return 7 -break; -case 56:return 7 -break; -case 57:return 7 -break; -case 58:return 7 -break; -case 59:return 7 -break; -case 60:return 7 -break; -case 61:return 7 -break; -case 62:return 7 -break; -case 63:return 13 -break; -case 64:return 7 -break; -case 65:return 7 -break; -case 66:return 13 -break; -case 67:return 7 -break; -case 68:return 7 -break; -case 69:return 7 -break; -case 70:return 7 -break; -case 71:return 7 -break; -case 72:return 7 -break; -case 73:return 13 -break; -case 74:return 7 -break; -case 75:return 13 -break; -case 76:return 7 -break; -case 77:return 7 -break; -case 78:return 7 -break; -case 79:return 7 -break; -case 80:return 7 -break; -case 81:return 7 -break; -case 82:return 7 -break; -case 83:return 7 -break; -case 84:return 7 -break; -case 85:return 7 -break; -case 86:return 7 -break; -case 87:return 7 -break; -case 88:return 7 -break; -case 89:return 7 -break; -case 90:return 7 -break; -case 91:return 7 -break; -case 92:return 7 -break; -case 93:return 7 -break; -case 94:return 7 -break; -case 95:return 7 -break; -case 96:return 7 -break; -case 97:return 7 -break; -case 98:return 7 -break; -case 99:return 7 -break; -case 100:return 7 -break; -case 101:return 7 -break; -case 102:return 7 -break; -case 103:return 7 -break; -case 104:return 7 -break; -case 105:return 7 -break; -case 106:return 7 -break; -case 107:return 7 -break; -case 108:return 7 -break; -case 109:return 7 -break; -case 110:return 7 -break; -case 111:return 7 -break; -case 112:return 7 -break; -case 113:return 7 -break; -case 114:return 7 -break; -case 115:return 7 -break; -case 116:return 7 -break; -case 117:return 7 -break; -case 118:return 7 -break; -case 119:return 7 -break; -case 120:return 7 -break; -case 121:return 7 -break; -case 122:return 7 -break; -case 123:return 7 -break; -case 124:return 7 -break; -case 125:return 7 -break; -case 126:return 7 -break; -case 127:return 7 -break; -case 128:return 7 -break; -case 129:return 7 -break; -case 130:return 7 -break; -case 131:return 7 -break; -case 132:return 7 -break; -case 133:return 7 -break; -case 134:return 7 -break; -case 135:return 7 -break; -case 136:return 7 -break; -case 137:return 7 -break; -case 138:return 7 -break; -case 139:return 7 -break; -case 140:return 7 -break; -case 141:return 7 -break; -case 142:return 7 -break; -case 143:return 7 -break; -case 144:return 7 -break; -case 145:return 7 -break; -case 146:return 7 -break; -case 147:return 7 -break; -case 148:return 7 -break; -case 149:return 7 -break; -case 150:return 7 -break; -case 151:return 7 -break; -case 152:return 7 -break; -case 153:return 7 -break; -case 154:return 7 -break; -case 155:return 7 -break; -case 156:return 7 -break; -case 157:return 7 -break; -case 158:return 7 -break; -case 159:return 7 -break; -case 160:return 7 -break; -case 161:return 7 -break; -case 162:return 7 -break; -case 163:return 7 -break; -case 164:return 7 -break; -case 165:return 7 -break; -case 166:return 7 -break; -case 167:return 7 -break; -case 168:return 7 -break; -case 169:return 7 -break; -case 170:return 7 -break; -case 171:return 7 -break; -case 172:return 7 -break; -case 173:return 7 -break; -case 174:return 7 -break; -case 175:return 7 -break; -case 176:return 7 -break; -case 177:return 7 -break; -case 178:return 7 -break; -case 179:return 7 -break; -case 180:return 7 -break; -case 181:return 7 -break; -case 182:return 7 -break; -case 183:return 7 -break; -case 184:return 7 -break; -case 185:return 7 -break; -case 186:return 7 -break; -case 187:return 7 -break; -case 188:return 7 -break; -case 189:return 7 -break; -case 190:return 7 -break; -case 191:return 7 -break; -case 192:return 7 -break; -case 193:return 7 -break; -case 194:return 7 -break; -case 195:return 7 -break; -case 196:return 7 -break; -case 197:return 7 -break; -case 198:return 7 -break; -case 199:return 7 -break; -case 200:return 7 -break; -case 201:return 7 -break; -case 202:return 7 -break; -case 203:return 7 -break; -case 204:return 7 -break; -case 205:return 7 -break; -case 206:return 7 -break; -case 207:return 7 -break; -case 208:return 7 -break; -case 209:return 7 -break; -case 210:return 7 -break; -case 211:return 7 -break; -case 212:return 7 -break; -case 213:return 7 -break; -case 214:return 7 -break; -case 215:return 7 -break; -case 216:return 7 -break; -case 217:return 7 -break; -case 218:return 7 -break; -case 219:return 7 -break; -case 220:return 7 -break; -case 221:return 7 -break; -case 222:return 7 -break; -case 223:return 7 -break; -case 224:return 7 -break; -case 225:return 7 -break; -case 226:return 7 -break; -case 227:return 7 -break; -case 228:return 7 -break; -case 229:return 7 -break; -case 230:return 7 -break; -case 231:return 7 -break; -case 232:return 7 -break; -case 233:return 7 -break; -case 234:return 7 -break; -case 235:return 7 -break; -case 236:return 7 -break; -case 237:return 7 -break; -case 238:return 7 -break; -case 239:return 7 -break; -case 240:return 7 -break; -case 241:return 7 -break; -case 242:return 7 -break; -case 243:return 7 -break; -case 244:return 7 -break; -case 245:return 7 -break; -case 246:return 7 -break; -case 247:return 7 -break; -case 248:return 7 -break; -case 249:return 7 -break; -case 250:return 7 -break; -case 251:return 7 -break; -case 252:return 7 -break; -case 253:return 7 -break; -case 254:return 7 -break; -case 255:return 7 -break; -case 256:return 7 -break; -case 257:return 7 -break; -case 258:return 7 -break; -case 259:return 7 -break; -case 260:return 7 -break; -case 261:return 7 -break; -case 262:return 7 -break; -case 263:return 7 -break; -case 264:return 7 -break; -case 265:return 7 -break; -case 266:return 7 -break; -case 267:return 7 -break; -case 268:return 7 -break; -case 269:return 7 -break; -case 270:return 7 -break; -case 271:return 7 -break; -case 272:return 7 -break; -case 273:return 7 -break; -case 274:return 7 -break; -case 275:return 7 -break; -case 276:return 7 -break; -case 277:return 7 -break; -case 278:return 7 -break; -case 279:return 7 -break; -case 280:return 7 -break; -case 281:return 7 -break; -case 282:return 7 -break; -case 283:return 7 -break; -case 284:return 7 -break; -case 285:return 7 -break; -case 286:return 7 -break; -case 287:return 7 -break; -case 288:return 7 -break; -case 289:return 7 -break; -case 290:return 7 -break; -case 291:return 7 -break; -case 292:return 7 -break; -case 293:return 7 -break; -case 294:return 7 -break; -case 295:return 7 -break; -case 296:return 7 -break; -case 297:return 7 -break; -case 298:return 7 -break; -case 299:return 7 -break; -case 300:return 7 -break; -case 301:return 7 -break; -case 302:return 7 -break; -case 303:return 7 -break; -case 304:return 7 -break; -case 305:return 7 -break; -case 306:return 7 -break; -case 307:return 7 -break; -case 308:return 7 -break; -case 309:return 7 -break; -case 310:return 7 -break; -case 311:return 7 -break; -case 312:return 7 -break; -case 313:return 7 -break; -case 314:return 7 -break; -case 315:return 7 -break; -case 316:return 7 -break; -case 317:return 7 -break; -case 318:return 7 -break; -case 319:return 7 -break; -case 320:return 7 -break; -case 321:return 7 -break; -case 322:return 7 -break; -case 323:return 7 -break; -case 324:return 7 -break; -case 325:return 7 -break; -case 326:return 7 -break; -case 327:return 7 -break; -case 328:return 7 -break; -case 329:return 7 -break; -case 330:return 7 -break; -case 331:return 7 -break; -case 332:return 7 -break; -case 333:return 7 -break; -case 334:return 7 -break; -case 335:return 7 -break; -case 336:return 7 -break; -case 337:return 7 -break; -case 338:return 7 -break; -case 339:return 7 -break; -case 340:return 7 -break; -case 341:return 7 -break; -case 342:return 7 -break; -case 343:return 7 -break; -case 344:return 7 -break; -case 345:return 7 -break; -case 346:return 7 -break; -case 347:return 7 -break; -case 348:return 7 -break; -case 349:return 7 -break; -case 350:return 7 -break; -case 351:return 7 -break; -case 352:return 7 -break; -case 353:return 7 -break; -case 354:return 7 -break; -case 355:return 7 -break; -case 356:return 7 -break; -case 357:return 7 -break; -case 358:return 7 -break; -case 359:return 7 -break; -case 360:return 7 -break; -case 361:return 7 -break; -case 362:return 7 -break; -case 363:return 7 -break; -case 364:return 7 -break; +GlobSync.prototype._process = function (pattern, index, inGlobStar) { + assert(this instanceof GlobSync) + + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. + + // See if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index) + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } + + var remain = pattern.slice(n) + + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix + + var abs = this._makeAbs(read) + + //if ignored, skip processing + if (childrenIgnored(this, read)) + return + + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar) +} + + +GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar) + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } + + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix.slice(-1) !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) + newPattern = [prefix, e] + else + newPattern = [e] + this._process(newPattern.concat(remain), index, inGlobStar) + } +} + + +GlobSync.prototype._emitMatch = function (index, e) { + if (isIgnored(this, e)) + return + + var abs = this._makeAbs(e) + + if (this.mark) + e = this._mark(e) + + if (this.absolute) { + e = abs + } + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true + + if (this.stat) + this._stat(e) +} + + +GlobSync.prototype._readdirInGlobStar = function (abs) { + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false) + + var entries + var lstat + var stat + try { + lstat = fs.lstatSync(abs) + } catch (er) { + if (er.code === 'ENOENT') { + // lstat failed, doesn't exist + return null + } + } + + var isSym = lstat && lstat.isSymbolicLink() + this.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) + this.cache[abs] = 'FILE' + else + entries = this._readdir(abs, false) + + return entries +} + +GlobSync.prototype._readdir = function (abs, inGlobStar) { + var entries + + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return null + + if (Array.isArray(c)) + return c + } + + try { + return this._readdirEntries(abs, fs.readdirSync(abs)) + } catch (er) { + this._readdirError(abs, er) + return null + } +} + +GlobSync.prototype._readdirEntries = function (abs, entries) { + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } + + this.cache[abs] = entries + + // mark and cache dir-ness + return entries +} + +GlobSync.prototype._readdirError = function (f, er) { + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + throw error + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) + throw er + if (!this.silent) + console.error('glob error', er) + break + } +} + +GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { + + var entries = this._readdir(abs, inGlobStar) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false) + + var len = entries.length + var isSym = this.symlinks[abs] + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return + + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true) + + var below = gspref.concat(entries[i], remain) + this._process(below, index, true) + } +} + +GlobSync.prototype._processSimple = function (prefix, index) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var exists = this._stat(prefix) + + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this._emitMatch(index, prefix) +} + +// Returns either 'DIR', 'FILE', or false +GlobSync.prototype._stat = function (f) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' + + if (f.length > this.maxLength) + return false + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] + + if (Array.isArray(c)) + c = 'DIR' + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return c + + if (needDir && c === 'FILE') + return false + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + + var exists + var stat = this.statCache[abs] + if (!stat) { + var lstat + try { + lstat = fs.lstatSync(abs) + } catch (er) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return false + } + } + + if (lstat && lstat.isSymbolicLink()) { + try { + stat = fs.statSync(abs) + } catch (er) { + stat = lstat + } + } else { + stat = lstat + } + } + + this.statCache[abs] = stat + + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + + this.cache[abs] = this.cache[abs] || c + + if (needDir && c === 'FILE') + return false + + return c +} + +GlobSync.prototype._mark = function (p) { + return common.mark(this, p) +} + +GlobSync.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} + + +/***/ }), +/* 514 */ +/***/ (function(module, exports, __webpack_require__) { + +exports.alphasort = alphasort +exports.alphasorti = alphasorti +exports.setopts = setopts +exports.ownProp = ownProp +exports.makeAbs = makeAbs +exports.finish = finish +exports.mark = mark +exports.isIgnored = isIgnored +exports.childrenIgnored = childrenIgnored + +function ownProp (obj, field) { + return Object.prototype.hasOwnProperty.call(obj, field) +} + +var path = __webpack_require__(4) +var minimatch = __webpack_require__(506) +var isAbsolute = __webpack_require__(512) +var Minimatch = minimatch.Minimatch + +function alphasorti (a, b) { + return a.toLowerCase().localeCompare(b.toLowerCase()) +} + +function alphasort (a, b) { + return a.localeCompare(b) +} + +function setupIgnores (self, options) { + self.ignore = options.ignore || [] + + if (!Array.isArray(self.ignore)) + self.ignore = [self.ignore] + + if (self.ignore.length) { + self.ignore = self.ignore.map(ignoreMap) + } +} + +// ignore patterns are always in dot:true mode. +function ignoreMap (pattern) { + var gmatcher = null + if (pattern.slice(-3) === '/**') { + var gpattern = pattern.replace(/(\/\*\*)+$/, '') + gmatcher = new Minimatch(gpattern, { dot: true }) + } + + return { + matcher: new Minimatch(pattern, { dot: true }), + gmatcher: gmatcher + } +} + +function setopts (self, pattern, options) { + if (!options) + options = {} + + // base-matching: just use globstar for that. + if (options.matchBase && -1 === pattern.indexOf("/")) { + if (options.noglobstar) { + throw new Error("base matching requires globstar") + } + pattern = "**/" + pattern + } + + self.silent = !!options.silent + self.pattern = pattern + self.strict = options.strict !== false + self.realpath = !!options.realpath + self.realpathCache = options.realpathCache || Object.create(null) + self.follow = !!options.follow + self.dot = !!options.dot + self.mark = !!options.mark + self.nodir = !!options.nodir + if (self.nodir) + self.mark = true + self.sync = !!options.sync + self.nounique = !!options.nounique + self.nonull = !!options.nonull + self.nosort = !!options.nosort + self.nocase = !!options.nocase + self.stat = !!options.stat + self.noprocess = !!options.noprocess + self.absolute = !!options.absolute + + self.maxLength = options.maxLength || Infinity + self.cache = options.cache || Object.create(null) + self.statCache = options.statCache || Object.create(null) + self.symlinks = options.symlinks || Object.create(null) + + setupIgnores(self, options) + + self.changedCwd = false + var cwd = process.cwd() + if (!ownProp(options, "cwd")) + self.cwd = cwd + else { + self.cwd = path.resolve(options.cwd) + self.changedCwd = self.cwd !== cwd + } + + self.root = options.root || path.resolve(self.cwd, "/") + self.root = path.resolve(self.root) + if (process.platform === "win32") + self.root = self.root.replace(/\\/g, "/") + + // TODO: is an absolute `cwd` supposed to be resolved against `root`? + // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') + self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) + if (process.platform === "win32") + self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") + self.nomount = !!options.nomount + + // disable comments and negation in Minimatch. + // Note that they are not supported in Glob itself anyway. + options.nonegate = true + options.nocomment = true + + self.minimatch = new Minimatch(pattern, options) + self.options = self.minimatch.options +} + +function finish (self) { + var nou = self.nounique + var all = nou ? [] : Object.create(null) + + for (var i = 0, l = self.matches.length; i < l; i ++) { + var matches = self.matches[i] + if (!matches || Object.keys(matches).length === 0) { + if (self.nonull) { + // do like the shell, and spit out the literal glob + var literal = self.minimatch.globSet[i] + if (nou) + all.push(literal) + else + all[literal] = true + } + } else { + // had matches + var m = Object.keys(matches) + if (nou) + all.push.apply(all, m) + else + m.forEach(function (m) { + all[m] = true + }) + } + } + + if (!nou) + all = Object.keys(all) + + if (!self.nosort) + all = all.sort(self.nocase ? alphasorti : alphasort) + + // at *some* point we statted all of these + if (self.mark) { + for (var i = 0; i < all.length; i++) { + all[i] = self._mark(all[i]) + } + if (self.nodir) { + all = all.filter(function (e) { + var notDir = !(/\/$/.test(e)) + var c = self.cache[e] || self.cache[makeAbs(self, e)] + if (notDir && c) + notDir = c !== 'DIR' && !Array.isArray(c) + return notDir + }) + } + } + + if (self.ignore.length) + all = all.filter(function(m) { + return !isIgnored(self, m) + }) + + self.found = all +} + +function mark (self, p) { + var abs = makeAbs(self, p) + var c = self.cache[abs] + var m = p + if (c) { + var isDir = c === 'DIR' || Array.isArray(c) + var slash = p.slice(-1) === '/' + + if (isDir && !slash) + m += '/' + else if (!isDir && slash) + m = m.slice(0, -1) + + if (m !== p) { + var mabs = makeAbs(self, m) + self.statCache[mabs] = self.statCache[abs] + self.cache[mabs] = self.cache[abs] + } + } + + return m +} + +// lotta situps... +function makeAbs (self, f) { + var abs = f + if (f.charAt(0) === '/') { + abs = path.join(self.root, f) + } else if (isAbsolute(f) || f === '') { + abs = f + } else if (self.changedCwd) { + abs = path.resolve(self.cwd, f) + } else { + abs = path.resolve(f) + } + + if (process.platform === 'win32') + abs = abs.replace(/\\/g, '/') + + return abs +} + + +// Return true, if pattern ends with globstar '**', for the accompanying parent directory. +// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents +function isIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + +function childrenIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + + +/***/ }), +/* 515 */ +/***/ (function(module, exports, __webpack_require__) { + +var wrappy = __webpack_require__(379) +var reqs = Object.create(null) +var once = __webpack_require__(378) + +module.exports = wrappy(inflight) + +function inflight (key, cb) { + if (reqs[key]) { + reqs[key].push(cb) + return null + } else { + reqs[key] = [cb] + return makeres(key) + } +} + +function makeres (key) { + return once(function RES () { + var cbs = reqs[key] + var len = cbs.length + var args = slice(arguments) + + // XXX It's somewhat ambiguous whether a new callback added in this + // pass should be queued for later execution if something in the + // list of callbacks throws, or if it should just be discarded. + // However, it's such an edge case that it hardly matters, and either + // choice is likely as surprising as the other. + // As it happens, we do go ahead and schedule it for later execution. + try { + for (var i = 0; i < len; i++) { + cbs[i].apply(null, args) + } + } finally { + if (cbs.length > len) { + // added more in the interim. + // de-zalgo, just in case, but don't call again. + cbs.splice(0, len) + process.nextTick(function () { + RES.apply(null, args) + }) + } else { + delete reqs[key] + } + } + }) +} + +function slice (args) { + var length = args.length + var array = [] + + for (var i = 0; i < length; i++) array[i] = args[i] + return array +} + + +/***/ }), +/* 516 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CliError", function() { return CliError; }); +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +class CliError extends Error { + constructor(message, meta = {}) { + super(message); + this.meta = meta; + } + +} + +/***/ }), +/* 517 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Project", function() { return Project; }); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(349); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__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 util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(397); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(516); +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(500); +/* harmony import */ var _package_json__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(518); +/* harmony import */ var _scripts__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(563); +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { 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; } + +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + + + + + + +class Project { + static async fromPath(path) { + const pkgJson = await Object(_package_json__WEBPACK_IMPORTED_MODULE_5__["readPackageJson"])(path); + return new Project(pkgJson, path); + } + /** parsed package.json */ + + + constructor(packageJson, projectPath) { + _defineProperty(this, "json", void 0); + + _defineProperty(this, "packageJsonLocation", void 0); + + _defineProperty(this, "nodeModulesLocation", void 0); + + _defineProperty(this, "targetLocation", void 0); + + _defineProperty(this, "path", void 0); + + _defineProperty(this, "version", void 0); + + _defineProperty(this, "allDependencies", void 0); + + _defineProperty(this, "productionDependencies", void 0); + + _defineProperty(this, "devDependencies", void 0); + + _defineProperty(this, "scripts", void 0); + + _defineProperty(this, "isWorkspaceRoot", false); + + _defineProperty(this, "isWorkspaceProject", false); + + this.json = Object.freeze(packageJson); + this.path = projectPath; + this.packageJsonLocation = path__WEBPACK_IMPORTED_MODULE_1___default.a.resolve(this.path, 'package.json'); + this.nodeModulesLocation = path__WEBPACK_IMPORTED_MODULE_1___default.a.resolve(this.path, 'node_modules'); + this.targetLocation = path__WEBPACK_IMPORTED_MODULE_1___default.a.resolve(this.path, 'target'); + this.version = this.json.version; + this.productionDependencies = this.json.dependencies || {}; + this.devDependencies = this.json.devDependencies || {}; + this.allDependencies = _objectSpread({}, this.devDependencies, {}, this.productionDependencies); + this.isWorkspaceRoot = this.json.hasOwnProperty('workspaces'); + this.scripts = this.json.scripts || {}; + } + + get name() { + return this.json.name; + } + + ensureValidProjectDependency(project, dependentProjectIsInWorkspace) { + const versionInPackageJson = this.allDependencies[project.name]; + let expectedVersionInPackageJson; + + if (dependentProjectIsInWorkspace) { + expectedVersionInPackageJson = project.json.version; + } else { + const relativePathToProject = normalizePath(path__WEBPACK_IMPORTED_MODULE_1___default.a.relative(this.path, project.path)); + expectedVersionInPackageJson = `link:${relativePathToProject}`; + } // No issues! + + + if (versionInPackageJson === expectedVersionInPackageJson) { + return; + } + + let problemMsg; + + if (Object(_package_json__WEBPACK_IMPORTED_MODULE_5__["isLinkDependency"])(versionInPackageJson) && dependentProjectIsInWorkspace) { + problemMsg = `but should be using a workspace`; + } else if (Object(_package_json__WEBPACK_IMPORTED_MODULE_5__["isLinkDependency"])(versionInPackageJson)) { + problemMsg = `using 'link:', but the path is wrong`; + } else { + problemMsg = `but it's not using the local package`; + } + + throw new _errors__WEBPACK_IMPORTED_MODULE_3__["CliError"](`[${this.name}] depends on [${project.name}] ${problemMsg}. Update its package.json to the expected value below.`, { + actual: `"${project.name}": "${versionInPackageJson}"`, + expected: `"${project.name}": "${expectedVersionInPackageJson}"`, + package: `${this.name} (${this.packageJsonLocation})` + }); + } + + getBuildConfig() { + return this.json.kibana && this.json.kibana.build || {}; + } + /** + * Returns the directory that should be copied into the Kibana build artifact. + * This config can be specified to only include the project's build artifacts + * instead of everything located in the project directory. + */ + + + getIntermediateBuildDirectory() { + return path__WEBPACK_IMPORTED_MODULE_1___default.a.resolve(this.path, this.getBuildConfig().intermediateBuildDirectory || '.'); + } + + getCleanConfig() { + return this.json.kibana && this.json.kibana.clean || {}; + } + + hasScript(name) { + return name in this.scripts; + } + + getExecutables() { + const raw = this.json.bin; + + if (!raw) { + return {}; + } + + if (typeof raw === 'string') { + return { + [this.name]: path__WEBPACK_IMPORTED_MODULE_1___default.a.resolve(this.path, raw) + }; + } + + if (typeof raw === 'object') { + const binsConfig = {}; + + for (const binName of Object.keys(raw)) { + binsConfig[binName] = path__WEBPACK_IMPORTED_MODULE_1___default.a.resolve(this.path, raw[binName]); + } + + return binsConfig; + } + + throw new _errors__WEBPACK_IMPORTED_MODULE_3__["CliError"](`[${this.name}] has an invalid "bin" field in its package.json, ` + `expected an object or a string`, { + binConfig: Object(util__WEBPACK_IMPORTED_MODULE_2__["inspect"])(raw), + package: `${this.name} (${this.packageJsonLocation})` + }); + } + + async runScript(scriptName, args = []) { + _log__WEBPACK_IMPORTED_MODULE_4__["log"].info(`Running script [${scriptName}] in [${this.name}]:`); + return Object(_scripts__WEBPACK_IMPORTED_MODULE_6__["runScriptInPackage"])(scriptName, args, this); + } + + runScriptStreaming(scriptName, options = {}) { + return Object(_scripts__WEBPACK_IMPORTED_MODULE_6__["runScriptInPackageStreaming"])({ + script: scriptName, + args: options.args || [], + pkg: this, + debug: options.debug + }); + } + + hasDependencies() { + return Object.keys(this.allDependencies).length > 0; + } + + async installDependencies({ + extraArgs + }) { + _log__WEBPACK_IMPORTED_MODULE_4__["log"].info(`[${this.name}] running yarn`); + _log__WEBPACK_IMPORTED_MODULE_4__["log"].write(''); + await Object(_scripts__WEBPACK_IMPORTED_MODULE_6__["installInDir"])(this.path, extraArgs); + _log__WEBPACK_IMPORTED_MODULE_4__["log"].write(''); + await this.removeExtraneousNodeModules(); + } + /** + * Yarn workspaces symlinks workspace projects to the root node_modules, even + * when there is no depenency on the project. This results in unnecicary, and + * often duplicated code in the build archives. + */ + + + async removeExtraneousNodeModules() { + // this is only relevant for the root workspace + if (!this.isWorkspaceRoot) { + return; + } + + const workspacesInfo = await Object(_scripts__WEBPACK_IMPORTED_MODULE_6__["yarnWorkspacesInfo"])(this.path); + const unusedWorkspaces = new Set(Object.keys(workspacesInfo)); // check for any cross-project dependency + + for (const name of Object.keys(workspacesInfo)) { + const workspace = workspacesInfo[name]; + workspace.workspaceDependencies.forEach(w => unusedWorkspaces.delete(w)); + } + + unusedWorkspaces.forEach(name => { + const { + dependencies, + devDependencies + } = this.json; + const nodeModulesPath = path__WEBPACK_IMPORTED_MODULE_1___default.a.resolve(this.nodeModulesLocation, name); + const isDependency = dependencies && dependencies.hasOwnProperty(name); + const isDevDependency = devDependencies && devDependencies.hasOwnProperty(name); + + if (!isDependency && !isDevDependency && fs__WEBPACK_IMPORTED_MODULE_0___default.a.existsSync(nodeModulesPath)) { + _log__WEBPACK_IMPORTED_MODULE_4__["log"].debug(`No dependency on ${name}, removing link in node_modules`); + fs__WEBPACK_IMPORTED_MODULE_0___default.a.unlinkSync(nodeModulesPath); + } + }); + } + +} // We normalize all path separators to `/` in generated files + +function normalizePath(path) { + return path.replace(/[\\\/]+/g, '/'); +} + +/***/ }), +/* 518 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readPackageJson", function() { return readPackageJson; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "writePackageJson", function() { return writePackageJson; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isLinkDependency", function() { return isLinkDependency; }); +/* harmony import */ var read_pkg__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(519); +/* harmony import */ var read_pkg__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(read_pkg__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var write_pkg__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(545); +/* harmony import */ var write_pkg__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(write_pkg__WEBPACK_IMPORTED_MODULE_1__); +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +function readPackageJson(cwd) { + return read_pkg__WEBPACK_IMPORTED_MODULE_0___default()({ + cwd, + normalize: false + }); +} +function writePackageJson(path, json) { + return write_pkg__WEBPACK_IMPORTED_MODULE_1___default()(path, json); +} +const isLinkDependency = depVersion => depVersion.startsWith('link:'); + +/***/ }), +/* 519 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const {promisify} = __webpack_require__(397); +const fs = __webpack_require__(349); +const path = __webpack_require__(4); +const parseJson = __webpack_require__(520); + +const readFileAsync = promisify(fs.readFile); + +module.exports = async options => { + options = { + cwd: process.cwd(), + normalize: true, + ...options + }; + + const filePath = path.resolve(options.cwd, 'package.json'); + const json = parseJson(await readFileAsync(filePath, 'utf8')); + + if (options.normalize) { + __webpack_require__(521)(json); + } + + return json; +}; + +module.exports.sync = options => { + options = { + cwd: process.cwd(), + normalize: true, + ...options + }; + + const filePath = path.resolve(options.cwd, 'package.json'); + const json = parseJson(fs.readFileSync(filePath, 'utf8')); + + if (options.normalize) { + __webpack_require__(521)(json); + } + + return json; +}; + + +/***/ }), +/* 520 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const errorEx = __webpack_require__(416); +const fallback = __webpack_require__(418); +const {default: LinesAndColumns} = __webpack_require__(419); +const {codeFrameColumns} = __webpack_require__(420); + +const JSONError = errorEx('JSONError', { + fileName: errorEx.append('in %s'), + codeFrame: errorEx.append('\n\n%s\n') +}); + +module.exports = (string, reviver, filename) => { + if (typeof reviver === 'string') { + filename = reviver; + reviver = null; + } + + try { + try { + return JSON.parse(string, reviver); + } catch (error) { + fallback(string, reviver); + throw error; + } + } catch (error) { + error.message = error.message.replace(/\n/g, ''); + const indexMatch = error.message.match(/in JSON at position (\d+) while parsing near/); + + const jsonError = new JSONError(error); + if (filename) { + jsonError.fileName = filename; + } + + if (indexMatch && indexMatch.length > 0) { + const lines = new LinesAndColumns(string); + const index = Number(indexMatch[1]); + const location = lines.locationForIndex(index); + + const codeFrame = codeFrameColumns( + string, + {start: {line: location.line + 1, column: location.column + 1}}, + {highlightCode: true} + ); + + jsonError.codeFrame = codeFrame; + } + + throw jsonError; + } +}; + + +/***/ }), +/* 521 */ +/***/ (function(module, exports, __webpack_require__) { + +module.exports = normalize + +var fixer = __webpack_require__(522) +normalize.fixer = fixer + +var makeWarning = __webpack_require__(543) + +var fieldsToFix = ['name','version','description','repository','modules','scripts' + ,'files','bin','man','bugs','keywords','readme','homepage','license'] +var otherThingsToFix = ['dependencies','people', 'typos'] + +var thingsToFix = fieldsToFix.map(function(fieldName) { + return ucFirst(fieldName) + "Field" +}) +// two ways to do this in CoffeeScript on only one line, sub-70 chars: +// thingsToFix = fieldsToFix.map (name) -> ucFirst(name) + "Field" +// thingsToFix = (ucFirst(name) + "Field" for name in fieldsToFix) +thingsToFix = thingsToFix.concat(otherThingsToFix) + +function normalize (data, warn, strict) { + if(warn === true) warn = null, strict = true + if(!strict) strict = false + if(!warn || data.private) warn = function(msg) { /* noop */ } + + if (data.scripts && + data.scripts.install === "node-gyp rebuild" && + !data.scripts.preinstall) { + data.gypfile = true + } + fixer.warn = function() { warn(makeWarning.apply(null, arguments)) } + thingsToFix.forEach(function(thingName) { + fixer["fix" + ucFirst(thingName)](data, strict) + }) + data._id = data.name + "@" + data.version +} + +function ucFirst (string) { + return string.charAt(0).toUpperCase() + string.slice(1); +} + + +/***/ }), +/* 522 */ +/***/ (function(module, exports, __webpack_require__) { + +var semver = __webpack_require__(523) +var validateLicense = __webpack_require__(524); +var hostedGitInfo = __webpack_require__(529) +var isBuiltinModule = __webpack_require__(532).isCore +var depTypes = ["dependencies","devDependencies","optionalDependencies"] +var extractDescription = __webpack_require__(541) +var url = __webpack_require__(439) +var typos = __webpack_require__(542) + +var fixer = module.exports = { + // default warning function + warn: function() {}, + + fixRepositoryField: function(data) { + if (data.repositories) { + this.warn("repositories"); + data.repository = data.repositories[0] + } + if (!data.repository) return this.warn("missingRepository") + if (typeof data.repository === "string") { + data.repository = { + type: "git", + url: data.repository + } + } + var r = data.repository.url || "" + if (r) { + var hosted = hostedGitInfo.fromUrl(r) + if (hosted) { + r = data.repository.url + = hosted.getDefaultRepresentation() == "shortcut" ? hosted.https() : hosted.toString() + } + } + + if (r.match(/github.com\/[^\/]+\/[^\/]+\.git\.git$/)) { + this.warn("brokenGitUrl", r) + } + } + +, fixTypos: function(data) { + Object.keys(typos.topLevel).forEach(function (d) { + if (data.hasOwnProperty(d)) { + this.warn("typo", d, typos.topLevel[d]) + } + }, this) + } + +, fixScriptsField: function(data) { + if (!data.scripts) return + if (typeof data.scripts !== "object") { + this.warn("nonObjectScripts") + delete data.scripts + return + } + Object.keys(data.scripts).forEach(function (k) { + if (typeof data.scripts[k] !== "string") { + this.warn("nonStringScript") + delete data.scripts[k] + } else if (typos.script[k] && !data.scripts[typos.script[k]]) { + this.warn("typo", k, typos.script[k], "scripts") + } + }, this) + } + +, fixFilesField: function(data) { + var files = data.files + if (files && !Array.isArray(files)) { + this.warn("nonArrayFiles") + delete data.files + } else if (data.files) { + data.files = data.files.filter(function(file) { + if (!file || typeof file !== "string") { + this.warn("invalidFilename", file) + return false + } else { + return true + } + }, this) + } + } + +, fixBinField: function(data) { + if (!data.bin) return; + if (typeof data.bin === "string") { + var b = {} + var match + if (match = data.name.match(/^@[^/]+[/](.*)$/)) { + b[match[1]] = data.bin + } else { + b[data.name] = data.bin + } + data.bin = b + } + } + +, fixManField: function(data) { + if (!data.man) return; + if (typeof data.man === "string") { + data.man = [ data.man ] + } + } +, fixBundleDependenciesField: function(data) { + var bdd = "bundledDependencies" + var bd = "bundleDependencies" + if (data[bdd] && !data[bd]) { + data[bd] = data[bdd] + delete data[bdd] + } + if (data[bd] && !Array.isArray(data[bd])) { + this.warn("nonArrayBundleDependencies") + delete data[bd] + } else if (data[bd]) { + data[bd] = data[bd].filter(function(bd) { + if (!bd || typeof bd !== 'string') { + this.warn("nonStringBundleDependency", bd) + return false + } else { + if (!data.dependencies) { + data.dependencies = {} + } + if (!data.dependencies.hasOwnProperty(bd)) { + this.warn("nonDependencyBundleDependency", bd) + data.dependencies[bd] = "*" + } + return true + } + }, this) + } + } + +, fixDependencies: function(data, strict) { + var loose = !strict + objectifyDeps(data, this.warn) + addOptionalDepsToDeps(data, this.warn) + this.fixBundleDependenciesField(data) + + ;['dependencies','devDependencies'].forEach(function(deps) { + if (!(deps in data)) return + if (!data[deps] || typeof data[deps] !== "object") { + this.warn("nonObjectDependencies", deps) + delete data[deps] + return + } + Object.keys(data[deps]).forEach(function (d) { + var r = data[deps][d] + if (typeof r !== 'string') { + this.warn("nonStringDependency", d, JSON.stringify(r)) + delete data[deps][d] + } + var hosted = hostedGitInfo.fromUrl(data[deps][d]) + if (hosted) data[deps][d] = hosted.toString() + }, this) + }, this) + } + +, fixModulesField: function (data) { + if (data.modules) { + this.warn("deprecatedModules") + delete data.modules + } + } + +, fixKeywordsField: function (data) { + if (typeof data.keywords === "string") { + data.keywords = data.keywords.split(/,\s+/) + } + if (data.keywords && !Array.isArray(data.keywords)) { + delete data.keywords + this.warn("nonArrayKeywords") + } else if (data.keywords) { + data.keywords = data.keywords.filter(function(kw) { + if (typeof kw !== "string" || !kw) { + this.warn("nonStringKeyword"); + return false + } else { + return true + } + }, this) + } + } + +, fixVersionField: function(data, strict) { + // allow "loose" semver 1.0 versions in non-strict mode + // enforce strict semver 2.0 compliance in strict mode + var loose = !strict + if (!data.version) { + data.version = "" + return true + } + if (!semver.valid(data.version, loose)) { + throw new Error('Invalid version: "'+ data.version + '"') + } + data.version = semver.clean(data.version, loose) + return true + } + +, fixPeople: function(data) { + modifyPeople(data, unParsePerson) + modifyPeople(data, parsePerson) + } + +, fixNameField: function(data, options) { + if (typeof options === "boolean") options = {strict: options} + else if (typeof options === "undefined") options = {} + var strict = options.strict + if (!data.name && !strict) { + data.name = "" + return + } + if (typeof data.name !== "string") { + throw new Error("name field must be a string.") + } + if (!strict) + data.name = data.name.trim() + ensureValidName(data.name, strict, options.allowLegacyCase) + if (isBuiltinModule(data.name)) + this.warn("conflictingName", data.name) + } + + +, fixDescriptionField: function (data) { + if (data.description && typeof data.description !== 'string') { + this.warn("nonStringDescription") + delete data.description + } + if (data.readme && !data.description) + data.description = extractDescription(data.readme) + if(data.description === undefined) delete data.description; + if (!data.description) this.warn("missingDescription") + } + +, fixReadmeField: function (data) { + if (!data.readme) { + this.warn("missingReadme") + data.readme = "ERROR: No README data found!" + } + } + +, fixBugsField: function(data) { + if (!data.bugs && data.repository && data.repository.url) { + var hosted = hostedGitInfo.fromUrl(data.repository.url) + if(hosted && hosted.bugs()) { + data.bugs = {url: hosted.bugs()} + } + } + else if(data.bugs) { + var emailRe = /^.+@.*\..+$/ + if(typeof data.bugs == "string") { + if(emailRe.test(data.bugs)) + data.bugs = {email:data.bugs} + else if(url.parse(data.bugs).protocol) + data.bugs = {url: data.bugs} + else + this.warn("nonEmailUrlBugsString") + } + else { + bugsTypos(data.bugs, this.warn) + var oldBugs = data.bugs + data.bugs = {} + if(oldBugs.url) { + if(typeof(oldBugs.url) == "string" && url.parse(oldBugs.url).protocol) + data.bugs.url = oldBugs.url + else + this.warn("nonUrlBugsUrlField") + } + if(oldBugs.email) { + if(typeof(oldBugs.email) == "string" && emailRe.test(oldBugs.email)) + data.bugs.email = oldBugs.email + else + this.warn("nonEmailBugsEmailField") + } + } + if(!data.bugs.email && !data.bugs.url) { + delete data.bugs + this.warn("emptyNormalizedBugs") + } + } + } + +, fixHomepageField: function(data) { + if (!data.homepage && data.repository && data.repository.url) { + var hosted = hostedGitInfo.fromUrl(data.repository.url) + if (hosted && hosted.docs()) data.homepage = hosted.docs() + } + if (!data.homepage) return + + if(typeof data.homepage !== "string") { + this.warn("nonUrlHomepage") + return delete data.homepage + } + if(!url.parse(data.homepage).protocol) { + data.homepage = "http://" + data.homepage + } + } + +, fixLicenseField: function(data) { + if (!data.license) { + return this.warn("missingLicense") + } else{ + if ( + typeof(data.license) !== 'string' || + data.license.length < 1 || + data.license.trim() === '' + ) { + this.warn("invalidLicense") + } else { + if (!validateLicense(data.license).validForNewPackages) + this.warn("invalidLicense") + } + } + } +} + +function isValidScopedPackageName(spec) { + if (spec.charAt(0) !== '@') return false + + var rest = spec.slice(1).split('/') + if (rest.length !== 2) return false + + return rest[0] && rest[1] && + rest[0] === encodeURIComponent(rest[0]) && + rest[1] === encodeURIComponent(rest[1]) +} + +function isCorrectlyEncodedName(spec) { + return !spec.match(/[\/@\s\+%:]/) && + spec === encodeURIComponent(spec) +} + +function ensureValidName (name, strict, allowLegacyCase) { + if (name.charAt(0) === "." || + !(isValidScopedPackageName(name) || isCorrectlyEncodedName(name)) || + (strict && (!allowLegacyCase) && name !== name.toLowerCase()) || + name.toLowerCase() === "node_modules" || + name.toLowerCase() === "favicon.ico") { + throw new Error("Invalid name: " + JSON.stringify(name)) + } +} + +function modifyPeople (data, fn) { + if (data.author) data.author = fn(data.author) + ;["maintainers", "contributors"].forEach(function (set) { + if (!Array.isArray(data[set])) return; + data[set] = data[set].map(fn) + }) + return data +} + +function unParsePerson (person) { + if (typeof person === "string") return person + var name = person.name || "" + var u = person.url || person.web + var url = u ? (" ("+u+")") : "" + var e = person.email || person.mail + var email = e ? (" <"+e+">") : "" + return name+email+url +} + +function parsePerson (person) { + if (typeof person !== "string") return person + var name = person.match(/^([^\(<]+)/) + var url = person.match(/\(([^\)]+)\)/) + var email = person.match(/<([^>]+)>/) + var obj = {} + if (name && name[0].trim()) obj.name = name[0].trim() + if (email) obj.email = email[1]; + if (url) obj.url = url[1]; + return obj } -}, -rules: [/^(?:$)/,/^(?:\s+)/,/^(?:\+)/,/^(?:\()/,/^(?:\))/,/^(?::)/,/^(?:DocumentRef-([0-9A-Za-z-+.]+))/,/^(?:LicenseRef-([0-9A-Za-z-+.]+))/,/^(?:AND)/,/^(?:OR)/,/^(?:WITH)/,/^(?:BSD-3-Clause-No-Nuclear-License-2014)/,/^(?:BSD-3-Clause-No-Nuclear-Warranty)/,/^(?:GPL-2\.0-with-classpath-exception)/,/^(?:GPL-3\.0-with-autoconf-exception)/,/^(?:GPL-2\.0-with-autoconf-exception)/,/^(?:BSD-3-Clause-No-Nuclear-License)/,/^(?:MPL-2\.0-no-copyleft-exception)/,/^(?:GPL-2\.0-with-bison-exception)/,/^(?:GPL-2\.0-with-font-exception)/,/^(?:GPL-2\.0-with-GCC-exception)/,/^(?:CNRI-Python-GPL-Compatible)/,/^(?:GPL-3\.0-with-GCC-exception)/,/^(?:BSD-3-Clause-Attribution)/,/^(?:Classpath-exception-2\.0)/,/^(?:WxWindows-exception-3\.1)/,/^(?:freertos-exception-2\.0)/,/^(?:Autoconf-exception-3\.0)/,/^(?:i2p-gpl-java-exception)/,/^(?:gnu-javamail-exception)/,/^(?:Nokia-Qt-exception-1\.1)/,/^(?:Autoconf-exception-2\.0)/,/^(?:BSD-2-Clause-FreeBSD)/,/^(?:u-boot-exception-2\.0)/,/^(?:zlib-acknowledgement)/,/^(?:Bison-exception-2\.2)/,/^(?:BSD-2-Clause-NetBSD)/,/^(?:CLISP-exception-2\.0)/,/^(?:eCos-exception-2\.0)/,/^(?:BSD-3-Clause-Clear)/,/^(?:Font-exception-2\.0)/,/^(?:FLTK-exception-2\.0)/,/^(?:GCC-exception-2\.0)/,/^(?:Qwt-exception-1\.0)/,/^(?:Libtool-exception)/,/^(?:BSD-3-Clause-LBNL)/,/^(?:GCC-exception-3\.1)/,/^(?:Artistic-1\.0-Perl)/,/^(?:Artistic-1\.0-cl8)/,/^(?:CC-BY-NC-SA-2\.5)/,/^(?:MIT-advertising)/,/^(?:BSD-Source-Code)/,/^(?:CC-BY-NC-SA-4\.0)/,/^(?:LiLiQ-Rplus-1\.1)/,/^(?:CC-BY-NC-SA-3\.0)/,/^(?:BSD-4-Clause-UC)/,/^(?:CC-BY-NC-SA-2\.0)/,/^(?:CC-BY-NC-SA-1\.0)/,/^(?:CC-BY-NC-ND-4\.0)/,/^(?:CC-BY-NC-ND-3\.0)/,/^(?:CC-BY-NC-ND-2\.5)/,/^(?:CC-BY-NC-ND-2\.0)/,/^(?:CC-BY-NC-ND-1\.0)/,/^(?:LZMA-exception)/,/^(?:BitTorrent-1\.1)/,/^(?:CrystalStacker)/,/^(?:FLTK-exception)/,/^(?:SugarCRM-1\.1\.3)/,/^(?:BSD-Protection)/,/^(?:BitTorrent-1\.0)/,/^(?:HaskellReport)/,/^(?:Interbase-1\.0)/,/^(?:StandardML-NJ)/,/^(?:mif-exception)/,/^(?:Frameworx-1\.0)/,/^(?:389-exception)/,/^(?:CC-BY-NC-2\.0)/,/^(?:CC-BY-NC-2\.5)/,/^(?:CC-BY-NC-3\.0)/,/^(?:CC-BY-NC-4\.0)/,/^(?:W3C-19980720)/,/^(?:CC-BY-SA-1\.0)/,/^(?:CC-BY-SA-2\.0)/,/^(?:CC-BY-SA-2\.5)/,/^(?:CC-BY-ND-2\.0)/,/^(?:CC-BY-SA-4\.0)/,/^(?:CC-BY-SA-3\.0)/,/^(?:Artistic-1\.0)/,/^(?:Artistic-2\.0)/,/^(?:CC-BY-ND-2\.5)/,/^(?:CC-BY-ND-3\.0)/,/^(?:CC-BY-ND-4\.0)/,/^(?:CC-BY-ND-1\.0)/,/^(?:BSD-4-Clause)/,/^(?:BSD-3-Clause)/,/^(?:BSD-2-Clause)/,/^(?:CC-BY-NC-1\.0)/,/^(?:bzip2-1\.0\.6)/,/^(?:Unicode-TOU)/,/^(?:CNRI-Jython)/,/^(?:ImageMagick)/,/^(?:Adobe-Glyph)/,/^(?:CUA-OPL-1\.0)/,/^(?:OLDAP-2\.2\.2)/,/^(?:LiLiQ-R-1\.1)/,/^(?:bzip2-1\.0\.5)/,/^(?:LiLiQ-P-1\.1)/,/^(?:OLDAP-2\.0\.1)/,/^(?:OLDAP-2\.2\.1)/,/^(?:CNRI-Python)/,/^(?:XFree86-1\.1)/,/^(?:OSET-PL-2\.1)/,/^(?:Apache-2\.0)/,/^(?:Watcom-1\.0)/,/^(?:PostgreSQL)/,/^(?:Python-2\.0)/,/^(?:RHeCos-1\.1)/,/^(?:EUDatagrid)/,/^(?:Spencer-99)/,/^(?:Intel-ACPI)/,/^(?:CECILL-1\.0)/,/^(?:CECILL-1\.1)/,/^(?:JasPer-2\.0)/,/^(?:CECILL-2\.0)/,/^(?:CECILL-2\.1)/,/^(?:gSOAP-1\.3b)/,/^(?:Spencer-94)/,/^(?:Apache-1\.1)/,/^(?:Spencer-86)/,/^(?:Apache-1\.0)/,/^(?:ClArtistic)/,/^(?:TORQUE-1\.1)/,/^(?:CATOSL-1\.1)/,/^(?:Adobe-2006)/,/^(?:Zimbra-1\.4)/,/^(?:Zimbra-1\.3)/,/^(?:Condor-1\.1)/,/^(?:CC-BY-3\.0)/,/^(?:CC-BY-2\.5)/,/^(?:OLDAP-2\.4)/,/^(?:SGI-B-1\.1)/,/^(?:SISSL-1\.2)/,/^(?:SGI-B-1\.0)/,/^(?:OLDAP-2\.3)/,/^(?:CC-BY-4\.0)/,/^(?:Crossword)/,/^(?:SimPL-2\.0)/,/^(?:OLDAP-2\.2)/,/^(?:OLDAP-2\.1)/,/^(?:ErlPL-1\.1)/,/^(?:LPPL-1\.3a)/,/^(?:LPPL-1\.3c)/,/^(?:OLDAP-2\.0)/,/^(?:Leptonica)/,/^(?:CPOL-1\.02)/,/^(?:OLDAP-1\.4)/,/^(?:OLDAP-1\.3)/,/^(?:CC-BY-2\.0)/,/^(?:Unlicense)/,/^(?:OLDAP-2\.8)/,/^(?:OLDAP-1\.2)/,/^(?:MakeIndex)/,/^(?:OLDAP-2\.7)/,/^(?:OLDAP-1\.1)/,/^(?:Sleepycat)/,/^(?:D-FSL-1\.0)/,/^(?:CC-BY-1\.0)/,/^(?:OLDAP-2\.6)/,/^(?:WXwindows)/,/^(?:NPOSL-3\.0)/,/^(?:FreeImage)/,/^(?:SGI-B-2\.0)/,/^(?:OLDAP-2\.5)/,/^(?:Beerware)/,/^(?:Newsletr)/,/^(?:NBPL-1\.0)/,/^(?:NASA-1\.3)/,/^(?:NLOD-1\.0)/,/^(?:AGPL-1\.0)/,/^(?:OCLC-2\.0)/,/^(?:ODbL-1\.0)/,/^(?:PDDL-1\.0)/,/^(?:Motosoto)/,/^(?:Afmparse)/,/^(?:ANTLR-PD)/,/^(?:LPL-1\.02)/,/^(?:Abstyles)/,/^(?:eCos-2\.0)/,/^(?:APSL-1\.0)/,/^(?:LPPL-1\.2)/,/^(?:LPPL-1\.1)/,/^(?:LPPL-1\.0)/,/^(?:APSL-1\.1)/,/^(?:APSL-2\.0)/,/^(?:Info-ZIP)/,/^(?:Zend-2\.0)/,/^(?:IBM-pibs)/,/^(?:LGPL-2\.0)/,/^(?:LGPL-3\.0)/,/^(?:LGPL-2\.1)/,/^(?:GFDL-1\.3)/,/^(?:PHP-3\.01)/,/^(?:GFDL-1\.2)/,/^(?:GFDL-1\.1)/,/^(?:AGPL-3\.0)/,/^(?:Giftware)/,/^(?:EUPL-1\.1)/,/^(?:RPSL-1\.0)/,/^(?:EUPL-1\.0)/,/^(?:MIT-enna)/,/^(?:CECILL-B)/,/^(?:diffmark)/,/^(?:CECILL-C)/,/^(?:CDDL-1\.0)/,/^(?:Sendmail)/,/^(?:CDDL-1\.1)/,/^(?:CPAL-1\.0)/,/^(?:APSL-1\.2)/,/^(?:NPL-1\.1)/,/^(?:AFL-1\.2)/,/^(?:Caldera)/,/^(?:AFL-2\.0)/,/^(?:FSFULLR)/,/^(?:AFL-2\.1)/,/^(?:VSL-1\.0)/,/^(?:VOSTROM)/,/^(?:UPL-1\.0)/,/^(?:Dotseqn)/,/^(?:CPL-1\.0)/,/^(?:dvipdfm)/,/^(?:EPL-1\.0)/,/^(?:OCCT-PL)/,/^(?:ECL-1\.0)/,/^(?:Latex2e)/,/^(?:ECL-2\.0)/,/^(?:GPL-1\.0)/,/^(?:GPL-2\.0)/,/^(?:GPL-3\.0)/,/^(?:AFL-3\.0)/,/^(?:LAL-1\.2)/,/^(?:LAL-1\.3)/,/^(?:EFL-1\.0)/,/^(?:EFL-2\.0)/,/^(?:gnuplot)/,/^(?:Aladdin)/,/^(?:LPL-1\.0)/,/^(?:libtiff)/,/^(?:Entessa)/,/^(?:AMDPLPA)/,/^(?:IPL-1\.0)/,/^(?:OPL-1\.0)/,/^(?:OSL-1\.0)/,/^(?:OSL-1\.1)/,/^(?:OSL-2\.0)/,/^(?:OSL-2\.1)/,/^(?:OSL-3\.0)/,/^(?:OpenSSL)/,/^(?:ZPL-2\.1)/,/^(?:PHP-3\.0)/,/^(?:ZPL-2\.0)/,/^(?:ZPL-1\.1)/,/^(?:CC0-1\.0)/,/^(?:SPL-1\.0)/,/^(?:psutils)/,/^(?:MPL-1\.0)/,/^(?:QPL-1\.0)/,/^(?:MPL-1\.1)/,/^(?:MPL-2\.0)/,/^(?:APL-1\.0)/,/^(?:RPL-1\.1)/,/^(?:RPL-1\.5)/,/^(?:MIT-CMU)/,/^(?:Multics)/,/^(?:Eurosym)/,/^(?:BSL-1\.0)/,/^(?:MIT-feh)/,/^(?:Saxpath)/,/^(?:Borceux)/,/^(?:OFL-1\.1)/,/^(?:OFL-1\.0)/,/^(?:AFL-1\.1)/,/^(?:YPL-1\.1)/,/^(?:YPL-1\.0)/,/^(?:NPL-1\.0)/,/^(?:iMatix)/,/^(?:mpich2)/,/^(?:APAFML)/,/^(?:Bahyph)/,/^(?:RSA-MD)/,/^(?:psfrag)/,/^(?:Plexus)/,/^(?:eGenix)/,/^(?:Glulxe)/,/^(?:SAX-PD)/,/^(?:Imlib2)/,/^(?:Wsuipa)/,/^(?:LGPLLR)/,/^(?:Libpng)/,/^(?:xinetd)/,/^(?:MITNFA)/,/^(?:NetCDF)/,/^(?:Naumen)/,/^(?:SMPPL)/,/^(?:Nunit)/,/^(?:FSFUL)/,/^(?:GL2PS)/,/^(?:SMLNJ)/,/^(?:Rdisc)/,/^(?:Noweb)/,/^(?:Nokia)/,/^(?:SISSL)/,/^(?:Qhull)/,/^(?:Intel)/,/^(?:Glide)/,/^(?:Xerox)/,/^(?:AMPAS)/,/^(?:WTFPL)/,/^(?:MS-PL)/,/^(?:XSkat)/,/^(?:MS-RL)/,/^(?:MirOS)/,/^(?:RSCPL)/,/^(?:TMate)/,/^(?:OGTSL)/,/^(?:FSFAP)/,/^(?:NCSA)/,/^(?:Zlib)/,/^(?:SCEA)/,/^(?:SNIA)/,/^(?:NGPL)/,/^(?:NOSL)/,/^(?:ADSL)/,/^(?:MTLL)/,/^(?:NLPL)/,/^(?:Ruby)/,/^(?:JSON)/,/^(?:Barr)/,/^(?:0BSD)/,/^(?:Xnet)/,/^(?:Cube)/,/^(?:curl)/,/^(?:DSDP)/,/^(?:Fair)/,/^(?:HPND)/,/^(?:TOSL)/,/^(?:IJG)/,/^(?:SWL)/,/^(?:Vim)/,/^(?:FTL)/,/^(?:ICU)/,/^(?:OML)/,/^(?:NRL)/,/^(?:DOC)/,/^(?:TCL)/,/^(?:W3C)/,/^(?:NTP)/,/^(?:IPA)/,/^(?:ISC)/,/^(?:X11)/,/^(?:AAL)/,/^(?:AML)/,/^(?:xpp)/,/^(?:Zed)/,/^(?:MIT)/,/^(?:Mup)/], -conditions: {"INITIAL":{"rules":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364],"inclusive":true}} -}); -return lexer; -})(); -parser.lexer = lexer; -function Parser () { - this.yy = {}; + +function addOptionalDepsToDeps (data, warn) { + var o = data.optionalDependencies + if (!o) return; + var d = data.dependencies || {} + Object.keys(o).forEach(function (k) { + d[k] = o[k] + }) + data.dependencies = d +} + +function depObjectify (deps, type, warn) { + if (!deps) return {} + if (typeof deps === "string") { + deps = deps.trim().split(/[\n\r\s\t ,]+/) + } + if (!Array.isArray(deps)) return deps + warn("deprecatedArrayDependencies", type) + var o = {} + deps.filter(function (d) { + return typeof d === "string" + }).forEach(function(d) { + d = d.trim().split(/(:?[@\s><=])/) + var dn = d.shift() + var dv = d.join("") + dv = dv.trim() + dv = dv.replace(/^@/, "") + o[dn] = dv + }) + return o +} + +function objectifyDeps (data, warn) { + depTypes.forEach(function (type) { + if (!data[type]) return; + data[type] = depObjectify(data[type], type, warn) + }) +} + +function bugsTypos(bugs, warn) { + if (!bugs) return + Object.keys(bugs).forEach(function (k) { + if (typos.bugs[k]) { + warn("typo", k, typos.bugs[k], "bugs") + bugs[typos.bugs[k]] = bugs[k] + delete bugs[k] + } + }) +} + + +/***/ }), +/* 523 */ +/***/ (function(module, exports) { + +exports = module.exports = SemVer + +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 () {} +} + +// 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' + +var MAX_LENGTH = 256 +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 + +// 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 R = 0 + +// 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. + +var NUMERICIDENTIFIER = R++ +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' +var NUMERICIDENTIFIERLOOSE = R++ +src[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. + +var NONNUMERICIDENTIFIER = R++ +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' + +// ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++ +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')' + +var MAINVERSIONLOOSE = R++ +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')' + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++ +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')' + +var PRERELEASEIDENTIFIERLOOSE = R++ +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')' + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +var PRERELEASE = R++ +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' + +var PRERELEASELOOSE = R++ +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +var BUILDIDENTIFIER = R++ +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +var BUILD = R++ +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// 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. + +var FULL = R++ +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?' + +src[FULL] = '^' + FULLPLAIN + '$' + +// 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. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?' + +var LOOSE = R++ +src[LOOSE] = '^' + LOOSEPLAIN + '$' + +var GTLT = R++ +src[GTLT] = '((?:<|>)?=?)' + +// 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. +var XRANGEIDENTIFIERLOOSE = R++ +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' +var XRANGEIDENTIFIER = R++ +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' + +var XRANGEPLAIN = R++ +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?' + +var XRANGEPLAINLOOSE = R++ +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?' + +var XRANGE = R++ +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' +var XRANGELOOSE = R++ +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +var COERCE = R++ +src[COERCE] = '(?:^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])' + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++ +src[LONETILDE] = '(?:~>?)' + +var TILDETRIM = R++ +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') +var tildeTrimReplace = '$1~' + +var TILDE = R++ +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' +var TILDELOOSE = R++ +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++ +src[LONECARET] = '(?:\\^)' + +var CARETTRIM = R++ +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') +var caretTrimReplace = '$1^' + +var CARET = R++ +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' +var CARETLOOSE = R++ +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++ +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' +var COMPARATOR = R++ +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++ +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' + +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') +var comparatorTrimReplace = '$1$2$3' + +// 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. +var HYPHENRANGE = R++ +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$' + +var HYPHENRANGELOOSE = R++ +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$' + +// Star ranges basically just allow anything at all. +var STAR = R++ +src[STAR] = '(<|>)?=?\\s*\\*' + +// 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]) + } +} + +exports.parse = parse +function parse (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + var r = options.loose ? re[LOOSE] : re[FULL] + if (!r.test(version)) { + return null + } + + try { + return new SemVer(version, options) + } catch (er) { + return null + } +} + +exports.valid = valid +function valid (version, options) { + var v = parse(version, options) + return v ? v.version : null +} + +exports.clean = clean +function clean (version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} + +exports.SemVer = SemVer + +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) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + } + + if (!(this instanceof SemVer)) { + return new SemVer(version, options) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + + var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) + + if (!m) { + throw new TypeError('Invalid Version: ' + version) + } + + 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') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // 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 + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() +} + +SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.') + } + return this.version +} + +SemVer.prototype.toString = function () { + return this.version +} + +SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return this.compareMain(other) || this.comparePre(other) +} + +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) +} + +SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // 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 + } + + 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) + } + } 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 + + 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 + + default: + throw new Error('invalid increment argument: ' + release) + } + this.format() + this.raw = this.version + return this } -Parser.prototype = parser;parser.Parser = Parser; -return new Parser; -})(); +exports.inc = inc +function inc (version, release, loose, identifier) { + if (typeof (loose) === 'string') { + identifier = loose + loose = undefined + } + + try { + return new SemVer(version, loose).inc(release, identifier).version + } catch (er) { + return null + } +} -if (true) { -exports.parser = spdxparse; -exports.Parser = spdxparse.Parser; -exports.parse = function () { return spdxparse.parse.apply(spdxparse, arguments); }; -exports.main = function commonjsMain(args) { - if (!args[1]) { - console.log('Usage: '+args[0]+' FILE'); - process.exit(1); +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' } - var source = __webpack_require__(23).readFileSync(__webpack_require__(16).normalize(args[1]), "utf8"); - return exports.parser.parse(source); -}; -if ( true && __webpack_require__.c[__webpack_require__.s] === module) { - exports.main(process.argv.slice(1)); + 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 + } } + +exports.compareIdentifiers = compareIdentifiers + +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 + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 } -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(5)(module))) +exports.rcompareIdentifiers = rcompareIdentifiers +function rcompareIdentifiers (a, b) { + return compareIdentifiers(b, a) +} -/***/ }), -/* 527 */ -/***/ (function(module, exports, __webpack_require__) { +exports.major = major +function major (a, loose) { + return new SemVer(a, loose).major +} -var licenseIDs = __webpack_require__(528); +exports.minor = minor +function minor (a, loose) { + return new SemVer(a, loose).minor +} -function valid(string) { - return licenseIDs.indexOf(string) > -1; +exports.patch = patch +function patch (a, loose) { + return new SemVer(a, loose).patch } -// Common transpositions of license identifier acronyms -var transpositions = [ - ['APGL', 'AGPL'], - ['Gpl', 'GPL'], - ['GLP', 'GPL'], - ['APL', 'Apache'], - ['ISD', 'ISC'], - ['GLP', 'GPL'], - ['IST', 'ISC'], - ['Claude', 'Clause'], - [' or later', '+'], - [' International', ''], - ['GNU', 'GPL'], - ['GUN', 'GPL'], - ['+', ''], - ['GNU GPL', 'GPL'], - ['GNU/GPL', 'GPL'], - ['GNU GLP', 'GPL'], - ['GNU General Public License', 'GPL'], - ['Gnu public license', 'GPL'], - ['GNU Public License', 'GPL'], - ['GNU GENERAL PUBLIC LICENSE', 'GPL'], - ['MTI', 'MIT'], - ['Mozilla Public License', 'MPL'], - ['WTH', 'WTF'], - ['-License', ''] -]; +exports.compare = compare +function compare (a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)) +} -var TRANSPOSED = 0; -var CORRECT = 1; +exports.compareLoose = compareLoose +function compareLoose (a, b) { + return compare(a, b, true) +} -// Simple corrections to nearly valid identifiers. -var transforms = [ - // e.g. 'mit' - function(argument) { - return argument.toUpperCase(); - }, - // e.g. 'MIT ' - function(argument) { - return argument.trim(); - }, - // e.g. 'M.I.T.' - function(argument) { - return argument.replace(/\./g, ''); - }, - // e.g. 'Apache- 2.0' - function(argument) { - return argument.replace(/\s+/g, ''); - }, - // e.g. 'CC BY 4.0'' - function(argument) { - return argument.replace(/\s+/g, '-'); - }, - // e.g. 'LGPLv2.1' - function(argument) { - return argument.replace('v', '-'); - }, - // e.g. 'Apache 2.0' - function(argument) { - return argument.replace(/,?\s*(\d)/, '-$1'); - }, - // e.g. 'GPL 2' - function(argument) { - return argument.replace(/,?\s*(\d)/, '-$1.0'); - }, - // e.g. 'Apache Version 2.0' - function(argument) { - return argument.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, '-$2'); - }, - // e.g. 'Apache Version 2' - function(argument) { - return argument.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, '-$2.0'); - }, - // e.g. 'ZLIB' - function(argument) { - return argument[0].toUpperCase() + argument.slice(1); - }, - // e.g. 'MPL/2.0' - function(argument) { - return argument.replace('/', '-'); - }, - // e.g. 'Apache 2' - function(argument) { - return argument - .replace(/\s*V\s*(\d)/, '-$1') - .replace(/(\d)$/, '$1.0'); - }, - // e.g. 'GPL-2.0-' - function(argument) { - return argument.slice(0, argument.length - 1); - }, - // e.g. 'GPL2' - function(argument) { - return argument.replace(/(\d)$/, '-$1.0'); - }, - // e.g. 'BSD 3' - function(argument) { - return argument.replace(/(-| )?(\d)$/, '-$2-Clause'); - }, - // e.g. 'BSD clause 3' - function(argument) { - return argument.replace(/(-| )clause(-| )(\d)/, '-$3-Clause'); - }, - // e.g. 'BY-NC-4.0' - function(argument) { - return 'CC-' + argument; - }, - // e.g. 'BY-NC' - function(argument) { - return 'CC-' + argument + '-4.0'; - }, - // e.g. 'Attribution-NonCommercial' - function(argument) { - return argument - .replace('Attribution', 'BY') - .replace('NonCommercial', 'NC') - .replace('NoDerivatives', 'ND') - .replace(/ (\d)/, '-$1') - .replace(/ ?International/, ''); - }, - // e.g. 'Attribution-NonCommercial' - function(argument) { - return 'CC-' + - argument - .replace('Attribution', 'BY') - .replace('NonCommercial', 'NC') - .replace('NoDerivatives', 'ND') - .replace(/ (\d)/, '-$1') - .replace(/ ?International/, '') + - '-4.0'; +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.compare(a, b, loose) + }) +} + +exports.rsort = rsort +function rsort (list, loose) { + return list.sort(function (a, b) { + return exports.rcompare(a, b, loose) + }) +} + +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 +} + +exports.eq = eq +function eq (a, b, loose) { + return compare(a, b, loose) === 0 +} + +exports.neq = neq +function neq (a, b, loose) { + return compare(a, b, loose) !== 0 +} + +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 +} + +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 + + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError('Invalid operator: ' + op) } -]; +} -// If all else fails, guess that strings containing certain substrings -// meant to identify certain licenses. -var lastResorts = [ - ['UNLI', 'Unlicense'], - ['WTF', 'WTFPL'], - ['2 CLAUSE', 'BSD-2-Clause'], - ['2-CLAUSE', 'BSD-2-Clause'], - ['3 CLAUSE', 'BSD-3-Clause'], - ['3-CLAUSE', 'BSD-3-Clause'], - ['AFFERO', 'AGPL-3.0'], - ['AGPL', 'AGPL-3.0'], - ['APACHE', 'Apache-2.0'], - ['ARTISTIC', 'Artistic-2.0'], - ['Affero', 'AGPL-3.0'], - ['BEER', 'Beerware'], - ['BOOST', 'BSL-1.0'], - ['BSD', 'BSD-2-Clause'], - ['ECLIPSE', 'EPL-1.0'], - ['FUCK', 'WTFPL'], - ['GNU', 'GPL-3.0'], - ['LGPL', 'LGPL-3.0'], - ['GPL', 'GPL-3.0'], - ['MIT', 'MIT'], - ['MPL', 'MPL-2.0'], - ['X11', 'X11'], - ['ZLIB', 'Zlib'] -]; +exports.Comparator = Comparator +function Comparator (comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + if (!(this instanceof Comparator)) { + return new Comparator(comp, options) + } + + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) +} + +var ANY = {} +Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var m = comp.match(r) + + if (!m) { + throw new TypeError('Invalid comparator: ' + comp) + } + + this.operator = m[1] + if (this.operator === '=') { + this.operator = '' + } + + // 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) + } +} + +Comparator.prototype.toString = function () { + return this.value +} + +Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY) { + return true + } + + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } + + return cmp(version, this.operator, this.semver, this.options) +} + +Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } -var SUBSTRING = 0; -var IDENTIFIER = 1; + var rangeTmp -var validTransformation = function(identifier) { - for (var i = 0; i < transforms.length; i++) { - var transformed = transforms[i](identifier); - if (transformed !== identifier && valid(transformed)) { - return transformed; - } + if (this.operator === '') { + rangeTmp = new Range(comp.value, options) + return satisfies(this.value, rangeTmp, options) + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, options) + return satisfies(comp.semver, rangeTmp, options) } - return null; -}; -var validLastResort = function(identifier) { - var upperCased = identifier.toUpperCase(); - for (var i = 0; i < lastResorts.length; i++) { - var lastResort = lastResorts[i]; - if (upperCased.indexOf(lastResort[SUBSTRING]) > -1) { - return lastResort[IDENTIFIER]; + 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 sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan +} + +exports.Range = Range +function Range (range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false } } - return null; -}; -var anyCorrection = function(identifier, check) { - for (var i = 0; i < transpositions.length; i++) { - var transposition = transpositions[i]; - var transposed = transposition[TRANSPOSED]; - if (identifier.indexOf(transposed) > -1) { - var corrected = identifier.replace( - transposed, - transposition[CORRECT] - ); - var checked = check(corrected); - if (checked !== null) { - return checked; - } + if (range instanceof Range) { + if (range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease) { + return range + } else { + return new Range(range.raw, options) } } - return null; -}; -module.exports = function(identifier) { - identifier = identifier.replace(/\+$/, ''); - if (valid(identifier)) { - return identifier; - } - var transformed = validTransformation(identifier); - if (transformed !== null) { - return transformed; - } - transformed = anyCorrection(identifier, function(argument) { - if (valid(argument)) { - return argument; - } - return validTransformation(argument); - }); - if (transformed !== null) { - return transformed; + if (range instanceof Comparator) { + return new Range(range.value, options) } - transformed = validLastResort(identifier); - if (transformed !== null) { - return transformed; + + if (!(this instanceof Range)) { + return new Range(range, options) } - transformed = anyCorrection(identifier, validLastResort); - if (transformed !== null) { - return transformed; + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // 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 (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range) } - return null; -}; + this.format() +} -/***/ }), -/* 528 */ -/***/ (function(module) { +Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim() + }).join('||').trim() + return this.range +} -module.exports = JSON.parse("[\"Glide\",\"Abstyles\",\"AFL-1.1\",\"AFL-1.2\",\"AFL-2.0\",\"AFL-2.1\",\"AFL-3.0\",\"AMPAS\",\"APL-1.0\",\"Adobe-Glyph\",\"APAFML\",\"Adobe-2006\",\"AGPL-1.0\",\"Afmparse\",\"Aladdin\",\"ADSL\",\"AMDPLPA\",\"ANTLR-PD\",\"Apache-1.0\",\"Apache-1.1\",\"Apache-2.0\",\"AML\",\"APSL-1.0\",\"APSL-1.1\",\"APSL-1.2\",\"APSL-2.0\",\"Artistic-1.0\",\"Artistic-1.0-Perl\",\"Artistic-1.0-cl8\",\"Artistic-2.0\",\"AAL\",\"Bahyph\",\"Barr\",\"Beerware\",\"BitTorrent-1.0\",\"BitTorrent-1.1\",\"BSL-1.0\",\"Borceux\",\"BSD-2-Clause\",\"BSD-2-Clause-FreeBSD\",\"BSD-2-Clause-NetBSD\",\"BSD-3-Clause\",\"BSD-3-Clause-Clear\",\"BSD-4-Clause\",\"BSD-Protection\",\"BSD-Source-Code\",\"BSD-3-Clause-Attribution\",\"0BSD\",\"BSD-4-Clause-UC\",\"bzip2-1.0.5\",\"bzip2-1.0.6\",\"Caldera\",\"CECILL-1.0\",\"CECILL-1.1\",\"CECILL-2.0\",\"CECILL-2.1\",\"CECILL-B\",\"CECILL-C\",\"ClArtistic\",\"MIT-CMU\",\"CNRI-Jython\",\"CNRI-Python\",\"CNRI-Python-GPL-Compatible\",\"CPOL-1.02\",\"CDDL-1.0\",\"CDDL-1.1\",\"CPAL-1.0\",\"CPL-1.0\",\"CATOSL-1.1\",\"Condor-1.1\",\"CC-BY-1.0\",\"CC-BY-2.0\",\"CC-BY-2.5\",\"CC-BY-3.0\",\"CC-BY-4.0\",\"CC-BY-ND-1.0\",\"CC-BY-ND-2.0\",\"CC-BY-ND-2.5\",\"CC-BY-ND-3.0\",\"CC-BY-ND-4.0\",\"CC-BY-NC-1.0\",\"CC-BY-NC-2.0\",\"CC-BY-NC-2.5\",\"CC-BY-NC-3.0\",\"CC-BY-NC-4.0\",\"CC-BY-NC-ND-1.0\",\"CC-BY-NC-ND-2.0\",\"CC-BY-NC-ND-2.5\",\"CC-BY-NC-ND-3.0\",\"CC-BY-NC-ND-4.0\",\"CC-BY-NC-SA-1.0\",\"CC-BY-NC-SA-2.0\",\"CC-BY-NC-SA-2.5\",\"CC-BY-NC-SA-3.0\",\"CC-BY-NC-SA-4.0\",\"CC-BY-SA-1.0\",\"CC-BY-SA-2.0\",\"CC-BY-SA-2.5\",\"CC-BY-SA-3.0\",\"CC-BY-SA-4.0\",\"CC0-1.0\",\"Crossword\",\"CrystalStacker\",\"CUA-OPL-1.0\",\"Cube\",\"curl\",\"D-FSL-1.0\",\"diffmark\",\"WTFPL\",\"DOC\",\"Dotseqn\",\"DSDP\",\"dvipdfm\",\"EPL-1.0\",\"ECL-1.0\",\"ECL-2.0\",\"eGenix\",\"EFL-1.0\",\"EFL-2.0\",\"MIT-advertising\",\"MIT-enna\",\"Entessa\",\"ErlPL-1.1\",\"EUDatagrid\",\"EUPL-1.0\",\"EUPL-1.1\",\"Eurosym\",\"Fair\",\"MIT-feh\",\"Frameworx-1.0\",\"FreeImage\",\"FTL\",\"FSFAP\",\"FSFUL\",\"FSFULLR\",\"Giftware\",\"GL2PS\",\"Glulxe\",\"AGPL-3.0\",\"GFDL-1.1\",\"GFDL-1.2\",\"GFDL-1.3\",\"GPL-1.0\",\"GPL-2.0\",\"GPL-3.0\",\"LGPL-2.1\",\"LGPL-3.0\",\"LGPL-2.0\",\"gnuplot\",\"gSOAP-1.3b\",\"HaskellReport\",\"HPND\",\"IBM-pibs\",\"IPL-1.0\",\"ICU\",\"ImageMagick\",\"iMatix\",\"Imlib2\",\"IJG\",\"Info-ZIP\",\"Intel-ACPI\",\"Intel\",\"Interbase-1.0\",\"IPA\",\"ISC\",\"JasPer-2.0\",\"JSON\",\"LPPL-1.0\",\"LPPL-1.1\",\"LPPL-1.2\",\"LPPL-1.3a\",\"LPPL-1.3c\",\"Latex2e\",\"BSD-3-Clause-LBNL\",\"Leptonica\",\"LGPLLR\",\"Libpng\",\"libtiff\",\"LAL-1.2\",\"LAL-1.3\",\"LiLiQ-P-1.1\",\"LiLiQ-Rplus-1.1\",\"LiLiQ-R-1.1\",\"LPL-1.02\",\"LPL-1.0\",\"MakeIndex\",\"MTLL\",\"MS-PL\",\"MS-RL\",\"MirOS\",\"MITNFA\",\"MIT\",\"Motosoto\",\"MPL-1.0\",\"MPL-1.1\",\"MPL-2.0\",\"MPL-2.0-no-copyleft-exception\",\"mpich2\",\"Multics\",\"Mup\",\"NASA-1.3\",\"Naumen\",\"NBPL-1.0\",\"NetCDF\",\"NGPL\",\"NOSL\",\"NPL-1.0\",\"NPL-1.1\",\"Newsletr\",\"NLPL\",\"Nokia\",\"NPOSL-3.0\",\"NLOD-1.0\",\"Noweb\",\"NRL\",\"NTP\",\"Nunit\",\"OCLC-2.0\",\"ODbL-1.0\",\"PDDL-1.0\",\"OCCT-PL\",\"OGTSL\",\"OLDAP-2.2.2\",\"OLDAP-1.1\",\"OLDAP-1.2\",\"OLDAP-1.3\",\"OLDAP-1.4\",\"OLDAP-2.0\",\"OLDAP-2.0.1\",\"OLDAP-2.1\",\"OLDAP-2.2\",\"OLDAP-2.2.1\",\"OLDAP-2.3\",\"OLDAP-2.4\",\"OLDAP-2.5\",\"OLDAP-2.6\",\"OLDAP-2.7\",\"OLDAP-2.8\",\"OML\",\"OPL-1.0\",\"OSL-1.0\",\"OSL-1.1\",\"OSL-2.0\",\"OSL-2.1\",\"OSL-3.0\",\"OpenSSL\",\"OSET-PL-2.1\",\"PHP-3.0\",\"PHP-3.01\",\"Plexus\",\"PostgreSQL\",\"psfrag\",\"psutils\",\"Python-2.0\",\"QPL-1.0\",\"Qhull\",\"Rdisc\",\"RPSL-1.0\",\"RPL-1.1\",\"RPL-1.5\",\"RHeCos-1.1\",\"RSCPL\",\"RSA-MD\",\"Ruby\",\"SAX-PD\",\"Saxpath\",\"SCEA\",\"SWL\",\"SMPPL\",\"Sendmail\",\"SGI-B-1.0\",\"SGI-B-1.1\",\"SGI-B-2.0\",\"OFL-1.0\",\"OFL-1.1\",\"SimPL-2.0\",\"Sleepycat\",\"SNIA\",\"Spencer-86\",\"Spencer-94\",\"Spencer-99\",\"SMLNJ\",\"SugarCRM-1.1.3\",\"SISSL\",\"SISSL-1.2\",\"SPL-1.0\",\"Watcom-1.0\",\"TCL\",\"Unlicense\",\"TMate\",\"TORQUE-1.1\",\"TOSL\",\"Unicode-TOU\",\"UPL-1.0\",\"NCSA\",\"Vim\",\"VOSTROM\",\"VSL-1.0\",\"W3C-19980720\",\"W3C\",\"Wsuipa\",\"Xnet\",\"X11\",\"Xerox\",\"XFree86-1.1\",\"xinetd\",\"xpp\",\"XSkat\",\"YPL-1.0\",\"YPL-1.1\",\"Zed\",\"Zend-2.0\",\"Zimbra-1.3\",\"Zimbra-1.4\",\"Zlib\",\"zlib-acknowledgement\",\"ZPL-1.1\",\"ZPL-2.0\",\"ZPL-2.1\",\"BSD-3-Clause-No-Nuclear-License\",\"BSD-3-Clause-No-Nuclear-Warranty\",\"BSD-3-Clause-No-Nuclear-License-2014\",\"eCos-2.0\",\"GPL-2.0-with-autoconf-exception\",\"GPL-2.0-with-bison-exception\",\"GPL-2.0-with-classpath-exception\",\"GPL-2.0-with-font-exception\",\"GPL-2.0-with-GCC-exception\",\"GPL-3.0-with-autoconf-exception\",\"GPL-3.0-with-GCC-exception\",\"StandardML-NJ\",\"WXwindows\"]"); +Range.prototype.toString = function () { + return this.range +} -/***/ }), -/* 529 */ -/***/ (function(module, exports, __webpack_require__) { +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[HYPHENRANGELOOSE] : re[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[COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, re[COMPARATORTRIM]) -"use strict"; + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace) -var url = __webpack_require__(452) -var gitHosts = __webpack_require__(530) -var GitHost = module.exports = __webpack_require__(531) + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace) -var protocolToRepresentationMap = { - 'git+ssh': 'sshurl', - 'git+https': 'https', - 'ssh': 'sshurl', - 'git': 'git' + // normalize spaces + range = range.split(/\s+/).join(' ') + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[COMPARATORLOOSE] : re[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) + + return set } -function protocolToRepresentation (protocol) { - if (protocol.substr(-1) === ':') protocol = protocol.slice(0, -1) - return protocolToRepresentationMap[protocol] || protocol +Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some(function (thisComparators) { + return thisComparators.every(function (thisComparator) { + return range.set.some(function (rangeComparators) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options) + }) + }) + }) + }) } -var authProtocols = { - 'git:': true, - 'https:': true, - 'git+https:': true, - 'http:': true, - 'git+http:': true +// 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(' ') + }) } -var cache = {} +// 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 +} -module.exports.fromUrl = function (giturl, opts) { - var key = giturl + JSON.stringify(opts || {}) +function isX (id) { + return !id || id.toLowerCase() === 'x' || id === '*' +} - if (!(key in cache)) { - cache[key] = fromUrl(giturl, opts) - } +// ~, ~> --> * (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(' ') +} - return cache[key] +function replaceTilde (comp, options) { + var r = options.loose ? re[TILDELOOSE] : re[TILDE] + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr) + var ret + + 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' + } + + debug('tilde return', ret) + return ret + }) } -function fromUrl (giturl, opts) { - if (giturl == null || giturl === '') return - var url = fixupUnqualifiedGist( - isGitHubShorthand(giturl) ? 'github:' + giturl : giturl - ) - var parsed = parseGitUrl(url) - var shortcutMatch = url.match(new RegExp('^([^:]+):(?:(?:[^@:]+(?:[^@]+)?@)?([^/]*))[/](.+?)(?:[.]git)?($|#)')) - var matches = Object.keys(gitHosts).map(function (gitHostName) { - try { - var gitHostInfo = gitHosts[gitHostName] - var auth = null - if (parsed.auth && authProtocols[parsed.protocol]) { - auth = decodeURIComponent(parsed.auth) +// ^ --> * (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(' ') +} + +function replaceCaret (comp, options) { + debug('caret', comp, options) + var r = options.loose ? re[CARETLOOSE] : re[CARET] + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr) + var ret + + 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' } - var committish = parsed.hash ? decodeURIComponent(parsed.hash.substr(1)) : null - var user = null - var project = null - var defaultRepresentation = null - if (shortcutMatch && shortcutMatch[1] === gitHostName) { - user = shortcutMatch[2] && decodeURIComponent(shortcutMatch[2]) - project = decodeURIComponent(shortcutMatch[3]) - defaultRepresentation = 'shortcut' + } 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 { - if (parsed.host !== gitHostInfo.domain) return - if (!gitHostInfo.protocols_re.test(parsed.protocol)) return - if (!parsed.path) return - var pathmatch = gitHostInfo.pathmatch - var matched = parsed.path.match(pathmatch) - if (!matched) return - if (matched[1] != null) user = decodeURIComponent(matched[1].replace(/^:/, '')) - if (matched[2] != null) project = decodeURIComponent(matched[2]) - defaultRepresentation = protocolToRepresentation(parsed.protocol) + 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' } - return new GitHost(gitHostName, user, auth, project, committish, defaultRepresentation, opts) - } catch (ex) { - if (!(ex instanceof URIError)) throw ex } - }).filter(function (gitHostInfo) { return gitHostInfo }) - if (matches.length !== 1) return - return matches[0] + + debug('caret return', ret) + return ret + }) } -function isGitHubShorthand (arg) { - // Note: This does not fully test the git ref format. - // See https://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html - // - // The only way to do this properly would be to shell out to - // git-check-ref-format, and as this is a fast sync function, - // we don't want to do that. Just let git fail if it turns - // out that the commit-ish is invalid. - // GH usernames cannot start with . or - - return /^[^:@%/\s.-][^:@%/\s]*[/][^:@\s/%]+(?:#.*)?$/.test(arg) +function replaceXRanges (comp, options) { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options) + }).join(' ') } -function fixupUnqualifiedGist (giturl) { - // necessary for round-tripping gists - var parsed = url.parse(giturl) - if (parsed.protocol === 'gist:' && parsed.host && !parsed.path) { - return parsed.protocol + '/' + parsed.host +function replaceXRange (comp, options) { + comp = comp.trim() + var r = options.loose ? re[XRANGELOOSE] : re[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 = '' + } + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<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 + } + } 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 + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } + + debug('xRange return', ret) + + return ret + }) +} + +// 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[STAR], '') +} + +// This function is passed to string.replace(re[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 { - return giturl + from = '>=' + from + } + + 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 + } + + 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') { + version = new SemVer(version, this.options) + } + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } } + return false } -function parseGitUrl (giturl) { - if (typeof giturl !== 'string') giturl = '' + giturl - var matched = giturl.match(/^([^@]+)@([^:/]+):[/]?((?:[^/]+[/])?[^/]+?)(?:[.]git)?(#.*)?$/) - if (!matched) return url.parse(giturl) - return { - protocol: 'git+ssh:', - slashes: true, - auth: matched[1], - host: matched[2], - port: null, - hostname: matched[2], - hash: matched[4], - search: null, - query: null, - pathname: '/' + matched[3], - path: '/' + matched[3], - href: 'git+ssh://' + matched[1] + '@' + matched[2] + - '/' + matched[3] + (matched[4] || '') +function testSet (set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } } -} + 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 + } -/***/ }), -/* 530 */ -/***/ (function(module, exports, __webpack_require__) { + 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 + } + } + } -"use strict"; + // Version has a -pre, but it's not one of the ones we like. + return false + } + return true +} -var gitHosts = module.exports = { - github: { - // First two are insecure and generally shouldn't be used any more, but - // they are still supported. - 'protocols': [ 'git', 'http', 'git+ssh', 'git+https', 'ssh', 'https' ], - 'domain': 'github.com', - 'treepath': 'tree', - 'filetemplate': 'https://{auth@}raw.githubusercontent.com/{user}/{project}/{committish}/{path}', - 'bugstemplate': 'https://{domain}/{user}/{project}/issues', - 'gittemplate': 'git://{auth@}{domain}/{user}/{project}.git{#committish}', - 'tarballtemplate': 'https://{domain}/{user}/{project}/archive/{committish}.tar.gz' - }, - bitbucket: { - 'protocols': [ 'git+ssh', 'git+https', 'ssh', 'https' ], - 'domain': 'bitbucket.org', - 'treepath': 'src', - 'tarballtemplate': 'https://{domain}/{user}/{project}/get/{committish}.tar.gz' - }, - gitlab: { - 'protocols': [ 'git+ssh', 'git+https', 'ssh', 'https' ], - 'domain': 'gitlab.com', - 'treepath': 'tree', - 'docstemplate': 'https://{domain}/{user}/{project}{/tree/committish}#README', - 'bugstemplate': 'https://{domain}/{user}/{project}/issues', - 'tarballtemplate': 'https://{domain}/{user}/{project}/repository/archive.tar.gz?ref={committish}' - }, - gist: { - 'protocols': [ 'git', 'git+ssh', 'git+https', 'ssh', 'https' ], - 'domain': 'gist.github.com', - 'pathmatch': /^[/](?:([^/]+)[/])?([a-z0-9]+)(?:[.]git)?$/, - 'filetemplate': 'https://gist.githubusercontent.com/{user}/{project}/raw{/committish}/{path}', - 'bugstemplate': 'https://{domain}/{project}', - 'gittemplate': 'git://{domain}/{project}.git{#committish}', - 'sshtemplate': 'git@{domain}:/{project}.git{#committish}', - 'sshurltemplate': 'git+ssh://git@{domain}/{project}.git{#committish}', - 'browsetemplate': 'https://{domain}/{project}{/committish}', - 'docstemplate': 'https://{domain}/{project}{/committish}', - 'httpstemplate': 'git+https://{domain}/{project}.git{#committish}', - 'shortcuttemplate': '{type}:{project}{#committish}', - 'pathtemplate': '{project}{#committish}', - 'tarballtemplate': 'https://{domain}/{user}/{project}/archive/{committish}.tar.gz' +exports.satisfies = satisfies +function satisfies (version, range, options) { + try { + range = new Range(range, options) + } catch (er) { + return false } + return range.test(version) } -var gitHostDefaults = { - 'sshtemplate': 'git@{domain}:{user}/{project}.git{#committish}', - 'sshurltemplate': 'git+ssh://git@{domain}/{user}/{project}.git{#committish}', - 'browsetemplate': 'https://{domain}/{user}/{project}{/tree/committish}', - 'docstemplate': 'https://{domain}/{user}/{project}{/tree/committish}#readme', - 'httpstemplate': 'git+https://{auth@}{domain}/{user}/{project}.git{#committish}', - 'filetemplate': 'https://{domain}/{user}/{project}/raw/{committish}/{path}', - 'shortcuttemplate': '{type}:{user}/{project}{#committish}', - 'pathtemplate': '{user}/{project}{#committish}', - 'pathmatch': /^[/]([^/]+)[/]([^/]+?)(?:[.]git|[/])?$/ +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 } -Object.keys(gitHosts).forEach(function (name) { - Object.keys(gitHostDefaults).forEach(function (key) { - if (gitHosts[name][key]) return - gitHosts[name][key] = gitHostDefaults[key] +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) + } + } }) - gitHosts[name].protocols_re = RegExp('^(' + - gitHosts[name].protocols.map(function (protocol) { - return protocol.replace(/([\\+*{}()[\]$^|])/g, '\\$1') - }).join('|') + '):$') -}) + return min +} +exports.minVersion = minVersion +function minVersion (range, loose) { + range = new Range(range, loose) -/***/ }), -/* 531 */ -/***/ (function(module, exports, __webpack_require__) { + var minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } -"use strict"; + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } -var gitHosts = __webpack_require__(530) -var extend = Object.assign || __webpack_require__(29)._extend + minver = null + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] -var GitHost = module.exports = function (type, user, auth, project, committish, defaultRepresentation, opts) { - var gitHostInfo = this - gitHostInfo.type = type - Object.keys(gitHosts[type]).forEach(function (key) { - gitHostInfo[key] = gitHosts[type][key] - }) - gitHostInfo.user = user - gitHostInfo.auth = auth - gitHostInfo.project = project - gitHostInfo.committish = committish - gitHostInfo.default = defaultRepresentation - gitHostInfo.opts = opts || {} -} -GitHost.prototype = {} + 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) + } + }) + } -GitHost.prototype.hash = function () { - return this.committish ? '#' + this.committish : '' + if (minver && range.test(minver)) { + return minver + } + + return null } -GitHost.prototype._fill = function (template, opts) { - if (!template) return - var vars = extend({}, opts) - opts = extend(extend({}, this.opts), opts) - var self = this - Object.keys(this).forEach(function (key) { - if (self[key] != null && vars[key] == null) vars[key] = self[key] - }) - var rawAuth = vars.auth - var rawComittish = vars.committish - Object.keys(vars).forEach(function (key) { - vars[key] = encodeURIComponent(vars[key]) - }) - vars['auth@'] = rawAuth ? rawAuth + '@' : '' - if (opts.noCommittish) { - vars['#committish'] = '' - vars['/tree/committish'] = '' - vars['/comittish'] = '' - vars.comittish = '' - } else { - vars['#committish'] = rawComittish ? '#' + rawComittish : '' - vars['/tree/committish'] = vars.committish - ? '/' + vars.treepath + '/' + vars.committish - : '' - vars['/committish'] = vars.committish ? '/' + vars.committish : '' - vars.committish = vars.committish || 'master' - } - var res = template - Object.keys(vars).forEach(function (key) { - res = res.replace(new RegExp('[{]' + key + '[}]', 'g'), vars[key]) - }) - if (opts.noGitPlus) { - return res.replace(/^git[+]/, '') - } else { - return res +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 } } -GitHost.prototype.ssh = function (opts) { - return this._fill(this.sshtemplate, opts) +// 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) } -GitHost.prototype.sshurl = function (opts) { - return this._fill(this.sshurltemplate, opts) +// 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) } -GitHost.prototype.browse = function (opts) { - return this._fill(this.browsetemplate, opts) -} +exports.outside = outside +function outside (version, range, hilo, options) { + version = new SemVer(version, options) + range = new Range(range, options) -GitHost.prototype.docs = function (opts) { - return this._fill(this.docstemplate, opts) -} + 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 ">"') + } -GitHost.prototype.bugs = function (opts) { - return this._fill(this.bugstemplate, opts) -} + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false + } -GitHost.prototype.https = function (opts) { - return this._fill(this.httpstemplate, opts) -} + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. -GitHost.prototype.git = function (opts) { - return this._fill(this.gittemplate, opts) -} + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] -GitHost.prototype.shortcut = function (opts) { - return this._fill(this.shortcuttemplate, opts) -} + var high = null + var low = null -GitHost.prototype.path = function (opts) { - return this._fill(this.pathtemplate, opts) -} + 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 + } + }) -GitHost.prototype.tarball = function (opts) { - return this._fill(this.tarballtemplate, opts) + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // 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 } -GitHost.prototype.file = function (P, opts) { - return this._fill(this.filetemplate, extend({ - path: P.replace(/^[/]+/g, '') - }, opts)) +exports.prerelease = prerelease +function prerelease (version, options) { + var parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } -GitHost.prototype.getDefaultRepresentation = function () { - return this.default +exports.intersects = intersects +function intersects (r1, r2, options) { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) } -GitHost.prototype.toString = function (opts) { - return (this[this.default] || this.sshurl).call(this, opts) +exports.coerce = coerce +function coerce (version) { + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + var match = version.match(re[COERCE]) + + if (match == null) { + return null + } + + return parse(match[1] + + '.' + (match[2] || '0') + + '.' + (match[3] || '0')) } /***/ }), -/* 532 */ +/* 524 */ /***/ (function(module, exports, __webpack_require__) { -var core = __webpack_require__(533); -var async = __webpack_require__(535); -async.core = core; -async.isCore = function isCore(x) { return core[x]; }; -async.sync = __webpack_require__(540); +var parse = __webpack_require__(525); +var correct = __webpack_require__(527); -exports = async; -module.exports = async; +var genericWarning = ( + 'license should be ' + + 'a valid SPDX license expression (without "LicenseRef"), ' + + '"UNLICENSED", or ' + + '"SEE LICENSE IN "' +); +var fileReferenceRE = /^SEE LICEN[CS]E IN (.+)$/; -/***/ }), -/* 533 */ -/***/ (function(module, exports, __webpack_require__) { +function startsWith(prefix, string) { + return string.slice(0, prefix.length) === prefix; +} -var current = (process.versions && process.versions.node && process.versions.node.split('.')) || []; +function usesLicenseRef(ast) { + if (ast.hasOwnProperty('license')) { + var license = ast.license; + return ( + startsWith('LicenseRef', license) || + startsWith('DocumentRef', license) + ); + } else { + return ( + usesLicenseRef(ast.left) || + usesLicenseRef(ast.right) + ); + } +} -function specifierIncluded(specifier) { - var parts = specifier.split(' '); - var op = parts.length > 1 ? parts[0] : '='; - var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); +module.exports = function(argument) { + var ast; - for (var i = 0; i < 3; ++i) { - var cur = Number(current[i] || 0); - var ver = Number(versionParts[i] || 0); - if (cur === ver) { - continue; // eslint-disable-line no-restricted-syntax, no-continue - } - if (op === '<') { - return cur < ver; - } else if (op === '>=') { - return cur >= ver; - } else { - return false; - } + try { + ast = parse(argument); + } catch (e) { + var match + if ( + argument === 'UNLICENSED' || + argument === 'UNLICENCED' + ) { + return { + validForOldPackages: true, + validForNewPackages: true, + unlicensed: true + }; + } else if (match = fileReferenceRE.exec(argument)) { + return { + validForOldPackages: true, + validForNewPackages: true, + inFile: match[1] + }; + } else { + var result = { + validForOldPackages: false, + validForNewPackages: false, + warnings: [genericWarning] + }; + var corrected = correct(argument); + if (corrected) { + result.warnings.push( + 'license is similar to the valid expression "' + corrected + '"' + ); + } + return result; } - return op === '>='; -} + } + + if (usesLicenseRef(ast)) { + return { + validForNewPackages: false, + validForOldPackages: false, + spdx: true, + warnings: [genericWarning] + }; + } else { + return { + validForNewPackages: true, + validForOldPackages: true, + spdx: true + }; + } +}; -function matchesRange(range) { - var specifiers = range.split(/ ?&& ?/); - if (specifiers.length === 0) { return false; } - for (var i = 0; i < specifiers.length; ++i) { - if (!specifierIncluded(specifiers[i])) { return false; } - } - return true; -} -function versionIncluded(specifierValue) { - if (typeof specifierValue === 'boolean') { return specifierValue; } - if (specifierValue && typeof specifierValue === 'object') { - for (var i = 0; i < specifierValue.length; ++i) { - if (matchesRange(specifierValue[i])) { return true; } - } - return false; - } - return matchesRange(specifierValue); -} +/***/ }), +/* 525 */ +/***/ (function(module, exports, __webpack_require__) { -var data = __webpack_require__(534); +var parser = __webpack_require__(526).parser -var core = {}; -for (var mod in data) { // eslint-disable-line no-restricted-syntax - if (Object.prototype.hasOwnProperty.call(data, mod)) { - core[mod] = versionIncluded(data[mod]); - } +module.exports = function (argument) { + return parser.parse(argument) } -module.exports = core; /***/ }), -/* 534 */ -/***/ (function(module) { +/* 526 */ +/***/ (function(module, exports, __webpack_require__) { -module.exports = JSON.parse("{\"assert\":true,\"async_hooks\":\">= 8\",\"buffer_ieee754\":\"< 0.9.7\",\"buffer\":true,\"child_process\":true,\"cluster\":true,\"console\":true,\"constants\":true,\"crypto\":true,\"_debugger\":\"< 8\",\"dgram\":true,\"dns\":true,\"domain\":true,\"events\":true,\"freelist\":\"< 6\",\"fs\":true,\"fs/promises\":\">= 10 && < 10.1\",\"_http_agent\":\">= 0.11.1\",\"_http_client\":\">= 0.11.1\",\"_http_common\":\">= 0.11.1\",\"_http_incoming\":\">= 0.11.1\",\"_http_outgoing\":\">= 0.11.1\",\"_http_server\":\">= 0.11.1\",\"http\":true,\"http2\":\">= 8.8\",\"https\":true,\"inspector\":\">= 8.0.0\",\"_linklist\":\"< 8\",\"module\":true,\"net\":true,\"node-inspect/lib/_inspect\":\">= 7.6.0\",\"node-inspect/lib/internal/inspect_client\":\">= 7.6.0\",\"node-inspect/lib/internal/inspect_repl\":\">= 7.6.0\",\"os\":true,\"path\":true,\"perf_hooks\":\">= 8.5\",\"process\":\">= 1\",\"punycode\":true,\"querystring\":true,\"readline\":true,\"repl\":true,\"smalloc\":\">= 0.11.5 && < 3\",\"_stream_duplex\":\">= 0.9.4\",\"_stream_transform\":\">= 0.9.4\",\"_stream_wrap\":\">= 1.4.1\",\"_stream_passthrough\":\">= 0.9.4\",\"_stream_readable\":\">= 0.9.4\",\"_stream_writable\":\">= 0.9.4\",\"stream\":true,\"string_decoder\":true,\"sys\":true,\"timers\":true,\"_tls_common\":\">= 0.11.13\",\"_tls_legacy\":\">= 0.11.3 && < 10\",\"_tls_wrap\":\">= 0.11.3\",\"tls\":true,\"trace_events\":\">= 10\",\"tty\":true,\"url\":true,\"util\":true,\"v8/tools/arguments\":\">= 10\",\"v8/tools/codemap\":[\">= 4.4.0 && < 5\",\">= 5.2.0\"],\"v8/tools/consarray\":[\">= 4.4.0 && < 5\",\">= 5.2.0\"],\"v8/tools/csvparser\":[\">= 4.4.0 && < 5\",\">= 5.2.0\"],\"v8/tools/logreader\":[\">= 4.4.0 && < 5\",\">= 5.2.0\"],\"v8/tools/profile_view\":[\">= 4.4.0 && < 5\",\">= 5.2.0\"],\"v8/tools/splaytree\":[\">= 4.4.0 && < 5\",\">= 5.2.0\"],\"v8\":\">= 1\",\"vm\":true,\"worker_threads\":\">= 11.7\",\"zlib\":true}"); +/* WEBPACK VAR INJECTION */(function(module) {/* parser generated by jison 0.4.17 */ +/* + Returns a Parser object of the following structure: -/***/ }), -/* 535 */ -/***/ (function(module, exports, __webpack_require__) { + Parser: { + yy: {} + } -var core = __webpack_require__(533); -var fs = __webpack_require__(23); -var path = __webpack_require__(16); -var caller = __webpack_require__(536); -var nodeModulesPaths = __webpack_require__(537); -var normalizeOptions = __webpack_require__(539); + Parser.prototype: { + yy: {}, + trace: function(), + symbols_: {associative list: name ==> number}, + terminals_: {associative list: number ==> name}, + productions_: [...], + performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$), + table: [...], + defaultActions: {...}, + parseError: function(str, hash), + parse: function(input), -var defaultIsFile = function isFile(file, cb) { - fs.stat(file, function (err, stat) { - if (!err) { - return cb(null, stat.isFile() || stat.isFIFO()); - } - if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); - return cb(err); - }); -}; + lexer: { + EOF: 1, + parseError: function(str, hash), + setInput: function(input), + input: function(), + unput: function(str), + more: function(), + less: function(n), + pastInput: function(), + upcomingInput: function(), + showPosition: function(), + test_match: function(regex_match_array, rule_index), + next: function(), + lex: function(), + begin: function(condition), + popState: function(), + _currentRules: function(), + topState: function(), + pushState: function(condition), -module.exports = function resolve(x, options, callback) { - var cb = callback; - var opts = options; - if (typeof options === 'function') { - cb = opts; - opts = {}; - } - if (typeof x !== 'string') { - var err = new TypeError('Path must be a string.'); - return process.nextTick(function () { - cb(err); - }); + options: { + ranges: boolean (optional: true ==> token location info will include a .range[] member) + flex: boolean (optional: true ==> flex-like lexing behaviour where the rules are tested exhaustively to find the longest match) + backtrack_lexer: boolean (optional: true ==> lexer regexes are tested in order and for each matching regex the action code is invoked; the lexer terminates the scan when a token is returned by the action code) + }, + + performAction: function(yy, yy_, $avoiding_name_collisions, YY_START), + rules: [...], + conditions: {associative list: name ==> set}, } + } - opts = normalizeOptions(x, opts); - var isFile = opts.isFile || defaultIsFile; - var readFile = opts.readFile || fs.readFile; + token location info (@$, _$, etc.): { + first_line: n, + last_line: n, + first_column: n, + last_column: n, + range: [start_number, end_number] (where the numbers are indexes into the input string, regular zero-based) + } - var extensions = opts.extensions || ['.js']; - var basedir = opts.basedir || path.dirname(caller()); - var parent = opts.filename || basedir; - opts.paths = opts.paths || []; + the parseError function receives a 'hash' object with these members for lexer and parser errors: { + text: (matched text) + token: (the produced terminal token, if any) + line: (yylineno) + } + while parser (grammar) errors will also provide these members, i.e. parser errors deliver a superset of attributes: { + loc: (yylloc) + expected: (string describing the set of expected tokens) + recoverable: (boolean: TRUE when the parser has a error recovery rule available for this particular error) + } +*/ +var spdxparse = (function(){ +var o=function(k,v,o,l){for(o=o||{},l=k.length;l--;o[k[l]]=v);return o},$V0=[1,5],$V1=[1,6],$V2=[1,7],$V3=[1,4],$V4=[1,9],$V5=[1,10],$V6=[5,14,15,17],$V7=[5,12,14,15,17]; +var parser = {trace: function trace() { }, +yy: {}, +symbols_: {"error":2,"start":3,"expression":4,"EOS":5,"simpleExpression":6,"LICENSE":7,"PLUS":8,"LICENSEREF":9,"DOCUMENTREF":10,"COLON":11,"WITH":12,"EXCEPTION":13,"AND":14,"OR":15,"OPEN":16,"CLOSE":17,"$accept":0,"$end":1}, +terminals_: {2:"error",5:"EOS",7:"LICENSE",8:"PLUS",9:"LICENSEREF",10:"DOCUMENTREF",11:"COLON",12:"WITH",13:"EXCEPTION",14:"AND",15:"OR",16:"OPEN",17:"CLOSE"}, +productions_: [0,[3,2],[6,1],[6,2],[6,1],[6,3],[4,1],[4,3],[4,3],[4,3],[4,3]], +performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate /* action[1] */, $$ /* vstack */, _$ /* lstack */) { +/* this == yyval */ - // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory - var absoluteStart = path.resolve(basedir); +var $0 = $$.length - 1; +switch (yystate) { +case 1: +return this.$ = $$[$0-1] +break; +case 2: case 4: case 5: +this.$ = {license: yytext} +break; +case 3: +this.$ = {license: $$[$0-1], plus: true} +break; +case 6: +this.$ = $$[$0] +break; +case 7: +this.$ = {exception: $$[$0]} +this.$.license = $$[$0-2].license +if ($$[$0-2].hasOwnProperty('plus')) { + this.$.plus = $$[$0-2].plus +} +break; +case 8: +this.$ = {conjunction: 'and', left: $$[$0-2], right: $$[$0]} +break; +case 9: +this.$ = {conjunction: 'or', left: $$[$0-2], right: $$[$0]} +break; +case 10: +this.$ = $$[$0-1] +break; +} +}, +table: [{3:1,4:2,6:3,7:$V0,9:$V1,10:$V2,16:$V3},{1:[3]},{5:[1,8],14:$V4,15:$V5},o($V6,[2,6],{12:[1,11]}),{4:12,6:3,7:$V0,9:$V1,10:$V2,16:$V3},o($V7,[2,2],{8:[1,13]}),o($V7,[2,4]),{11:[1,14]},{1:[2,1]},{4:15,6:3,7:$V0,9:$V1,10:$V2,16:$V3},{4:16,6:3,7:$V0,9:$V1,10:$V2,16:$V3},{13:[1,17]},{14:$V4,15:$V5,17:[1,18]},o($V7,[2,3]),{9:[1,19]},o($V6,[2,8]),o([5,15,17],[2,9],{14:$V4}),o($V6,[2,7]),o($V6,[2,10]),o($V7,[2,5])], +defaultActions: {8:[2,1]}, +parseError: function parseError(str, hash) { + if (hash.recoverable) { + this.trace(str); + } else { + function _parseError (msg, hash) { + this.message = msg; + this.hash = hash; + } + _parseError.prototype = Error; - if (opts.preserveSymlinks === false) { - fs.realpath(absoluteStart, function (realPathErr, realStart) { - if (realPathErr && realPathErr.code !== 'ENOENT') cb(err); - else init(realPathErr ? absoluteStart : realStart); - }); + throw new _parseError(str, hash); + } +}, +parse: function parse(input) { + var self = this, stack = [0], tstack = [], vstack = [null], lstack = [], table = this.table, yytext = '', yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1; + var args = lstack.slice.call(arguments, 1); + var lexer = Object.create(this.lexer); + var sharedState = { yy: {} }; + for (var k in this.yy) { + if (Object.prototype.hasOwnProperty.call(this.yy, k)) { + sharedState.yy[k] = this.yy[k]; + } + } + lexer.setInput(input, sharedState.yy); + sharedState.yy.lexer = lexer; + sharedState.yy.parser = this; + if (typeof lexer.yylloc == 'undefined') { + lexer.yylloc = {}; + } + var yyloc = lexer.yylloc; + lstack.push(yyloc); + var ranges = lexer.options && lexer.options.ranges; + if (typeof sharedState.yy.parseError === 'function') { + this.parseError = sharedState.yy.parseError; } else { - init(absoluteStart); + this.parseError = Object.getPrototypeOf(this).parseError; } - - var res; - function init(basedir) { - if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { - res = path.resolve(basedir, x); - if (x === '..' || x.slice(-1) === '/') res += '/'; - if ((/\/$/).test(x) && res === basedir) { - loadAsDirectory(res, opts.package, onfile); - } else loadAsFile(res, opts.package, onfile); - } else loadNodeModules(x, basedir, function (err, n, pkg) { - if (err) cb(err); - else if (n) cb(null, n, pkg); - else if (core[x]) return cb(null, x); - else { - var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); - moduleError.code = 'MODULE_NOT_FOUND'; - cb(moduleError); - } - }); + function popStack(n) { + stack.length = stack.length - 2 * n; + vstack.length = vstack.length - n; + lstack.length = lstack.length - n; } - - function onfile(err, m, pkg) { - if (err) cb(err); - else if (m) cb(null, m, pkg); - else loadAsDirectory(res, function (err, d, pkg) { - if (err) cb(err); - else if (d) cb(null, d, pkg); - else { - var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); - moduleError.code = 'MODULE_NOT_FOUND'; - cb(moduleError); + _token_stack: + var lex = function () { + var token; + token = lexer.lex() || EOF; + if (typeof token !== 'number') { + token = self.symbols_[token] || token; } - }); + return token; + }; + var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected; + while (true) { + state = stack[stack.length - 1]; + if (this.defaultActions[state]) { + action = this.defaultActions[state]; + } else { + if (symbol === null || typeof symbol == 'undefined') { + symbol = lex(); + } + action = table[state] && table[state][symbol]; + } + if (typeof action === 'undefined' || !action.length || !action[0]) { + var errStr = ''; + expected = []; + for (p in table[state]) { + if (this.terminals_[p] && p > TERROR) { + expected.push('\'' + this.terminals_[p] + '\''); + } + } + if (lexer.showPosition) { + errStr = 'Parse error on line ' + (yylineno + 1) + ':\n' + lexer.showPosition() + '\nExpecting ' + expected.join(', ') + ', got \'' + (this.terminals_[symbol] || symbol) + '\''; + } else { + errStr = 'Parse error on line ' + (yylineno + 1) + ': Unexpected ' + (symbol == EOF ? 'end of input' : '\'' + (this.terminals_[symbol] || symbol) + '\''); + } + this.parseError(errStr, { + text: lexer.match, + token: this.terminals_[symbol] || symbol, + line: lexer.yylineno, + loc: yyloc, + expected: expected + }); + } + if (action[0] instanceof Array && action.length > 1) { + throw new Error('Parse Error: multiple actions possible at state: ' + state + ', token: ' + symbol); + } + switch (action[0]) { + case 1: + stack.push(symbol); + vstack.push(lexer.yytext); + lstack.push(lexer.yylloc); + stack.push(action[1]); + symbol = null; + if (!preErrorSymbol) { + yyleng = lexer.yyleng; + yytext = lexer.yytext; + yylineno = lexer.yylineno; + yyloc = lexer.yylloc; + if (recovering > 0) { + recovering--; + } + } else { + symbol = preErrorSymbol; + preErrorSymbol = null; + } + break; + case 2: + len = this.productions_[action[1]][1]; + yyval.$ = vstack[vstack.length - len]; + yyval._$ = { + first_line: lstack[lstack.length - (len || 1)].first_line, + last_line: lstack[lstack.length - 1].last_line, + first_column: lstack[lstack.length - (len || 1)].first_column, + last_column: lstack[lstack.length - 1].last_column + }; + if (ranges) { + yyval._$.range = [ + lstack[lstack.length - (len || 1)].range[0], + lstack[lstack.length - 1].range[1] + ]; + } + r = this.performAction.apply(yyval, [ + yytext, + yyleng, + yylineno, + sharedState.yy, + action[1], + vstack, + lstack + ].concat(args)); + if (typeof r !== 'undefined') { + return r; + } + if (len) { + stack = stack.slice(0, -1 * len * 2); + vstack = vstack.slice(0, -1 * len); + lstack = lstack.slice(0, -1 * len); + } + stack.push(this.productions_[action[1]][0]); + vstack.push(yyval.$); + lstack.push(yyval._$); + newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; + stack.push(newState); + break; + case 3: + return true; + } } + return true; +}}; +/* generated by jison-lex 0.3.4 */ +var lexer = (function(){ +var lexer = ({ - function loadAsFile(x, thePackage, callback) { - var loadAsFilePackage = thePackage; - var cb = callback; - if (typeof loadAsFilePackage === 'function') { - cb = loadAsFilePackage; - loadAsFilePackage = undefined; +EOF:1, + +parseError:function parseError(str, hash) { + if (this.yy.parser) { + this.yy.parser.parseError(str, hash); + } else { + throw new Error(str); } + }, - var exts = [''].concat(extensions); - load(exts, x, loadAsFilePackage); +// resets the lexer, sets new input +setInput:function (input, yy) { + this.yy = yy || this.yy || {}; + this._input = input; + this._more = this._backtrack = this.done = false; + this.yylineno = this.yyleng = 0; + this.yytext = this.matched = this.match = ''; + this.conditionStack = ['INITIAL']; + this.yylloc = { + first_line: 1, + first_column: 0, + last_line: 1, + last_column: 0 + }; + if (this.options.ranges) { + this.yylloc.range = [0,0]; + } + this.offset = 0; + return this; + }, - function load(exts, x, loadPackage) { - if (exts.length === 0) return cb(null, undefined, loadPackage); - var file = x + exts[0]; +// consumes and returns one char from the input +input:function () { + var ch = this._input[0]; + this.yytext += ch; + this.yyleng++; + this.offset++; + this.match += ch; + this.matched += ch; + var lines = ch.match(/(?:\r\n?|\n).*/g); + if (lines) { + this.yylineno++; + this.yylloc.last_line++; + } else { + this.yylloc.last_column++; + } + if (this.options.ranges) { + this.yylloc.range[1]++; + } - var pkg = loadPackage; - if (pkg) onpkg(null, pkg); - else loadpkg(path.dirname(file), onpkg); + this._input = this._input.slice(1); + return ch; + }, - function onpkg(err, pkg_, dir) { - pkg = pkg_; - if (err) return cb(err); - if (dir && pkg && opts.pathFilter) { - var rfile = path.relative(dir, file); - var rel = rfile.slice(0, rfile.length - exts[0].length); - var r = opts.pathFilter(pkg, x, rel); - if (r) return load( - [''].concat(extensions.slice()), - path.resolve(dir, r), - pkg - ); - } - isFile(file, onex); - } - function onex(err, ex) { - if (err) return cb(err); - if (ex) return cb(null, file, pkg); - load(exts.slice(1), x, pkg); - } - } - } +// unshifts one char (or a string) into the input +unput:function (ch) { + var len = ch.length; + var lines = ch.split(/(?:\r\n?|\n)/g); - function loadpkg(dir, cb) { - if (dir === '' || dir === '/') return cb(null); - if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { - return cb(null); + this._input = ch + this._input; + this.yytext = this.yytext.substr(0, this.yytext.length - len); + //this.yyleng -= len; + this.offset -= len; + var oldLines = this.match.split(/(?:\r\n?|\n)/g); + this.match = this.match.substr(0, this.match.length - 1); + this.matched = this.matched.substr(0, this.matched.length - 1); + + if (lines.length - 1) { + this.yylineno -= lines.length - 1; } - if ((/[/\\]node_modules[/\\]*$/).test(dir)) return cb(null); + var r = this.yylloc.range; - var pkgfile = path.join(dir, 'package.json'); - isFile(pkgfile, function (err, ex) { - // on err, ex is false - if (!ex) return loadpkg(path.dirname(dir), cb); + this.yylloc = { + first_line: this.yylloc.first_line, + last_line: this.yylineno + 1, + first_column: this.yylloc.first_column, + last_column: lines ? + (lines.length === oldLines.length ? this.yylloc.first_column : 0) + + oldLines[oldLines.length - lines.length].length - lines[0].length : + this.yylloc.first_column - len + }; - readFile(pkgfile, function (err, body) { - if (err) cb(err); - try { var pkg = JSON.parse(body); } catch (jsonErr) {} + if (this.options.ranges) { + this.yylloc.range = [r[0], r[0] + this.yyleng - len]; + } + this.yyleng = this.yytext.length; + return this; + }, - if (pkg && opts.packageFilter) { - pkg = opts.packageFilter(pkg, pkgfile); - } - cb(null, pkg, dir); +// When called from action, caches matched text and appends it on next action +more:function () { + this._more = true; + return this; + }, + +// When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead. +reject:function () { + if (this.options.backtrack_lexer) { + this._backtrack = true; + } else { + return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n' + this.showPosition(), { + text: "", + token: null, + line: this.yylineno }); - }); - } - function loadAsDirectory(x, loadAsDirectoryPackage, callback) { - var cb = callback; - var fpkg = loadAsDirectoryPackage; - if (typeof fpkg === 'function') { - cb = fpkg; - fpkg = opts.package; } + return this; + }, - var pkgfile = path.join(x, 'package.json'); - isFile(pkgfile, function (err, ex) { - if (err) return cb(err); - if (!ex) return loadAsFile(path.join(x, 'index'), fpkg, cb); - - readFile(pkgfile, function (err, body) { - if (err) return cb(err); - try { - var pkg = JSON.parse(body); - } catch (jsonErr) {} - - if (opts.packageFilter) { - pkg = opts.packageFilter(pkg, pkgfile); - } - - if (pkg.main) { - if (typeof pkg.main !== 'string') { - var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); - mainError.code = 'INVALID_PACKAGE_MAIN'; - return cb(mainError); - } - if (pkg.main === '.' || pkg.main === './') { - pkg.main = 'index'; - } - loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) { - if (err) return cb(err); - if (m) return cb(null, m, pkg); - if (!pkg) return loadAsFile(path.join(x, 'index'), pkg, cb); +// retain first n characters of the match +less:function (n) { + this.unput(this.match.slice(n)); + }, - var dir = path.resolve(x, pkg.main); - loadAsDirectory(dir, pkg, function (err, n, pkg) { - if (err) return cb(err); - if (n) return cb(null, n, pkg); - loadAsFile(path.join(x, 'index'), pkg, cb); - }); - }); - return; - } +// displays already matched input, i.e. for error messages +pastInput:function () { + var past = this.matched.substr(0, this.matched.length - this.match.length); + return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, ""); + }, - loadAsFile(path.join(x, '/index'), pkg, cb); - }); - }); - } +// displays upcoming input, i.e. for error messages +upcomingInput:function () { + var next = this.match; + if (next.length < 20) { + next += this._input.substr(0, 20-next.length); + } + return (next.substr(0,20) + (next.length > 20 ? '...' : '')).replace(/\n/g, ""); + }, - function processDirs(cb, dirs) { - if (dirs.length === 0) return cb(null, undefined); - var dir = dirs[0]; +// displays the character position where the lexing error occurred, i.e. for error messages +showPosition:function () { + var pre = this.pastInput(); + var c = new Array(pre.length + 1).join("-"); + return pre + this.upcomingInput() + "\n" + c + "^"; + }, - var file = path.join(dir, x); - loadAsFile(file, opts.package, onfile); +// test the lexed token: return FALSE when not a match, otherwise return token +test_match:function (match, indexed_rule) { + var token, + lines, + backup; - function onfile(err, m, pkg) { - if (err) return cb(err); - if (m) return cb(null, m, pkg); - loadAsDirectory(path.join(dir, x), opts.package, ondir); + if (this.options.backtrack_lexer) { + // save context + backup = { + yylineno: this.yylineno, + yylloc: { + first_line: this.yylloc.first_line, + last_line: this.last_line, + first_column: this.yylloc.first_column, + last_column: this.yylloc.last_column + }, + yytext: this.yytext, + match: this.match, + matches: this.matches, + matched: this.matched, + yyleng: this.yyleng, + offset: this.offset, + _more: this._more, + _input: this._input, + yy: this.yy, + conditionStack: this.conditionStack.slice(0), + done: this.done + }; + if (this.options.ranges) { + backup.yylloc.range = this.yylloc.range.slice(0); + } } - function ondir(err, n, pkg) { - if (err) return cb(err); - if (n) return cb(null, n, pkg); - processDirs(cb, dirs.slice(1)); + lines = match[0].match(/(?:\r\n?|\n).*/g); + if (lines) { + this.yylineno += lines.length; } - } - function loadNodeModules(x, start, cb) { - processDirs(cb, nodeModulesPaths(start, opts, x)); - } -}; + this.yylloc = { + first_line: this.yylloc.last_line, + last_line: this.yylineno + 1, + first_column: this.yylloc.last_column, + last_column: lines ? + lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : + this.yylloc.last_column + match[0].length + }; + this.yytext += match[0]; + this.match += match[0]; + this.matches = match; + this.yyleng = this.yytext.length; + if (this.options.ranges) { + this.yylloc.range = [this.offset, this.offset += this.yyleng]; + } + this._more = false; + this._backtrack = false; + this._input = this._input.slice(match[0].length); + this.matched += match[0]; + token = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]); + if (this.done && this._input) { + this.done = false; + } + if (token) { + return token; + } else if (this._backtrack) { + // recover context + for (var k in backup) { + this[k] = backup[k]; + } + return false; // rule action called reject() implying the next rule should be tested instead. + } + return false; + }, +// return next match in input +next:function () { + if (this.done) { + return this.EOF; + } + if (!this._input) { + this.done = true; + } -/***/ }), -/* 536 */ -/***/ (function(module, exports) { + var token, + match, + tempMatch, + index; + if (!this._more) { + this.yytext = ''; + this.match = ''; + } + var rules = this._currentRules(); + for (var i = 0; i < rules.length; i++) { + tempMatch = this._input.match(this.rules[rules[i]]); + if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { + match = tempMatch; + index = i; + if (this.options.backtrack_lexer) { + token = this.test_match(tempMatch, rules[i]); + if (token !== false) { + return token; + } else if (this._backtrack) { + match = false; + continue; // rule action called reject() implying a rule MISmatch. + } else { + // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace) + return false; + } + } else if (!this.options.flex) { + break; + } + } + } + if (match) { + token = this.test_match(match, rules[index]); + if (token !== false) { + return token; + } + // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace) + return false; + } + if (this._input === "") { + return this.EOF; + } else { + return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { + text: "", + token: null, + line: this.yylineno + }); + } + }, -module.exports = function () { - // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi - var origPrepareStackTrace = Error.prepareStackTrace; - Error.prepareStackTrace = function (_, stack) { return stack; }; - var stack = (new Error()).stack; - Error.prepareStackTrace = origPrepareStackTrace; - return stack[2].getFileName(); -}; +// return next match that has a token +lex:function lex() { + var r = this.next(); + if (r) { + return r; + } else { + return this.lex(); + } + }, +// activates a new lexer condition state (pushes the new lexer condition state onto the condition stack) +begin:function begin(condition) { + this.conditionStack.push(condition); + }, -/***/ }), -/* 537 */ -/***/ (function(module, exports, __webpack_require__) { +// pop the previously active lexer condition state off the condition stack +popState:function popState() { + var n = this.conditionStack.length - 1; + if (n > 0) { + return this.conditionStack.pop(); + } else { + return this.conditionStack[0]; + } + }, -var path = __webpack_require__(16); -var parse = path.parse || __webpack_require__(538); +// produce the lexer rule set which is active for the currently active lexer condition state +_currentRules:function _currentRules() { + if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) { + return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules; + } else { + return this.conditions["INITIAL"].rules; + } + }, -var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) { - var prefix = '/'; - if ((/^([A-Za-z]:)/).test(absoluteStart)) { - prefix = ''; - } else if ((/^\\\\/).test(absoluteStart)) { - prefix = '\\\\'; - } +// return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available +topState:function topState(n) { + n = this.conditionStack.length - 1 - Math.abs(n || 0); + if (n >= 0) { + return this.conditionStack[n]; + } else { + return "INITIAL"; + } + }, - var paths = [absoluteStart]; - var parsed = parse(absoluteStart); - while (parsed.dir !== paths[paths.length - 1]) { - paths.push(parsed.dir); - parsed = parse(parsed.dir); - } +// alias for begin(condition) +pushState:function pushState(condition) { + this.begin(condition); + }, - return paths.reduce(function (dirs, aPath) { - return dirs.concat(modules.map(function (moduleDir) { - return path.join(prefix, aPath, moduleDir); - })); - }, []); -}; +// return the number of states currently on the stack +stateStackSize:function stateStackSize() { + return this.conditionStack.length; + }, +options: {}, +performAction: function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) { +var YYSTATE=YY_START; +switch($avoiding_name_collisions) { +case 0:return 5 +break; +case 1:/* skip whitespace */ +break; +case 2:return 8 +break; +case 3:return 16 +break; +case 4:return 17 +break; +case 5:return 11 +break; +case 6:return 10 +break; +case 7:return 9 +break; +case 8:return 14 +break; +case 9:return 15 +break; +case 10:return 12 +break; +case 11:return 7 +break; +case 12:return 7 +break; +case 13:return 7 +break; +case 14:return 7 +break; +case 15:return 7 +break; +case 16:return 7 +break; +case 17:return 7 +break; +case 18:return 7 +break; +case 19:return 7 +break; +case 20:return 7 +break; +case 21:return 7 +break; +case 22:return 7 +break; +case 23:return 7 +break; +case 24:return 13 +break; +case 25:return 13 +break; +case 26:return 13 +break; +case 27:return 13 +break; +case 28:return 13 +break; +case 29:return 13 +break; +case 30:return 13 +break; +case 31:return 13 +break; +case 32:return 7 +break; +case 33:return 13 +break; +case 34:return 7 +break; +case 35:return 13 +break; +case 36:return 7 +break; +case 37:return 13 +break; +case 38:return 13 +break; +case 39:return 7 +break; +case 40:return 13 +break; +case 41:return 13 +break; +case 42:return 13 +break; +case 43:return 13 +break; +case 44:return 13 +break; +case 45:return 7 +break; +case 46:return 13 +break; +case 47:return 7 +break; +case 48:return 7 +break; +case 49:return 7 +break; +case 50:return 7 +break; +case 51:return 7 +break; +case 52:return 7 +break; +case 53:return 7 +break; +case 54:return 7 +break; +case 55:return 7 +break; +case 56:return 7 +break; +case 57:return 7 +break; +case 58:return 7 +break; +case 59:return 7 +break; +case 60:return 7 +break; +case 61:return 7 +break; +case 62:return 7 +break; +case 63:return 13 +break; +case 64:return 7 +break; +case 65:return 7 +break; +case 66:return 13 +break; +case 67:return 7 +break; +case 68:return 7 +break; +case 69:return 7 +break; +case 70:return 7 +break; +case 71:return 7 +break; +case 72:return 7 +break; +case 73:return 13 +break; +case 74:return 7 +break; +case 75:return 13 +break; +case 76:return 7 +break; +case 77:return 7 +break; +case 78:return 7 +break; +case 79:return 7 +break; +case 80:return 7 +break; +case 81:return 7 +break; +case 82:return 7 +break; +case 83:return 7 +break; +case 84:return 7 +break; +case 85:return 7 +break; +case 86:return 7 +break; +case 87:return 7 +break; +case 88:return 7 +break; +case 89:return 7 +break; +case 90:return 7 +break; +case 91:return 7 +break; +case 92:return 7 +break; +case 93:return 7 +break; +case 94:return 7 +break; +case 95:return 7 +break; +case 96:return 7 +break; +case 97:return 7 +break; +case 98:return 7 +break; +case 99:return 7 +break; +case 100:return 7 +break; +case 101:return 7 +break; +case 102:return 7 +break; +case 103:return 7 +break; +case 104:return 7 +break; +case 105:return 7 +break; +case 106:return 7 +break; +case 107:return 7 +break; +case 108:return 7 +break; +case 109:return 7 +break; +case 110:return 7 +break; +case 111:return 7 +break; +case 112:return 7 +break; +case 113:return 7 +break; +case 114:return 7 +break; +case 115:return 7 +break; +case 116:return 7 +break; +case 117:return 7 +break; +case 118:return 7 +break; +case 119:return 7 +break; +case 120:return 7 +break; +case 121:return 7 +break; +case 122:return 7 +break; +case 123:return 7 +break; +case 124:return 7 +break; +case 125:return 7 +break; +case 126:return 7 +break; +case 127:return 7 +break; +case 128:return 7 +break; +case 129:return 7 +break; +case 130:return 7 +break; +case 131:return 7 +break; +case 132:return 7 +break; +case 133:return 7 +break; +case 134:return 7 +break; +case 135:return 7 +break; +case 136:return 7 +break; +case 137:return 7 +break; +case 138:return 7 +break; +case 139:return 7 +break; +case 140:return 7 +break; +case 141:return 7 +break; +case 142:return 7 +break; +case 143:return 7 +break; +case 144:return 7 +break; +case 145:return 7 +break; +case 146:return 7 +break; +case 147:return 7 +break; +case 148:return 7 +break; +case 149:return 7 +break; +case 150:return 7 +break; +case 151:return 7 +break; +case 152:return 7 +break; +case 153:return 7 +break; +case 154:return 7 +break; +case 155:return 7 +break; +case 156:return 7 +break; +case 157:return 7 +break; +case 158:return 7 +break; +case 159:return 7 +break; +case 160:return 7 +break; +case 161:return 7 +break; +case 162:return 7 +break; +case 163:return 7 +break; +case 164:return 7 +break; +case 165:return 7 +break; +case 166:return 7 +break; +case 167:return 7 +break; +case 168:return 7 +break; +case 169:return 7 +break; +case 170:return 7 +break; +case 171:return 7 +break; +case 172:return 7 +break; +case 173:return 7 +break; +case 174:return 7 +break; +case 175:return 7 +break; +case 176:return 7 +break; +case 177:return 7 +break; +case 178:return 7 +break; +case 179:return 7 +break; +case 180:return 7 +break; +case 181:return 7 +break; +case 182:return 7 +break; +case 183:return 7 +break; +case 184:return 7 +break; +case 185:return 7 +break; +case 186:return 7 +break; +case 187:return 7 +break; +case 188:return 7 +break; +case 189:return 7 +break; +case 190:return 7 +break; +case 191:return 7 +break; +case 192:return 7 +break; +case 193:return 7 +break; +case 194:return 7 +break; +case 195:return 7 +break; +case 196:return 7 +break; +case 197:return 7 +break; +case 198:return 7 +break; +case 199:return 7 +break; +case 200:return 7 +break; +case 201:return 7 +break; +case 202:return 7 +break; +case 203:return 7 +break; +case 204:return 7 +break; +case 205:return 7 +break; +case 206:return 7 +break; +case 207:return 7 +break; +case 208:return 7 +break; +case 209:return 7 +break; +case 210:return 7 +break; +case 211:return 7 +break; +case 212:return 7 +break; +case 213:return 7 +break; +case 214:return 7 +break; +case 215:return 7 +break; +case 216:return 7 +break; +case 217:return 7 +break; +case 218:return 7 +break; +case 219:return 7 +break; +case 220:return 7 +break; +case 221:return 7 +break; +case 222:return 7 +break; +case 223:return 7 +break; +case 224:return 7 +break; +case 225:return 7 +break; +case 226:return 7 +break; +case 227:return 7 +break; +case 228:return 7 +break; +case 229:return 7 +break; +case 230:return 7 +break; +case 231:return 7 +break; +case 232:return 7 +break; +case 233:return 7 +break; +case 234:return 7 +break; +case 235:return 7 +break; +case 236:return 7 +break; +case 237:return 7 +break; +case 238:return 7 +break; +case 239:return 7 +break; +case 240:return 7 +break; +case 241:return 7 +break; +case 242:return 7 +break; +case 243:return 7 +break; +case 244:return 7 +break; +case 245:return 7 +break; +case 246:return 7 +break; +case 247:return 7 +break; +case 248:return 7 +break; +case 249:return 7 +break; +case 250:return 7 +break; +case 251:return 7 +break; +case 252:return 7 +break; +case 253:return 7 +break; +case 254:return 7 +break; +case 255:return 7 +break; +case 256:return 7 +break; +case 257:return 7 +break; +case 258:return 7 +break; +case 259:return 7 +break; +case 260:return 7 +break; +case 261:return 7 +break; +case 262:return 7 +break; +case 263:return 7 +break; +case 264:return 7 +break; +case 265:return 7 +break; +case 266:return 7 +break; +case 267:return 7 +break; +case 268:return 7 +break; +case 269:return 7 +break; +case 270:return 7 +break; +case 271:return 7 +break; +case 272:return 7 +break; +case 273:return 7 +break; +case 274:return 7 +break; +case 275:return 7 +break; +case 276:return 7 +break; +case 277:return 7 +break; +case 278:return 7 +break; +case 279:return 7 +break; +case 280:return 7 +break; +case 281:return 7 +break; +case 282:return 7 +break; +case 283:return 7 +break; +case 284:return 7 +break; +case 285:return 7 +break; +case 286:return 7 +break; +case 287:return 7 +break; +case 288:return 7 +break; +case 289:return 7 +break; +case 290:return 7 +break; +case 291:return 7 +break; +case 292:return 7 +break; +case 293:return 7 +break; +case 294:return 7 +break; +case 295:return 7 +break; +case 296:return 7 +break; +case 297:return 7 +break; +case 298:return 7 +break; +case 299:return 7 +break; +case 300:return 7 +break; +case 301:return 7 +break; +case 302:return 7 +break; +case 303:return 7 +break; +case 304:return 7 +break; +case 305:return 7 +break; +case 306:return 7 +break; +case 307:return 7 +break; +case 308:return 7 +break; +case 309:return 7 +break; +case 310:return 7 +break; +case 311:return 7 +break; +case 312:return 7 +break; +case 313:return 7 +break; +case 314:return 7 +break; +case 315:return 7 +break; +case 316:return 7 +break; +case 317:return 7 +break; +case 318:return 7 +break; +case 319:return 7 +break; +case 320:return 7 +break; +case 321:return 7 +break; +case 322:return 7 +break; +case 323:return 7 +break; +case 324:return 7 +break; +case 325:return 7 +break; +case 326:return 7 +break; +case 327:return 7 +break; +case 328:return 7 +break; +case 329:return 7 +break; +case 330:return 7 +break; +case 331:return 7 +break; +case 332:return 7 +break; +case 333:return 7 +break; +case 334:return 7 +break; +case 335:return 7 +break; +case 336:return 7 +break; +case 337:return 7 +break; +case 338:return 7 +break; +case 339:return 7 +break; +case 340:return 7 +break; +case 341:return 7 +break; +case 342:return 7 +break; +case 343:return 7 +break; +case 344:return 7 +break; +case 345:return 7 +break; +case 346:return 7 +break; +case 347:return 7 +break; +case 348:return 7 +break; +case 349:return 7 +break; +case 350:return 7 +break; +case 351:return 7 +break; +case 352:return 7 +break; +case 353:return 7 +break; +case 354:return 7 +break; +case 355:return 7 +break; +case 356:return 7 +break; +case 357:return 7 +break; +case 358:return 7 +break; +case 359:return 7 +break; +case 360:return 7 +break; +case 361:return 7 +break; +case 362:return 7 +break; +case 363:return 7 +break; +case 364:return 7 +break; +} +}, +rules: [/^(?:$)/,/^(?:\s+)/,/^(?:\+)/,/^(?:\()/,/^(?:\))/,/^(?::)/,/^(?:DocumentRef-([0-9A-Za-z-+.]+))/,/^(?:LicenseRef-([0-9A-Za-z-+.]+))/,/^(?:AND)/,/^(?:OR)/,/^(?:WITH)/,/^(?:BSD-3-Clause-No-Nuclear-License-2014)/,/^(?:BSD-3-Clause-No-Nuclear-Warranty)/,/^(?:GPL-2\.0-with-classpath-exception)/,/^(?:GPL-3\.0-with-autoconf-exception)/,/^(?:GPL-2\.0-with-autoconf-exception)/,/^(?:BSD-3-Clause-No-Nuclear-License)/,/^(?:MPL-2\.0-no-copyleft-exception)/,/^(?:GPL-2\.0-with-bison-exception)/,/^(?:GPL-2\.0-with-font-exception)/,/^(?:GPL-2\.0-with-GCC-exception)/,/^(?:CNRI-Python-GPL-Compatible)/,/^(?:GPL-3\.0-with-GCC-exception)/,/^(?:BSD-3-Clause-Attribution)/,/^(?:Classpath-exception-2\.0)/,/^(?:WxWindows-exception-3\.1)/,/^(?:freertos-exception-2\.0)/,/^(?:Autoconf-exception-3\.0)/,/^(?:i2p-gpl-java-exception)/,/^(?:gnu-javamail-exception)/,/^(?:Nokia-Qt-exception-1\.1)/,/^(?:Autoconf-exception-2\.0)/,/^(?:BSD-2-Clause-FreeBSD)/,/^(?:u-boot-exception-2\.0)/,/^(?:zlib-acknowledgement)/,/^(?:Bison-exception-2\.2)/,/^(?:BSD-2-Clause-NetBSD)/,/^(?:CLISP-exception-2\.0)/,/^(?:eCos-exception-2\.0)/,/^(?:BSD-3-Clause-Clear)/,/^(?:Font-exception-2\.0)/,/^(?:FLTK-exception-2\.0)/,/^(?:GCC-exception-2\.0)/,/^(?:Qwt-exception-1\.0)/,/^(?:Libtool-exception)/,/^(?:BSD-3-Clause-LBNL)/,/^(?:GCC-exception-3\.1)/,/^(?:Artistic-1\.0-Perl)/,/^(?:Artistic-1\.0-cl8)/,/^(?:CC-BY-NC-SA-2\.5)/,/^(?:MIT-advertising)/,/^(?:BSD-Source-Code)/,/^(?:CC-BY-NC-SA-4\.0)/,/^(?:LiLiQ-Rplus-1\.1)/,/^(?:CC-BY-NC-SA-3\.0)/,/^(?:BSD-4-Clause-UC)/,/^(?:CC-BY-NC-SA-2\.0)/,/^(?:CC-BY-NC-SA-1\.0)/,/^(?:CC-BY-NC-ND-4\.0)/,/^(?:CC-BY-NC-ND-3\.0)/,/^(?:CC-BY-NC-ND-2\.5)/,/^(?:CC-BY-NC-ND-2\.0)/,/^(?:CC-BY-NC-ND-1\.0)/,/^(?:LZMA-exception)/,/^(?:BitTorrent-1\.1)/,/^(?:CrystalStacker)/,/^(?:FLTK-exception)/,/^(?:SugarCRM-1\.1\.3)/,/^(?:BSD-Protection)/,/^(?:BitTorrent-1\.0)/,/^(?:HaskellReport)/,/^(?:Interbase-1\.0)/,/^(?:StandardML-NJ)/,/^(?:mif-exception)/,/^(?:Frameworx-1\.0)/,/^(?:389-exception)/,/^(?:CC-BY-NC-2\.0)/,/^(?:CC-BY-NC-2\.5)/,/^(?:CC-BY-NC-3\.0)/,/^(?:CC-BY-NC-4\.0)/,/^(?:W3C-19980720)/,/^(?:CC-BY-SA-1\.0)/,/^(?:CC-BY-SA-2\.0)/,/^(?:CC-BY-SA-2\.5)/,/^(?:CC-BY-ND-2\.0)/,/^(?:CC-BY-SA-4\.0)/,/^(?:CC-BY-SA-3\.0)/,/^(?:Artistic-1\.0)/,/^(?:Artistic-2\.0)/,/^(?:CC-BY-ND-2\.5)/,/^(?:CC-BY-ND-3\.0)/,/^(?:CC-BY-ND-4\.0)/,/^(?:CC-BY-ND-1\.0)/,/^(?:BSD-4-Clause)/,/^(?:BSD-3-Clause)/,/^(?:BSD-2-Clause)/,/^(?:CC-BY-NC-1\.0)/,/^(?:bzip2-1\.0\.6)/,/^(?:Unicode-TOU)/,/^(?:CNRI-Jython)/,/^(?:ImageMagick)/,/^(?:Adobe-Glyph)/,/^(?:CUA-OPL-1\.0)/,/^(?:OLDAP-2\.2\.2)/,/^(?:LiLiQ-R-1\.1)/,/^(?:bzip2-1\.0\.5)/,/^(?:LiLiQ-P-1\.1)/,/^(?:OLDAP-2\.0\.1)/,/^(?:OLDAP-2\.2\.1)/,/^(?:CNRI-Python)/,/^(?:XFree86-1\.1)/,/^(?:OSET-PL-2\.1)/,/^(?:Apache-2\.0)/,/^(?:Watcom-1\.0)/,/^(?:PostgreSQL)/,/^(?:Python-2\.0)/,/^(?:RHeCos-1\.1)/,/^(?:EUDatagrid)/,/^(?:Spencer-99)/,/^(?:Intel-ACPI)/,/^(?:CECILL-1\.0)/,/^(?:CECILL-1\.1)/,/^(?:JasPer-2\.0)/,/^(?:CECILL-2\.0)/,/^(?:CECILL-2\.1)/,/^(?:gSOAP-1\.3b)/,/^(?:Spencer-94)/,/^(?:Apache-1\.1)/,/^(?:Spencer-86)/,/^(?:Apache-1\.0)/,/^(?:ClArtistic)/,/^(?:TORQUE-1\.1)/,/^(?:CATOSL-1\.1)/,/^(?:Adobe-2006)/,/^(?:Zimbra-1\.4)/,/^(?:Zimbra-1\.3)/,/^(?:Condor-1\.1)/,/^(?:CC-BY-3\.0)/,/^(?:CC-BY-2\.5)/,/^(?:OLDAP-2\.4)/,/^(?:SGI-B-1\.1)/,/^(?:SISSL-1\.2)/,/^(?:SGI-B-1\.0)/,/^(?:OLDAP-2\.3)/,/^(?:CC-BY-4\.0)/,/^(?:Crossword)/,/^(?:SimPL-2\.0)/,/^(?:OLDAP-2\.2)/,/^(?:OLDAP-2\.1)/,/^(?:ErlPL-1\.1)/,/^(?:LPPL-1\.3a)/,/^(?:LPPL-1\.3c)/,/^(?:OLDAP-2\.0)/,/^(?:Leptonica)/,/^(?:CPOL-1\.02)/,/^(?:OLDAP-1\.4)/,/^(?:OLDAP-1\.3)/,/^(?:CC-BY-2\.0)/,/^(?:Unlicense)/,/^(?:OLDAP-2\.8)/,/^(?:OLDAP-1\.2)/,/^(?:MakeIndex)/,/^(?:OLDAP-2\.7)/,/^(?:OLDAP-1\.1)/,/^(?:Sleepycat)/,/^(?:D-FSL-1\.0)/,/^(?:CC-BY-1\.0)/,/^(?:OLDAP-2\.6)/,/^(?:WXwindows)/,/^(?:NPOSL-3\.0)/,/^(?:FreeImage)/,/^(?:SGI-B-2\.0)/,/^(?:OLDAP-2\.5)/,/^(?:Beerware)/,/^(?:Newsletr)/,/^(?:NBPL-1\.0)/,/^(?:NASA-1\.3)/,/^(?:NLOD-1\.0)/,/^(?:AGPL-1\.0)/,/^(?:OCLC-2\.0)/,/^(?:ODbL-1\.0)/,/^(?:PDDL-1\.0)/,/^(?:Motosoto)/,/^(?:Afmparse)/,/^(?:ANTLR-PD)/,/^(?:LPL-1\.02)/,/^(?:Abstyles)/,/^(?:eCos-2\.0)/,/^(?:APSL-1\.0)/,/^(?:LPPL-1\.2)/,/^(?:LPPL-1\.1)/,/^(?:LPPL-1\.0)/,/^(?:APSL-1\.1)/,/^(?:APSL-2\.0)/,/^(?:Info-ZIP)/,/^(?:Zend-2\.0)/,/^(?:IBM-pibs)/,/^(?:LGPL-2\.0)/,/^(?:LGPL-3\.0)/,/^(?:LGPL-2\.1)/,/^(?:GFDL-1\.3)/,/^(?:PHP-3\.01)/,/^(?:GFDL-1\.2)/,/^(?:GFDL-1\.1)/,/^(?:AGPL-3\.0)/,/^(?:Giftware)/,/^(?:EUPL-1\.1)/,/^(?:RPSL-1\.0)/,/^(?:EUPL-1\.0)/,/^(?:MIT-enna)/,/^(?:CECILL-B)/,/^(?:diffmark)/,/^(?:CECILL-C)/,/^(?:CDDL-1\.0)/,/^(?:Sendmail)/,/^(?:CDDL-1\.1)/,/^(?:CPAL-1\.0)/,/^(?:APSL-1\.2)/,/^(?:NPL-1\.1)/,/^(?:AFL-1\.2)/,/^(?:Caldera)/,/^(?:AFL-2\.0)/,/^(?:FSFULLR)/,/^(?:AFL-2\.1)/,/^(?:VSL-1\.0)/,/^(?:VOSTROM)/,/^(?:UPL-1\.0)/,/^(?:Dotseqn)/,/^(?:CPL-1\.0)/,/^(?:dvipdfm)/,/^(?:EPL-1\.0)/,/^(?:OCCT-PL)/,/^(?:ECL-1\.0)/,/^(?:Latex2e)/,/^(?:ECL-2\.0)/,/^(?:GPL-1\.0)/,/^(?:GPL-2\.0)/,/^(?:GPL-3\.0)/,/^(?:AFL-3\.0)/,/^(?:LAL-1\.2)/,/^(?:LAL-1\.3)/,/^(?:EFL-1\.0)/,/^(?:EFL-2\.0)/,/^(?:gnuplot)/,/^(?:Aladdin)/,/^(?:LPL-1\.0)/,/^(?:libtiff)/,/^(?:Entessa)/,/^(?:AMDPLPA)/,/^(?:IPL-1\.0)/,/^(?:OPL-1\.0)/,/^(?:OSL-1\.0)/,/^(?:OSL-1\.1)/,/^(?:OSL-2\.0)/,/^(?:OSL-2\.1)/,/^(?:OSL-3\.0)/,/^(?:OpenSSL)/,/^(?:ZPL-2\.1)/,/^(?:PHP-3\.0)/,/^(?:ZPL-2\.0)/,/^(?:ZPL-1\.1)/,/^(?:CC0-1\.0)/,/^(?:SPL-1\.0)/,/^(?:psutils)/,/^(?:MPL-1\.0)/,/^(?:QPL-1\.0)/,/^(?:MPL-1\.1)/,/^(?:MPL-2\.0)/,/^(?:APL-1\.0)/,/^(?:RPL-1\.1)/,/^(?:RPL-1\.5)/,/^(?:MIT-CMU)/,/^(?:Multics)/,/^(?:Eurosym)/,/^(?:BSL-1\.0)/,/^(?:MIT-feh)/,/^(?:Saxpath)/,/^(?:Borceux)/,/^(?:OFL-1\.1)/,/^(?:OFL-1\.0)/,/^(?:AFL-1\.1)/,/^(?:YPL-1\.1)/,/^(?:YPL-1\.0)/,/^(?:NPL-1\.0)/,/^(?:iMatix)/,/^(?:mpich2)/,/^(?:APAFML)/,/^(?:Bahyph)/,/^(?:RSA-MD)/,/^(?:psfrag)/,/^(?:Plexus)/,/^(?:eGenix)/,/^(?:Glulxe)/,/^(?:SAX-PD)/,/^(?:Imlib2)/,/^(?:Wsuipa)/,/^(?:LGPLLR)/,/^(?:Libpng)/,/^(?:xinetd)/,/^(?:MITNFA)/,/^(?:NetCDF)/,/^(?:Naumen)/,/^(?:SMPPL)/,/^(?:Nunit)/,/^(?:FSFUL)/,/^(?:GL2PS)/,/^(?:SMLNJ)/,/^(?:Rdisc)/,/^(?:Noweb)/,/^(?:Nokia)/,/^(?:SISSL)/,/^(?:Qhull)/,/^(?:Intel)/,/^(?:Glide)/,/^(?:Xerox)/,/^(?:AMPAS)/,/^(?:WTFPL)/,/^(?:MS-PL)/,/^(?:XSkat)/,/^(?:MS-RL)/,/^(?:MirOS)/,/^(?:RSCPL)/,/^(?:TMate)/,/^(?:OGTSL)/,/^(?:FSFAP)/,/^(?:NCSA)/,/^(?:Zlib)/,/^(?:SCEA)/,/^(?:SNIA)/,/^(?:NGPL)/,/^(?:NOSL)/,/^(?:ADSL)/,/^(?:MTLL)/,/^(?:NLPL)/,/^(?:Ruby)/,/^(?:JSON)/,/^(?:Barr)/,/^(?:0BSD)/,/^(?:Xnet)/,/^(?:Cube)/,/^(?:curl)/,/^(?:DSDP)/,/^(?:Fair)/,/^(?:HPND)/,/^(?:TOSL)/,/^(?:IJG)/,/^(?:SWL)/,/^(?:Vim)/,/^(?:FTL)/,/^(?:ICU)/,/^(?:OML)/,/^(?:NRL)/,/^(?:DOC)/,/^(?:TCL)/,/^(?:W3C)/,/^(?:NTP)/,/^(?:IPA)/,/^(?:ISC)/,/^(?:X11)/,/^(?:AAL)/,/^(?:AML)/,/^(?:xpp)/,/^(?:Zed)/,/^(?:MIT)/,/^(?:Mup)/], +conditions: {"INITIAL":{"rules":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364],"inclusive":true}} +}); +return lexer; +})(); +parser.lexer = lexer; +function Parser () { + this.yy = {}; +} +Parser.prototype = parser;parser.Parser = Parser; +return new Parser; +})(); -module.exports = function nodeModulesPaths(start, opts, request) { - var modules = opts && opts.moduleDirectory - ? [].concat(opts.moduleDirectory) - : ['node_modules']; - if (opts && typeof opts.paths === 'function') { - return opts.paths( - request, - start, - function () { return getNodeModulesDirs(start, modules); }, - opts - ); +if (true) { +exports.parser = spdxparse; +exports.Parser = spdxparse.Parser; +exports.parse = function () { return spdxparse.parse.apply(spdxparse, arguments); }; +exports.main = function commonjsMain(args) { + if (!args[1]) { + console.log('Usage: '+args[0]+' FILE'); + process.exit(1); } - - var dirs = getNodeModulesDirs(start, modules); - return opts && opts.paths ? dirs.concat(opts.paths) : dirs; + var source = __webpack_require__(349).readFileSync(__webpack_require__(4).normalize(args[1]), "utf8"); + return exports.parser.parse(source); }; +if ( true && __webpack_require__.c[__webpack_require__.s] === module) { + exports.main(process.argv.slice(1)); +} +} +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(11)(module))) /***/ }), -/* 538 */ +/* 527 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +var licenseIDs = __webpack_require__(528); +function valid(string) { + return licenseIDs.indexOf(string) > -1; +} -var isWindows = process.platform === 'win32'; +// Common transpositions of license identifier acronyms +var transpositions = [ + ['APGL', 'AGPL'], + ['Gpl', 'GPL'], + ['GLP', 'GPL'], + ['APL', 'Apache'], + ['ISD', 'ISC'], + ['GLP', 'GPL'], + ['IST', 'ISC'], + ['Claude', 'Clause'], + [' or later', '+'], + [' International', ''], + ['GNU', 'GPL'], + ['GUN', 'GPL'], + ['+', ''], + ['GNU GPL', 'GPL'], + ['GNU/GPL', 'GPL'], + ['GNU GLP', 'GPL'], + ['GNU General Public License', 'GPL'], + ['Gnu public license', 'GPL'], + ['GNU Public License', 'GPL'], + ['GNU GENERAL PUBLIC LICENSE', 'GPL'], + ['MTI', 'MIT'], + ['Mozilla Public License', 'MPL'], + ['WTH', 'WTF'], + ['-License', ''] +]; -// Regex to split a windows path into three parts: [*, device, slash, -// tail] windows-only -var splitDeviceRe = - /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; +var TRANSPOSED = 0; +var CORRECT = 1; -// Regex to split the tail part of the above into [*, dir, basename, ext] -var splitTailRe = - /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/; +// Simple corrections to nearly valid identifiers. +var transforms = [ + // e.g. 'mit' + function(argument) { + return argument.toUpperCase(); + }, + // e.g. 'MIT ' + function(argument) { + return argument.trim(); + }, + // e.g. 'M.I.T.' + function(argument) { + return argument.replace(/\./g, ''); + }, + // e.g. 'Apache- 2.0' + function(argument) { + return argument.replace(/\s+/g, ''); + }, + // e.g. 'CC BY 4.0'' + function(argument) { + return argument.replace(/\s+/g, '-'); + }, + // e.g. 'LGPLv2.1' + function(argument) { + return argument.replace('v', '-'); + }, + // e.g. 'Apache 2.0' + function(argument) { + return argument.replace(/,?\s*(\d)/, '-$1'); + }, + // e.g. 'GPL 2' + function(argument) { + return argument.replace(/,?\s*(\d)/, '-$1.0'); + }, + // e.g. 'Apache Version 2.0' + function(argument) { + return argument.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, '-$2'); + }, + // e.g. 'Apache Version 2' + function(argument) { + return argument.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, '-$2.0'); + }, + // e.g. 'ZLIB' + function(argument) { + return argument[0].toUpperCase() + argument.slice(1); + }, + // e.g. 'MPL/2.0' + function(argument) { + return argument.replace('/', '-'); + }, + // e.g. 'Apache 2' + function(argument) { + return argument + .replace(/\s*V\s*(\d)/, '-$1') + .replace(/(\d)$/, '$1.0'); + }, + // e.g. 'GPL-2.0-' + function(argument) { + return argument.slice(0, argument.length - 1); + }, + // e.g. 'GPL2' + function(argument) { + return argument.replace(/(\d)$/, '-$1.0'); + }, + // e.g. 'BSD 3' + function(argument) { + return argument.replace(/(-| )?(\d)$/, '-$2-Clause'); + }, + // e.g. 'BSD clause 3' + function(argument) { + return argument.replace(/(-| )clause(-| )(\d)/, '-$3-Clause'); + }, + // e.g. 'BY-NC-4.0' + function(argument) { + return 'CC-' + argument; + }, + // e.g. 'BY-NC' + function(argument) { + return 'CC-' + argument + '-4.0'; + }, + // e.g. 'Attribution-NonCommercial' + function(argument) { + return argument + .replace('Attribution', 'BY') + .replace('NonCommercial', 'NC') + .replace('NoDerivatives', 'ND') + .replace(/ (\d)/, '-$1') + .replace(/ ?International/, ''); + }, + // e.g. 'Attribution-NonCommercial' + function(argument) { + return 'CC-' + + argument + .replace('Attribution', 'BY') + .replace('NonCommercial', 'NC') + .replace('NoDerivatives', 'ND') + .replace(/ (\d)/, '-$1') + .replace(/ ?International/, '') + + '-4.0'; + } +]; -var win32 = {}; +// If all else fails, guess that strings containing certain substrings +// meant to identify certain licenses. +var lastResorts = [ + ['UNLI', 'Unlicense'], + ['WTF', 'WTFPL'], + ['2 CLAUSE', 'BSD-2-Clause'], + ['2-CLAUSE', 'BSD-2-Clause'], + ['3 CLAUSE', 'BSD-3-Clause'], + ['3-CLAUSE', 'BSD-3-Clause'], + ['AFFERO', 'AGPL-3.0'], + ['AGPL', 'AGPL-3.0'], + ['APACHE', 'Apache-2.0'], + ['ARTISTIC', 'Artistic-2.0'], + ['Affero', 'AGPL-3.0'], + ['BEER', 'Beerware'], + ['BOOST', 'BSL-1.0'], + ['BSD', 'BSD-2-Clause'], + ['ECLIPSE', 'EPL-1.0'], + ['FUCK', 'WTFPL'], + ['GNU', 'GPL-3.0'], + ['LGPL', 'LGPL-3.0'], + ['GPL', 'GPL-3.0'], + ['MIT', 'MIT'], + ['MPL', 'MPL-2.0'], + ['X11', 'X11'], + ['ZLIB', 'Zlib'] +]; -// Function to split a filename into [root, dir, basename, ext] -function win32SplitPath(filename) { - // Separate device+slash from tail - var result = splitDeviceRe.exec(filename), - device = (result[1] || '') + (result[2] || ''), - tail = result[3] || ''; - // Split the tail into dir, basename and extension - var result2 = splitTailRe.exec(tail), - dir = result2[1], - basename = result2[2], - ext = result2[3]; - return [device, dir, basename, ext]; -} +var SUBSTRING = 0; +var IDENTIFIER = 1; -win32.parse = function(pathString) { - if (typeof pathString !== 'string') { - throw new TypeError( - "Parameter 'pathString' must be a string, not " + typeof pathString - ); - } - var allParts = win32SplitPath(pathString); - if (!allParts || allParts.length !== 4) { - throw new TypeError("Invalid path '" + pathString + "'"); +var validTransformation = function(identifier) { + for (var i = 0; i < transforms.length; i++) { + var transformed = transforms[i](identifier); + if (transformed !== identifier && valid(transformed)) { + return transformed; + } } - return { - root: allParts[0], - dir: allParts[0] + allParts[1].slice(0, -1), - base: allParts[2], - ext: allParts[3], - name: allParts[2].slice(0, allParts[2].length - allParts[3].length) - }; + return null; }; +var validLastResort = function(identifier) { + var upperCased = identifier.toUpperCase(); + for (var i = 0; i < lastResorts.length; i++) { + var lastResort = lastResorts[i]; + if (upperCased.indexOf(lastResort[SUBSTRING]) > -1) { + return lastResort[IDENTIFIER]; + } + } + return null; +}; +var anyCorrection = function(identifier, check) { + for (var i = 0; i < transpositions.length; i++) { + var transposition = transpositions[i]; + var transposed = transposition[TRANSPOSED]; + if (identifier.indexOf(transposed) > -1) { + var corrected = identifier.replace( + transposed, + transposition[CORRECT] + ); + var checked = check(corrected); + if (checked !== null) { + return checked; + } + } + } + return null; +}; -// Split a filename into [root, dir, basename, ext], unix version -// 'root' is just a slash, or nothing. -var splitPathRe = - /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; -var posix = {}; - - -function posixSplitPath(filename) { - return splitPathRe.exec(filename).slice(1); -} - - -posix.parse = function(pathString) { - if (typeof pathString !== 'string') { - throw new TypeError( - "Parameter 'pathString' must be a string, not " + typeof pathString - ); +module.exports = function(identifier) { + identifier = identifier.replace(/\+$/, ''); + if (valid(identifier)) { + return identifier; } - var allParts = posixSplitPath(pathString); - if (!allParts || allParts.length !== 4) { - throw new TypeError("Invalid path '" + pathString + "'"); + var transformed = validTransformation(identifier); + if (transformed !== null) { + return transformed; } - allParts[1] = allParts[1] || ''; - allParts[2] = allParts[2] || ''; - allParts[3] = allParts[3] || ''; - - return { - root: allParts[0], - dir: allParts[0] + allParts[1].slice(0, -1), - base: allParts[2], - ext: allParts[3], - name: allParts[2].slice(0, allParts[2].length - allParts[3].length) - }; + transformed = anyCorrection(identifier, function(argument) { + if (valid(argument)) { + return argument; + } + return validTransformation(argument); + }); + if (transformed !== null) { + return transformed; + } + transformed = validLastResort(identifier); + if (transformed !== null) { + return transformed; + } + transformed = anyCorrection(identifier, validLastResort); + if (transformed !== null) { + return transformed; + } + return null; }; -if (isWindows) - module.exports = win32.parse; -else /* posix */ - module.exports = posix.parse; - -module.exports.posix = posix.parse; -module.exports.win32 = win32.parse; - - /***/ }), -/* 539 */ -/***/ (function(module, exports) { - -module.exports = function (x, opts) { - /** - * This file is purposefully a passthrough. It's expected that third-party - * environments will override it at runtime in order to inject special logic - * into `resolve` (by manipulating the options). One such example is the PnP - * code path in Yarn. - */ - - return opts || {}; -}; +/* 528 */ +/***/ (function(module) { +module.exports = JSON.parse("[\"Glide\",\"Abstyles\",\"AFL-1.1\",\"AFL-1.2\",\"AFL-2.0\",\"AFL-2.1\",\"AFL-3.0\",\"AMPAS\",\"APL-1.0\",\"Adobe-Glyph\",\"APAFML\",\"Adobe-2006\",\"AGPL-1.0\",\"Afmparse\",\"Aladdin\",\"ADSL\",\"AMDPLPA\",\"ANTLR-PD\",\"Apache-1.0\",\"Apache-1.1\",\"Apache-2.0\",\"AML\",\"APSL-1.0\",\"APSL-1.1\",\"APSL-1.2\",\"APSL-2.0\",\"Artistic-1.0\",\"Artistic-1.0-Perl\",\"Artistic-1.0-cl8\",\"Artistic-2.0\",\"AAL\",\"Bahyph\",\"Barr\",\"Beerware\",\"BitTorrent-1.0\",\"BitTorrent-1.1\",\"BSL-1.0\",\"Borceux\",\"BSD-2-Clause\",\"BSD-2-Clause-FreeBSD\",\"BSD-2-Clause-NetBSD\",\"BSD-3-Clause\",\"BSD-3-Clause-Clear\",\"BSD-4-Clause\",\"BSD-Protection\",\"BSD-Source-Code\",\"BSD-3-Clause-Attribution\",\"0BSD\",\"BSD-4-Clause-UC\",\"bzip2-1.0.5\",\"bzip2-1.0.6\",\"Caldera\",\"CECILL-1.0\",\"CECILL-1.1\",\"CECILL-2.0\",\"CECILL-2.1\",\"CECILL-B\",\"CECILL-C\",\"ClArtistic\",\"MIT-CMU\",\"CNRI-Jython\",\"CNRI-Python\",\"CNRI-Python-GPL-Compatible\",\"CPOL-1.02\",\"CDDL-1.0\",\"CDDL-1.1\",\"CPAL-1.0\",\"CPL-1.0\",\"CATOSL-1.1\",\"Condor-1.1\",\"CC-BY-1.0\",\"CC-BY-2.0\",\"CC-BY-2.5\",\"CC-BY-3.0\",\"CC-BY-4.0\",\"CC-BY-ND-1.0\",\"CC-BY-ND-2.0\",\"CC-BY-ND-2.5\",\"CC-BY-ND-3.0\",\"CC-BY-ND-4.0\",\"CC-BY-NC-1.0\",\"CC-BY-NC-2.0\",\"CC-BY-NC-2.5\",\"CC-BY-NC-3.0\",\"CC-BY-NC-4.0\",\"CC-BY-NC-ND-1.0\",\"CC-BY-NC-ND-2.0\",\"CC-BY-NC-ND-2.5\",\"CC-BY-NC-ND-3.0\",\"CC-BY-NC-ND-4.0\",\"CC-BY-NC-SA-1.0\",\"CC-BY-NC-SA-2.0\",\"CC-BY-NC-SA-2.5\",\"CC-BY-NC-SA-3.0\",\"CC-BY-NC-SA-4.0\",\"CC-BY-SA-1.0\",\"CC-BY-SA-2.0\",\"CC-BY-SA-2.5\",\"CC-BY-SA-3.0\",\"CC-BY-SA-4.0\",\"CC0-1.0\",\"Crossword\",\"CrystalStacker\",\"CUA-OPL-1.0\",\"Cube\",\"curl\",\"D-FSL-1.0\",\"diffmark\",\"WTFPL\",\"DOC\",\"Dotseqn\",\"DSDP\",\"dvipdfm\",\"EPL-1.0\",\"ECL-1.0\",\"ECL-2.0\",\"eGenix\",\"EFL-1.0\",\"EFL-2.0\",\"MIT-advertising\",\"MIT-enna\",\"Entessa\",\"ErlPL-1.1\",\"EUDatagrid\",\"EUPL-1.0\",\"EUPL-1.1\",\"Eurosym\",\"Fair\",\"MIT-feh\",\"Frameworx-1.0\",\"FreeImage\",\"FTL\",\"FSFAP\",\"FSFUL\",\"FSFULLR\",\"Giftware\",\"GL2PS\",\"Glulxe\",\"AGPL-3.0\",\"GFDL-1.1\",\"GFDL-1.2\",\"GFDL-1.3\",\"GPL-1.0\",\"GPL-2.0\",\"GPL-3.0\",\"LGPL-2.1\",\"LGPL-3.0\",\"LGPL-2.0\",\"gnuplot\",\"gSOAP-1.3b\",\"HaskellReport\",\"HPND\",\"IBM-pibs\",\"IPL-1.0\",\"ICU\",\"ImageMagick\",\"iMatix\",\"Imlib2\",\"IJG\",\"Info-ZIP\",\"Intel-ACPI\",\"Intel\",\"Interbase-1.0\",\"IPA\",\"ISC\",\"JasPer-2.0\",\"JSON\",\"LPPL-1.0\",\"LPPL-1.1\",\"LPPL-1.2\",\"LPPL-1.3a\",\"LPPL-1.3c\",\"Latex2e\",\"BSD-3-Clause-LBNL\",\"Leptonica\",\"LGPLLR\",\"Libpng\",\"libtiff\",\"LAL-1.2\",\"LAL-1.3\",\"LiLiQ-P-1.1\",\"LiLiQ-Rplus-1.1\",\"LiLiQ-R-1.1\",\"LPL-1.02\",\"LPL-1.0\",\"MakeIndex\",\"MTLL\",\"MS-PL\",\"MS-RL\",\"MirOS\",\"MITNFA\",\"MIT\",\"Motosoto\",\"MPL-1.0\",\"MPL-1.1\",\"MPL-2.0\",\"MPL-2.0-no-copyleft-exception\",\"mpich2\",\"Multics\",\"Mup\",\"NASA-1.3\",\"Naumen\",\"NBPL-1.0\",\"NetCDF\",\"NGPL\",\"NOSL\",\"NPL-1.0\",\"NPL-1.1\",\"Newsletr\",\"NLPL\",\"Nokia\",\"NPOSL-3.0\",\"NLOD-1.0\",\"Noweb\",\"NRL\",\"NTP\",\"Nunit\",\"OCLC-2.0\",\"ODbL-1.0\",\"PDDL-1.0\",\"OCCT-PL\",\"OGTSL\",\"OLDAP-2.2.2\",\"OLDAP-1.1\",\"OLDAP-1.2\",\"OLDAP-1.3\",\"OLDAP-1.4\",\"OLDAP-2.0\",\"OLDAP-2.0.1\",\"OLDAP-2.1\",\"OLDAP-2.2\",\"OLDAP-2.2.1\",\"OLDAP-2.3\",\"OLDAP-2.4\",\"OLDAP-2.5\",\"OLDAP-2.6\",\"OLDAP-2.7\",\"OLDAP-2.8\",\"OML\",\"OPL-1.0\",\"OSL-1.0\",\"OSL-1.1\",\"OSL-2.0\",\"OSL-2.1\",\"OSL-3.0\",\"OpenSSL\",\"OSET-PL-2.1\",\"PHP-3.0\",\"PHP-3.01\",\"Plexus\",\"PostgreSQL\",\"psfrag\",\"psutils\",\"Python-2.0\",\"QPL-1.0\",\"Qhull\",\"Rdisc\",\"RPSL-1.0\",\"RPL-1.1\",\"RPL-1.5\",\"RHeCos-1.1\",\"RSCPL\",\"RSA-MD\",\"Ruby\",\"SAX-PD\",\"Saxpath\",\"SCEA\",\"SWL\",\"SMPPL\",\"Sendmail\",\"SGI-B-1.0\",\"SGI-B-1.1\",\"SGI-B-2.0\",\"OFL-1.0\",\"OFL-1.1\",\"SimPL-2.0\",\"Sleepycat\",\"SNIA\",\"Spencer-86\",\"Spencer-94\",\"Spencer-99\",\"SMLNJ\",\"SugarCRM-1.1.3\",\"SISSL\",\"SISSL-1.2\",\"SPL-1.0\",\"Watcom-1.0\",\"TCL\",\"Unlicense\",\"TMate\",\"TORQUE-1.1\",\"TOSL\",\"Unicode-TOU\",\"UPL-1.0\",\"NCSA\",\"Vim\",\"VOSTROM\",\"VSL-1.0\",\"W3C-19980720\",\"W3C\",\"Wsuipa\",\"Xnet\",\"X11\",\"Xerox\",\"XFree86-1.1\",\"xinetd\",\"xpp\",\"XSkat\",\"YPL-1.0\",\"YPL-1.1\",\"Zed\",\"Zend-2.0\",\"Zimbra-1.3\",\"Zimbra-1.4\",\"Zlib\",\"zlib-acknowledgement\",\"ZPL-1.1\",\"ZPL-2.0\",\"ZPL-2.1\",\"BSD-3-Clause-No-Nuclear-License\",\"BSD-3-Clause-No-Nuclear-Warranty\",\"BSD-3-Clause-No-Nuclear-License-2014\",\"eCos-2.0\",\"GPL-2.0-with-autoconf-exception\",\"GPL-2.0-with-bison-exception\",\"GPL-2.0-with-classpath-exception\",\"GPL-2.0-with-font-exception\",\"GPL-2.0-with-GCC-exception\",\"GPL-3.0-with-autoconf-exception\",\"GPL-3.0-with-GCC-exception\",\"StandardML-NJ\",\"WXwindows\"]"); /***/ }), -/* 540 */ +/* 529 */ /***/ (function(module, exports, __webpack_require__) { -var core = __webpack_require__(533); -var fs = __webpack_require__(23); -var path = __webpack_require__(16); -var caller = __webpack_require__(536); -var nodeModulesPaths = __webpack_require__(537); -var normalizeOptions = __webpack_require__(539); - -var defaultIsFile = function isFile(file) { - try { - var stat = fs.statSync(file); - } catch (e) { - if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; - throw e; - } - return stat.isFile() || stat.isFIFO(); -}; +"use strict"; -module.exports = function (x, options) { - if (typeof x !== 'string') { - throw new TypeError('Path must be a string.'); - } - var opts = normalizeOptions(x, options); +var url = __webpack_require__(439) +var gitHosts = __webpack_require__(530) +var GitHost = module.exports = __webpack_require__(531) - var isFile = opts.isFile || defaultIsFile; - var readFileSync = opts.readFileSync || fs.readFileSync; +var protocolToRepresentationMap = { + 'git+ssh': 'sshurl', + 'git+https': 'https', + 'ssh': 'sshurl', + 'git': 'git' +} - var extensions = opts.extensions || ['.js']; - var basedir = opts.basedir || path.dirname(caller()); - var parent = opts.filename || basedir; +function protocolToRepresentation (protocol) { + if (protocol.substr(-1) === ':') protocol = protocol.slice(0, -1) + return protocolToRepresentationMap[protocol] || protocol +} - opts.paths = opts.paths || []; +var authProtocols = { + 'git:': true, + 'https:': true, + 'git+https:': true, + 'http:': true, + 'git+http:': true +} - // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory - var absoluteStart = path.resolve(basedir); +var cache = {} - if (opts.preserveSymlinks === false) { - try { - absoluteStart = fs.realpathSync(absoluteStart); - } catch (realPathErr) { - if (realPathErr.code !== 'ENOENT') { - throw realPathErr; - } - } - } +module.exports.fromUrl = function (giturl, opts) { + var key = giturl + JSON.stringify(opts || {}) - if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { - var res = path.resolve(absoluteStart, x); - if (x === '..' || x.slice(-1) === '/') res += '/'; - var m = loadAsFileSync(res) || loadAsDirectorySync(res); - if (m) return m; - } else { - var n = loadNodeModulesSync(x, absoluteStart); - if (n) return n; - } + if (!(key in cache)) { + cache[key] = fromUrl(giturl, opts) + } - if (core[x]) return x; + return cache[key] +} - var err = new Error("Cannot find module '" + x + "' from '" + parent + "'"); - err.code = 'MODULE_NOT_FOUND'; - throw err; +function fromUrl (giturl, opts) { + if (giturl == null || giturl === '') return + var url = fixupUnqualifiedGist( + isGitHubShorthand(giturl) ? 'github:' + giturl : giturl + ) + var parsed = parseGitUrl(url) + var shortcutMatch = url.match(new RegExp('^([^:]+):(?:(?:[^@:]+(?:[^@]+)?@)?([^/]*))[/](.+?)(?:[.]git)?($|#)')) + var matches = Object.keys(gitHosts).map(function (gitHostName) { + try { + var gitHostInfo = gitHosts[gitHostName] + var auth = null + if (parsed.auth && authProtocols[parsed.protocol]) { + auth = decodeURIComponent(parsed.auth) + } + var committish = parsed.hash ? decodeURIComponent(parsed.hash.substr(1)) : null + var user = null + var project = null + var defaultRepresentation = null + if (shortcutMatch && shortcutMatch[1] === gitHostName) { + user = shortcutMatch[2] && decodeURIComponent(shortcutMatch[2]) + project = decodeURIComponent(shortcutMatch[3]) + defaultRepresentation = 'shortcut' + } else { + if (parsed.host !== gitHostInfo.domain) return + if (!gitHostInfo.protocols_re.test(parsed.protocol)) return + if (!parsed.path) return + var pathmatch = gitHostInfo.pathmatch + var matched = parsed.path.match(pathmatch) + if (!matched) return + if (matched[1] != null) user = decodeURIComponent(matched[1].replace(/^:/, '')) + if (matched[2] != null) project = decodeURIComponent(matched[2]) + defaultRepresentation = protocolToRepresentation(parsed.protocol) + } + return new GitHost(gitHostName, user, auth, project, committish, defaultRepresentation, opts) + } catch (ex) { + if (!(ex instanceof URIError)) throw ex + } + }).filter(function (gitHostInfo) { return gitHostInfo }) + if (matches.length !== 1) return + return matches[0] +} - function loadAsFileSync(x) { - var pkg = loadpkg(path.dirname(x)); +function isGitHubShorthand (arg) { + // Note: This does not fully test the git ref format. + // See https://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html + // + // The only way to do this properly would be to shell out to + // git-check-ref-format, and as this is a fast sync function, + // we don't want to do that. Just let git fail if it turns + // out that the commit-ish is invalid. + // GH usernames cannot start with . or - + return /^[^:@%/\s.-][^:@%/\s]*[/][^:@\s/%]+(?:#.*)?$/.test(arg) +} - if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) { - var rfile = path.relative(pkg.dir, x); - var r = opts.pathFilter(pkg.pkg, x, rfile); - if (r) { - x = path.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign - } - } +function fixupUnqualifiedGist (giturl) { + // necessary for round-tripping gists + var parsed = url.parse(giturl) + if (parsed.protocol === 'gist:' && parsed.host && !parsed.path) { + return parsed.protocol + '/' + parsed.host + } else { + return giturl + } +} - if (isFile(x)) { - return x; - } +function parseGitUrl (giturl) { + if (typeof giturl !== 'string') giturl = '' + giturl + var matched = giturl.match(/^([^@]+)@([^:/]+):[/]?((?:[^/]+[/])?[^/]+?)(?:[.]git)?(#.*)?$/) + if (!matched) return url.parse(giturl) + return { + protocol: 'git+ssh:', + slashes: true, + auth: matched[1], + host: matched[2], + port: null, + hostname: matched[2], + hash: matched[4], + search: null, + query: null, + pathname: '/' + matched[3], + path: '/' + matched[3], + href: 'git+ssh://' + matched[1] + '@' + matched[2] + + '/' + matched[3] + (matched[4] || '') + } +} - for (var i = 0; i < extensions.length; i++) { - var file = x + extensions[i]; - if (isFile(file)) { - return file; - } - } - } - function loadpkg(dir) { - if (dir === '' || dir === '/') return; - if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { - return; - } - if ((/[/\\]node_modules[/\\]*$/).test(dir)) return; +/***/ }), +/* 530 */ +/***/ (function(module, exports, __webpack_require__) { - var pkgfile = path.join(dir, 'package.json'); +"use strict"; - if (!isFile(pkgfile)) { - return loadpkg(path.dirname(dir)); - } - var body = readFileSync(pkgfile); +var gitHosts = module.exports = { + github: { + // First two are insecure and generally shouldn't be used any more, but + // they are still supported. + 'protocols': [ 'git', 'http', 'git+ssh', 'git+https', 'ssh', 'https' ], + 'domain': 'github.com', + 'treepath': 'tree', + 'filetemplate': 'https://{auth@}raw.githubusercontent.com/{user}/{project}/{committish}/{path}', + 'bugstemplate': 'https://{domain}/{user}/{project}/issues', + 'gittemplate': 'git://{auth@}{domain}/{user}/{project}.git{#committish}', + 'tarballtemplate': 'https://{domain}/{user}/{project}/archive/{committish}.tar.gz' + }, + bitbucket: { + 'protocols': [ 'git+ssh', 'git+https', 'ssh', 'https' ], + 'domain': 'bitbucket.org', + 'treepath': 'src', + 'tarballtemplate': 'https://{domain}/{user}/{project}/get/{committish}.tar.gz' + }, + gitlab: { + 'protocols': [ 'git+ssh', 'git+https', 'ssh', 'https' ], + 'domain': 'gitlab.com', + 'treepath': 'tree', + 'docstemplate': 'https://{domain}/{user}/{project}{/tree/committish}#README', + 'bugstemplate': 'https://{domain}/{user}/{project}/issues', + 'tarballtemplate': 'https://{domain}/{user}/{project}/repository/archive.tar.gz?ref={committish}' + }, + gist: { + 'protocols': [ 'git', 'git+ssh', 'git+https', 'ssh', 'https' ], + 'domain': 'gist.github.com', + 'pathmatch': /^[/](?:([^/]+)[/])?([a-z0-9]+)(?:[.]git)?$/, + 'filetemplate': 'https://gist.githubusercontent.com/{user}/{project}/raw{/committish}/{path}', + 'bugstemplate': 'https://{domain}/{project}', + 'gittemplate': 'git://{domain}/{project}.git{#committish}', + 'sshtemplate': 'git@{domain}:/{project}.git{#committish}', + 'sshurltemplate': 'git+ssh://git@{domain}/{project}.git{#committish}', + 'browsetemplate': 'https://{domain}/{project}{/committish}', + 'docstemplate': 'https://{domain}/{project}{/committish}', + 'httpstemplate': 'git+https://{domain}/{project}.git{#committish}', + 'shortcuttemplate': '{type}:{project}{#committish}', + 'pathtemplate': '{project}{#committish}', + 'tarballtemplate': 'https://{domain}/{user}/{project}/archive/{committish}.tar.gz' + } +} - try { - var pkg = JSON.parse(body); - } catch (jsonErr) {} +var gitHostDefaults = { + 'sshtemplate': 'git@{domain}:{user}/{project}.git{#committish}', + 'sshurltemplate': 'git+ssh://git@{domain}/{user}/{project}.git{#committish}', + 'browsetemplate': 'https://{domain}/{user}/{project}{/tree/committish}', + 'docstemplate': 'https://{domain}/{user}/{project}{/tree/committish}#readme', + 'httpstemplate': 'git+https://{auth@}{domain}/{user}/{project}.git{#committish}', + 'filetemplate': 'https://{domain}/{user}/{project}/raw/{committish}/{path}', + 'shortcuttemplate': '{type}:{user}/{project}{#committish}', + 'pathtemplate': '{user}/{project}{#committish}', + 'pathmatch': /^[/]([^/]+)[/]([^/]+?)(?:[.]git|[/])?$/ +} - if (pkg && opts.packageFilter) { - pkg = opts.packageFilter(pkg, dir); - } +Object.keys(gitHosts).forEach(function (name) { + Object.keys(gitHostDefaults).forEach(function (key) { + if (gitHosts[name][key]) return + gitHosts[name][key] = gitHostDefaults[key] + }) + gitHosts[name].protocols_re = RegExp('^(' + + gitHosts[name].protocols.map(function (protocol) { + return protocol.replace(/([\\+*{}()[\]$^|])/g, '\\$1') + }).join('|') + '):$') +}) - return { pkg: pkg, dir: dir }; - } - function loadAsDirectorySync(x) { - var pkgfile = path.join(x, '/package.json'); - if (isFile(pkgfile)) { - try { - var body = readFileSync(pkgfile, 'UTF8'); - var pkg = JSON.parse(body); - } catch (e) {} +/***/ }), +/* 531 */ +/***/ (function(module, exports, __webpack_require__) { - if (opts.packageFilter) { - pkg = opts.packageFilter(pkg, x); - } +"use strict"; - if (pkg.main) { - if (typeof pkg.main !== 'string') { - var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); - mainError.code = 'INVALID_PACKAGE_MAIN'; - throw mainError; - } - if (pkg.main === '.' || pkg.main === './') { - pkg.main = 'index'; - } - try { - var m = loadAsFileSync(path.resolve(x, pkg.main)); - if (m) return m; - var n = loadAsDirectorySync(path.resolve(x, pkg.main)); - if (n) return n; - } catch (e) {} - } - } +var gitHosts = __webpack_require__(530) +var extend = Object.assign || __webpack_require__(397)._extend - return loadAsFileSync(path.join(x, '/index')); - } +var GitHost = module.exports = function (type, user, auth, project, committish, defaultRepresentation, opts) { + var gitHostInfo = this + gitHostInfo.type = type + Object.keys(gitHosts[type]).forEach(function (key) { + gitHostInfo[key] = gitHosts[type][key] + }) + gitHostInfo.user = user + gitHostInfo.auth = auth + gitHostInfo.project = project + gitHostInfo.committish = committish + gitHostInfo.default = defaultRepresentation + gitHostInfo.opts = opts || {} +} +GitHost.prototype = {} - function loadNodeModulesSync(x, start) { - var dirs = nodeModulesPaths(start, opts, x); - for (var i = 0; i < dirs.length; i++) { - var dir = dirs[i]; - var m = loadAsFileSync(path.join(dir, '/', x)); - if (m) return m; - var n = loadAsDirectorySync(path.join(dir, '/', x)); - if (n) return n; - } - } -}; +GitHost.prototype.hash = function () { + return this.committish ? '#' + this.committish : '' +} +GitHost.prototype._fill = function (template, opts) { + if (!template) return + var vars = extend({}, opts) + opts = extend(extend({}, this.opts), opts) + var self = this + Object.keys(this).forEach(function (key) { + if (self[key] != null && vars[key] == null) vars[key] = self[key] + }) + var rawAuth = vars.auth + var rawComittish = vars.committish + Object.keys(vars).forEach(function (key) { + vars[key] = encodeURIComponent(vars[key]) + }) + vars['auth@'] = rawAuth ? rawAuth + '@' : '' + if (opts.noCommittish) { + vars['#committish'] = '' + vars['/tree/committish'] = '' + vars['/comittish'] = '' + vars.comittish = '' + } else { + vars['#committish'] = rawComittish ? '#' + rawComittish : '' + vars['/tree/committish'] = vars.committish + ? '/' + vars.treepath + '/' + vars.committish + : '' + vars['/committish'] = vars.committish ? '/' + vars.committish : '' + vars.committish = vars.committish || 'master' + } + var res = template + Object.keys(vars).forEach(function (key) { + res = res.replace(new RegExp('[{]' + key + '[}]', 'g'), vars[key]) + }) + if (opts.noGitPlus) { + return res.replace(/^git[+]/, '') + } else { + return res + } +} -/***/ }), -/* 541 */ -/***/ (function(module, exports) { +GitHost.prototype.ssh = function (opts) { + return this._fill(this.sshtemplate, opts) +} -module.exports = extractDescription +GitHost.prototype.sshurl = function (opts) { + return this._fill(this.sshurltemplate, opts) +} -// Extracts description from contents of a readme file in markdown format -function extractDescription (d) { - if (!d) return; - if (d === "ERROR: No README data found!") return; - // the first block of text before the first heading - // that isn't the first line heading - d = d.trim().split('\n') - for (var s = 0; d[s] && d[s].trim().match(/^(#|$)/); s ++); - var l = d.length - for (var e = s + 1; e < l && d[e].trim(); e ++); - return d.slice(s, e).join(' ').trim() +GitHost.prototype.browse = function (opts) { + return this._fill(this.browsetemplate, opts) } +GitHost.prototype.docs = function (opts) { + return this._fill(this.docstemplate, opts) +} -/***/ }), -/* 542 */ -/***/ (function(module) { +GitHost.prototype.bugs = function (opts) { + return this._fill(this.bugstemplate, opts) +} -module.exports = JSON.parse("{\"topLevel\":{\"dependancies\":\"dependencies\",\"dependecies\":\"dependencies\",\"depdenencies\":\"dependencies\",\"devEependencies\":\"devDependencies\",\"depends\":\"dependencies\",\"dev-dependencies\":\"devDependencies\",\"devDependences\":\"devDependencies\",\"devDepenencies\":\"devDependencies\",\"devdependencies\":\"devDependencies\",\"repostitory\":\"repository\",\"repo\":\"repository\",\"prefereGlobal\":\"preferGlobal\",\"hompage\":\"homepage\",\"hampage\":\"homepage\",\"autohr\":\"author\",\"autor\":\"author\",\"contributers\":\"contributors\",\"publicationConfig\":\"publishConfig\",\"script\":\"scripts\"},\"bugs\":{\"web\":\"url\",\"name\":\"url\"},\"script\":{\"server\":\"start\",\"tests\":\"test\"}}"); +GitHost.prototype.https = function (opts) { + return this._fill(this.httpstemplate, opts) +} -/***/ }), -/* 543 */ -/***/ (function(module, exports, __webpack_require__) { +GitHost.prototype.git = function (opts) { + return this._fill(this.gittemplate, opts) +} -var util = __webpack_require__(29) -var messages = __webpack_require__(544) +GitHost.prototype.shortcut = function (opts) { + return this._fill(this.shortcuttemplate, opts) +} -module.exports = function() { - var args = Array.prototype.slice.call(arguments, 0) - var warningName = args.shift() - if (warningName == "typo") { - return makeTypoWarning.apply(null,args) - } - else { - var msgTemplate = messages[warningName] ? messages[warningName] : warningName + ": '%s'" - args.unshift(msgTemplate) - return util.format.apply(null, args) - } +GitHost.prototype.path = function (opts) { + return this._fill(this.pathtemplate, opts) } -function makeTypoWarning (providedName, probableName, field) { - if (field) { - providedName = field + "['" + providedName + "']" - probableName = field + "['" + probableName + "']" - } - return util.format(messages.typo, providedName, probableName) +GitHost.prototype.tarball = function (opts) { + return this._fill(this.tarballtemplate, opts) +} + +GitHost.prototype.file = function (P, opts) { + return this._fill(this.filetemplate, extend({ + path: P.replace(/^[/]+/g, '') + }, opts)) } +GitHost.prototype.getDefaultRepresentation = function () { + return this.default +} -/***/ }), -/* 544 */ -/***/ (function(module) { +GitHost.prototype.toString = function (opts) { + return (this[this.default] || this.sshurl).call(this, opts) +} -module.exports = JSON.parse("{\"repositories\":\"'repositories' (plural) Not supported. Please pick one as the 'repository' field\",\"missingRepository\":\"No repository field.\",\"brokenGitUrl\":\"Probably broken git url: %s\",\"nonObjectScripts\":\"scripts must be an object\",\"nonStringScript\":\"script values must be string commands\",\"nonArrayFiles\":\"Invalid 'files' member\",\"invalidFilename\":\"Invalid filename in 'files' list: %s\",\"nonArrayBundleDependencies\":\"Invalid 'bundleDependencies' list. Must be array of package names\",\"nonStringBundleDependency\":\"Invalid bundleDependencies member: %s\",\"nonDependencyBundleDependency\":\"Non-dependency in bundleDependencies: %s\",\"nonObjectDependencies\":\"%s field must be an object\",\"nonStringDependency\":\"Invalid dependency: %s %s\",\"deprecatedArrayDependencies\":\"specifying %s as array is deprecated\",\"deprecatedModules\":\"modules field is deprecated\",\"nonArrayKeywords\":\"keywords should be an array of strings\",\"nonStringKeyword\":\"keywords should be an array of strings\",\"conflictingName\":\"%s is also the name of a node core module.\",\"nonStringDescription\":\"'description' field should be a string\",\"missingDescription\":\"No description\",\"missingReadme\":\"No README data\",\"missingLicense\":\"No license field.\",\"nonEmailUrlBugsString\":\"Bug string field must be url, email, or {email,url}\",\"nonUrlBugsUrlField\":\"bugs.url field must be a string url. Deleted.\",\"nonEmailBugsEmailField\":\"bugs.email field must be a string email. Deleted.\",\"emptyNormalizedBugs\":\"Normalized value of bugs field is an empty object. Deleted.\",\"nonUrlHomepage\":\"homepage field must be a string url. Deleted.\",\"invalidLicense\":\"license should be a valid SPDX license expression\",\"typo\":\"%s should probably be %s.\"}"); /***/ }), -/* 545 */ +/* 532 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - -const path = __webpack_require__(16); -const writeJsonFile = __webpack_require__(546); -const sortKeys = __webpack_require__(558); - -const dependencyKeys = new Set([ - 'dependencies', - 'devDependencies', - 'optionalDependencies', - 'peerDependencies' -]); - -function normalize(packageJson) { - const result = {}; +var core = __webpack_require__(533); +var async = __webpack_require__(535); +async.core = core; +async.isCore = function isCore(x) { return core[x]; }; +async.sync = __webpack_require__(540); - for (const key of Object.keys(packageJson)) { - if (!dependencyKeys.has(key)) { - result[key] = packageJson[key]; - } else if (Object.keys(packageJson[key]).length !== 0) { - result[key] = sortKeys(packageJson[key]); - } - } +exports = async; +module.exports = async; - return result; -} -module.exports = async (filePath, data, options) => { - if (typeof filePath !== 'string') { - options = data; - data = filePath; - filePath = '.'; - } +/***/ }), +/* 533 */ +/***/ (function(module, exports, __webpack_require__) { - options = { - normalize: true, - ...options, - detectIndent: true - }; +var current = (process.versions && process.versions.node && process.versions.node.split('.')) || []; - filePath = path.basename(filePath) === 'package.json' ? filePath : path.join(filePath, 'package.json'); +function specifierIncluded(specifier) { + var parts = specifier.split(' '); + var op = parts.length > 1 ? parts[0] : '='; + var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); - data = options.normalize ? normalize(data) : data; + for (var i = 0; i < 3; ++i) { + var cur = Number(current[i] || 0); + var ver = Number(versionParts[i] || 0); + if (cur === ver) { + continue; // eslint-disable-line no-restricted-syntax, no-continue + } + if (op === '<') { + return cur < ver; + } else if (op === '>=') { + return cur >= ver; + } else { + return false; + } + } + return op === '>='; +} - return writeJsonFile(filePath, data, options); -}; +function matchesRange(range) { + var specifiers = range.split(/ ?&& ?/); + if (specifiers.length === 0) { return false; } + for (var i = 0; i < specifiers.length; ++i) { + if (!specifierIncluded(specifiers[i])) { return false; } + } + return true; +} -module.exports.sync = (filePath, data, options) => { - if (typeof filePath !== 'string') { - options = data; - data = filePath; - filePath = '.'; - } +function versionIncluded(specifierValue) { + if (typeof specifierValue === 'boolean') { return specifierValue; } + if (specifierValue && typeof specifierValue === 'object') { + for (var i = 0; i < specifierValue.length; ++i) { + if (matchesRange(specifierValue[i])) { return true; } + } + return false; + } + return matchesRange(specifierValue); +} - options = { - normalize: true, - ...options, - detectIndent: true - }; +var data = __webpack_require__(534); - filePath = path.basename(filePath) === 'package.json' ? filePath : path.join(filePath, 'package.json'); +var core = {}; +for (var mod in data) { // eslint-disable-line no-restricted-syntax + if (Object.prototype.hasOwnProperty.call(data, mod)) { + core[mod] = versionIncluded(data[mod]); + } +} +module.exports = core; - data = options.normalize ? normalize(data) : data; - writeJsonFile.sync(filePath, data, options); -}; +/***/ }), +/* 534 */ +/***/ (function(module) { +module.exports = JSON.parse("{\"assert\":true,\"async_hooks\":\">= 8\",\"buffer_ieee754\":\"< 0.9.7\",\"buffer\":true,\"child_process\":true,\"cluster\":true,\"console\":true,\"constants\":true,\"crypto\":true,\"_debugger\":\"< 8\",\"dgram\":true,\"dns\":true,\"domain\":true,\"events\":true,\"freelist\":\"< 6\",\"fs\":true,\"fs/promises\":\">= 10 && < 10.1\",\"_http_agent\":\">= 0.11.1\",\"_http_client\":\">= 0.11.1\",\"_http_common\":\">= 0.11.1\",\"_http_incoming\":\">= 0.11.1\",\"_http_outgoing\":\">= 0.11.1\",\"_http_server\":\">= 0.11.1\",\"http\":true,\"http2\":\">= 8.8\",\"https\":true,\"inspector\":\">= 8.0.0\",\"_linklist\":\"< 8\",\"module\":true,\"net\":true,\"node-inspect/lib/_inspect\":\">= 7.6.0\",\"node-inspect/lib/internal/inspect_client\":\">= 7.6.0\",\"node-inspect/lib/internal/inspect_repl\":\">= 7.6.0\",\"os\":true,\"path\":true,\"perf_hooks\":\">= 8.5\",\"process\":\">= 1\",\"punycode\":true,\"querystring\":true,\"readline\":true,\"repl\":true,\"smalloc\":\">= 0.11.5 && < 3\",\"_stream_duplex\":\">= 0.9.4\",\"_stream_transform\":\">= 0.9.4\",\"_stream_wrap\":\">= 1.4.1\",\"_stream_passthrough\":\">= 0.9.4\",\"_stream_readable\":\">= 0.9.4\",\"_stream_writable\":\">= 0.9.4\",\"stream\":true,\"string_decoder\":true,\"sys\":true,\"timers\":true,\"_tls_common\":\">= 0.11.13\",\"_tls_legacy\":\">= 0.11.3 && < 10\",\"_tls_wrap\":\">= 0.11.3\",\"tls\":true,\"trace_events\":\">= 10\",\"tty\":true,\"url\":true,\"util\":true,\"v8/tools/arguments\":\">= 10\",\"v8/tools/codemap\":[\">= 4.4.0 && < 5\",\">= 5.2.0\"],\"v8/tools/consarray\":[\">= 4.4.0 && < 5\",\">= 5.2.0\"],\"v8/tools/csvparser\":[\">= 4.4.0 && < 5\",\">= 5.2.0\"],\"v8/tools/logreader\":[\">= 4.4.0 && < 5\",\">= 5.2.0\"],\"v8/tools/profile_view\":[\">= 4.4.0 && < 5\",\">= 5.2.0\"],\"v8/tools/splaytree\":[\">= 4.4.0 && < 5\",\">= 5.2.0\"],\"v8\":\">= 1\",\"vm\":true,\"worker_threads\":\">= 11.7\",\"zlib\":true}"); /***/ }), -/* 546 */ +/* 535 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - -const path = __webpack_require__(16); -const fs = __webpack_require__(547); -const writeFileAtomic = __webpack_require__(551); -const sortKeys = __webpack_require__(558); -const makeDir = __webpack_require__(560); -const pify = __webpack_require__(561); -const detectIndent = __webpack_require__(562); +var core = __webpack_require__(533); +var fs = __webpack_require__(349); +var path = __webpack_require__(4); +var caller = __webpack_require__(536); +var nodeModulesPaths = __webpack_require__(537); +var normalizeOptions = __webpack_require__(539); -const init = (fn, filePath, data, options) => { - if (!filePath) { - throw new TypeError('Expected a filepath'); - } +var defaultIsFile = function isFile(file, cb) { + fs.stat(file, function (err, stat) { + if (!err) { + return cb(null, stat.isFile() || stat.isFIFO()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); +}; - if (data === undefined) { - throw new TypeError('Expected data to stringify'); - } +module.exports = function resolve(x, options, callback) { + var cb = callback; + var opts = options; + if (typeof options === 'function') { + cb = opts; + opts = {}; + } + if (typeof x !== 'string') { + var err = new TypeError('Path must be a string.'); + return process.nextTick(function () { + cb(err); + }); + } - options = Object.assign({ - indent: '\t', - sortKeys: false - }, options); + opts = normalizeOptions(x, opts); - if (options.sortKeys) { - data = sortKeys(data, { - deep: true, - compare: typeof options.sortKeys === 'function' ? options.sortKeys : undefined - }); - } + var isFile = opts.isFile || defaultIsFile; + var readFile = opts.readFile || fs.readFile; - return fn(filePath, data, options); -}; + var extensions = opts.extensions || ['.js']; + var basedir = opts.basedir || path.dirname(caller()); + var parent = opts.filename || basedir; -const readFile = filePath => pify(fs.readFile)(filePath, 'utf8').catch(() => {}); + opts.paths = opts.paths || []; -const main = (filePath, data, options) => { - return (options.detectIndent ? readFile(filePath) : Promise.resolve()) - .then(string => { - const indent = string ? detectIndent(string).indent : options.indent; - const json = JSON.stringify(data, options.replacer, indent); + // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory + var absoluteStart = path.resolve(basedir); - return pify(writeFileAtomic)(filePath, `${json}\n`, {mode: options.mode}); - }); -}; + if (opts.preserveSymlinks === false) { + fs.realpath(absoluteStart, function (realPathErr, realStart) { + if (realPathErr && realPathErr.code !== 'ENOENT') cb(err); + else init(realPathErr ? absoluteStart : realStart); + }); + } else { + init(absoluteStart); + } -const mainSync = (filePath, data, options) => { - let {indent} = options; + var res; + function init(basedir) { + if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { + res = path.resolve(basedir, x); + if (x === '..' || x.slice(-1) === '/') res += '/'; + if ((/\/$/).test(x) && res === basedir) { + loadAsDirectory(res, opts.package, onfile); + } else loadAsFile(res, opts.package, onfile); + } else loadNodeModules(x, basedir, function (err, n, pkg) { + if (err) cb(err); + else if (n) cb(null, n, pkg); + else if (core[x]) return cb(null, x); + else { + var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + moduleError.code = 'MODULE_NOT_FOUND'; + cb(moduleError); + } + }); + } - if (options.detectIndent) { - try { - const file = fs.readFileSync(filePath, 'utf8'); - indent = detectIndent(file).indent; - } catch (error) { - if (error.code !== 'ENOENT') { - throw error; - } - } - } + function onfile(err, m, pkg) { + if (err) cb(err); + else if (m) cb(null, m, pkg); + else loadAsDirectory(res, function (err, d, pkg) { + if (err) cb(err); + else if (d) cb(null, d, pkg); + else { + var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + moduleError.code = 'MODULE_NOT_FOUND'; + cb(moduleError); + } + }); + } - const json = JSON.stringify(data, options.replacer, indent); + function loadAsFile(x, thePackage, callback) { + var loadAsFilePackage = thePackage; + var cb = callback; + if (typeof loadAsFilePackage === 'function') { + cb = loadAsFilePackage; + loadAsFilePackage = undefined; + } - return writeFileAtomic.sync(filePath, `${json}\n`, {mode: options.mode}); -}; + var exts = [''].concat(extensions); + load(exts, x, loadAsFilePackage); -const writeJsonFile = (filePath, data, options) => { - return makeDir(path.dirname(filePath), {fs}) - .then(() => init(main, filePath, data, options)); -}; + function load(exts, x, loadPackage) { + if (exts.length === 0) return cb(null, undefined, loadPackage); + var file = x + exts[0]; -module.exports = writeJsonFile; -// TODO: Remove this for the next major release -module.exports.default = writeJsonFile; -module.exports.sync = (filePath, data, options) => { - makeDir.sync(path.dirname(filePath), {fs}); - init(mainSync, filePath, data, options); -}; + var pkg = loadPackage; + if (pkg) onpkg(null, pkg); + else loadpkg(path.dirname(file), onpkg); + function onpkg(err, pkg_, dir) { + pkg = pkg_; + if (err) return cb(err); + if (dir && pkg && opts.pathFilter) { + var rfile = path.relative(dir, file); + var rel = rfile.slice(0, rfile.length - exts[0].length); + var r = opts.pathFilter(pkg, x, rel); + if (r) return load( + [''].concat(extensions.slice()), + path.resolve(dir, r), + pkg + ); + } + isFile(file, onex); + } + function onex(err, ex) { + if (err) return cb(err); + if (ex) return cb(null, file, pkg); + load(exts.slice(1), x, pkg); + } + } + } -/***/ }), -/* 547 */ -/***/ (function(module, exports, __webpack_require__) { + function loadpkg(dir, cb) { + if (dir === '' || dir === '/') return cb(null); + if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { + return cb(null); + } + if ((/[/\\]node_modules[/\\]*$/).test(dir)) return cb(null); -var fs = __webpack_require__(23) -var polyfills = __webpack_require__(548) -var legacy = __webpack_require__(549) -var clone = __webpack_require__(550) + var pkgfile = path.join(dir, 'package.json'); + isFile(pkgfile, function (err, ex) { + // on err, ex is false + if (!ex) return loadpkg(path.dirname(dir), cb); -var queue = [] + readFile(pkgfile, function (err, body) { + if (err) cb(err); + try { var pkg = JSON.parse(body); } catch (jsonErr) {} -var util = __webpack_require__(29) + if (pkg && opts.packageFilter) { + pkg = opts.packageFilter(pkg, pkgfile); + } + cb(null, pkg, dir); + }); + }); + } -function noop () {} + function loadAsDirectory(x, loadAsDirectoryPackage, callback) { + var cb = callback; + var fpkg = loadAsDirectoryPackage; + if (typeof fpkg === 'function') { + cb = fpkg; + fpkg = opts.package; + } -var debug = noop -if (util.debuglog) - debug = util.debuglog('gfs4') -else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) - debug = function() { - var m = util.format.apply(util, arguments) - m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') - console.error(m) - } + var pkgfile = path.join(x, 'package.json'); + isFile(pkgfile, function (err, ex) { + if (err) return cb(err); + if (!ex) return loadAsFile(path.join(x, 'index'), fpkg, cb); -if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug(queue) - __webpack_require__(30).equal(queue.length, 0) - }) -} + readFile(pkgfile, function (err, body) { + if (err) return cb(err); + try { + var pkg = JSON.parse(body); + } catch (jsonErr) {} -module.exports = patch(clone(fs)) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { - module.exports = patch(fs) - fs.__patched = true; -} + if (opts.packageFilter) { + pkg = opts.packageFilter(pkg, pkgfile); + } -// Always patch fs.close/closeSync, because we want to -// retry() whenever a close happens *anywhere* in the program. -// This is essential when multiple graceful-fs instances are -// in play at the same time. -module.exports.close = (function (fs$close) { return function (fd, cb) { - return fs$close.call(fs, fd, function (err) { - if (!err) - retry() + if (pkg.main) { + if (typeof pkg.main !== 'string') { + var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); + mainError.code = 'INVALID_PACKAGE_MAIN'; + return cb(mainError); + } + if (pkg.main === '.' || pkg.main === './') { + pkg.main = 'index'; + } + loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) { + if (err) return cb(err); + if (m) return cb(null, m, pkg); + if (!pkg) return loadAsFile(path.join(x, 'index'), pkg, cb); - if (typeof cb === 'function') - cb.apply(this, arguments) - }) -}})(fs.close) + var dir = path.resolve(x, pkg.main); + loadAsDirectory(dir, pkg, function (err, n, pkg) { + if (err) return cb(err); + if (n) return cb(null, n, pkg); + loadAsFile(path.join(x, 'index'), pkg, cb); + }); + }); + return; + } -module.exports.closeSync = (function (fs$closeSync) { return function (fd) { - // Note that graceful-fs also retries when fs.closeSync() fails. - // Looks like a bug to me, although it's probably a harmless one. - var rval = fs$closeSync.apply(fs, arguments) - retry() - return rval -}})(fs.closeSync) + loadAsFile(path.join(x, '/index'), pkg, cb); + }); + }); + } -// Only patch fs once, otherwise we'll run into a memory leak if -// graceful-fs is loaded multiple times, such as in test environments that -// reset the loaded modules between tests. -// We look for the string `graceful-fs` from the comment above. This -// way we are not adding any extra properties and it will detect if older -// versions of graceful-fs are installed. -if (!/\bgraceful-fs\b/.test(fs.closeSync.toString())) { - fs.closeSync = module.exports.closeSync; - fs.close = module.exports.close; -} + function processDirs(cb, dirs) { + if (dirs.length === 0) return cb(null, undefined); + var dir = dirs[0]; -function patch (fs) { - // Everything that references the open() function needs to be in here - polyfills(fs) - fs.gracefulify = patch - fs.FileReadStream = ReadStream; // Legacy name. - fs.FileWriteStream = WriteStream; // Legacy name. - fs.createReadStream = createReadStream - fs.createWriteStream = createWriteStream - var fs$readFile = fs.readFile - fs.readFile = readFile - function readFile (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null + var file = path.join(dir, x); + loadAsFile(file, opts.package, onfile); - return go$readFile(path, options, cb) + function onfile(err, m, pkg) { + if (err) return cb(err); + if (m) return cb(null, m, pkg); + loadAsDirectory(path.join(dir, x), opts.package, ondir); + } - function go$readFile (path, options, cb) { - return fs$readFile(path, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readFile, [path, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() + function ondir(err, n, pkg) { + if (err) return cb(err); + if (n) return cb(null, n, pkg); + processDirs(cb, dirs.slice(1)); } - }) } - } + function loadNodeModules(x, start, cb) { + processDirs(cb, nodeModulesPaths(start, opts, x)); + } +}; - var fs$writeFile = fs.writeFile - fs.writeFile = writeFile - function writeFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null - return go$writeFile(path, data, options, cb) +/***/ }), +/* 536 */ +/***/ (function(module, exports) { - function go$writeFile (path, data, options, cb) { - return fs$writeFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$writeFile, [path, data, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } +module.exports = function () { + // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi + var origPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = function (_, stack) { return stack; }; + var stack = (new Error()).stack; + Error.prepareStackTrace = origPrepareStackTrace; + return stack[2].getFileName(); +}; - var fs$appendFile = fs.appendFile - if (fs$appendFile) - fs.appendFile = appendFile - function appendFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null - return go$appendFile(path, data, options, cb) +/***/ }), +/* 537 */ +/***/ (function(module, exports, __webpack_require__) { - function go$appendFile (path, data, options, cb) { - return fs$appendFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$appendFile, [path, data, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } +var path = __webpack_require__(4); +var parse = path.parse || __webpack_require__(538); - var fs$readdir = fs.readdir - fs.readdir = readdir - function readdir (path, options, cb) { - var args = [path] - if (typeof options !== 'function') { - args.push(options) - } else { - cb = options +var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) { + var prefix = '/'; + if ((/^([A-Za-z]:)/).test(absoluteStart)) { + prefix = ''; + } else if ((/^\\\\/).test(absoluteStart)) { + prefix = '\\\\'; } - args.push(go$readdir$cb) - return go$readdir(args) + var paths = [absoluteStart]; + var parsed = parse(absoluteStart); + while (parsed.dir !== paths[paths.length - 1]) { + paths.push(parsed.dir); + parsed = parse(parsed.dir); + } - function go$readdir$cb (err, files) { - if (files && files.sort) - files.sort() + return paths.reduce(function (dirs, aPath) { + return dirs.concat(modules.map(function (moduleDir) { + return path.join(prefix, aPath, moduleDir); + })); + }, []); +}; - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readdir, [args]]) +module.exports = function nodeModulesPaths(start, opts, request) { + var modules = opts && opts.moduleDirectory + ? [].concat(opts.moduleDirectory) + : ['node_modules']; - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } + if (opts && typeof opts.paths === 'function') { + return opts.paths( + request, + start, + function () { return getNodeModulesDirs(start, modules); }, + opts + ); } - } - function go$readdir (args) { - return fs$readdir.apply(fs, args) - } + var dirs = getNodeModulesDirs(start, modules); + return opts && opts.paths ? dirs.concat(opts.paths) : dirs; +}; - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs) - ReadStream = legStreams.ReadStream - WriteStream = legStreams.WriteStream - } - var fs$ReadStream = fs.ReadStream - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open - } +/***/ }), +/* 538 */ +/***/ (function(module, exports, __webpack_require__) { - var fs$WriteStream = fs.WriteStream - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype) - WriteStream.prototype.open = WriteStream$open - } +"use strict"; - fs.ReadStream = ReadStream - fs.WriteStream = WriteStream - function ReadStream (path, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments) - } +var isWindows = process.platform === 'win32'; - function ReadStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - if (that.autoClose) - that.destroy() +// Regex to split a windows path into three parts: [*, device, slash, +// tail] windows-only +var splitDeviceRe = + /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - that.read() - } - }) - } +// Regex to split the tail part of the above into [*, dir, basename, ext] +var splitTailRe = + /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/; - function WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } +var win32 = {}; - function WriteStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - that.destroy() - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - } - }) - } +// Function to split a filename into [root, dir, basename, ext] +function win32SplitPath(filename) { + // Separate device+slash from tail + var result = splitDeviceRe.exec(filename), + device = (result[1] || '') + (result[2] || ''), + tail = result[3] || ''; + // Split the tail into dir, basename and extension + var result2 = splitTailRe.exec(tail), + dir = result2[1], + basename = result2[2], + ext = result2[3]; + return [device, dir, basename, ext]; +} - function createReadStream (path, options) { - return new ReadStream(path, options) +win32.parse = function(pathString) { + if (typeof pathString !== 'string') { + throw new TypeError( + "Parameter 'pathString' must be a string, not " + typeof pathString + ); } - - function createWriteStream (path, options) { - return new WriteStream(path, options) + var allParts = win32SplitPath(pathString); + if (!allParts || allParts.length !== 4) { + throw new TypeError("Invalid path '" + pathString + "'"); } + return { + root: allParts[0], + dir: allParts[0] + allParts[1].slice(0, -1), + base: allParts[2], + ext: allParts[3], + name: allParts[2].slice(0, allParts[2].length - allParts[3].length) + }; +}; - var fs$open = fs.open - fs.open = open - function open (path, flags, mode, cb) { - if (typeof mode === 'function') - cb = mode, mode = null - return go$open(path, flags, mode, cb) - function go$open (path, flags, mode, cb) { - return fs$open(path, flags, mode, function (err, fd) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$open, [path, flags, mode, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var posix = {}; - return fs -} -function enqueue (elem) { - debug('ENQUEUE', elem[0].name, elem[1]) - queue.push(elem) +function posixSplitPath(filename) { + return splitPathRe.exec(filename).slice(1); } -function retry () { - var elem = queue.shift() - if (elem) { - debug('RETRY', elem[0].name, elem[1]) - elem[0].apply(null, elem[1]) - } -} +posix.parse = function(pathString) { + if (typeof pathString !== 'string') { + throw new TypeError( + "Parameter 'pathString' must be a string, not " + typeof pathString + ); + } + var allParts = posixSplitPath(pathString); + if (!allParts || allParts.length !== 4) { + throw new TypeError("Invalid path '" + pathString + "'"); + } + allParts[1] = allParts[1] || ''; + allParts[2] = allParts[2] || ''; + allParts[3] = allParts[3] || ''; -/***/ }), -/* 548 */ -/***/ (function(module, exports, __webpack_require__) { + return { + root: allParts[0], + dir: allParts[0] + allParts[1].slice(0, -1), + base: allParts[2], + ext: allParts[3], + name: allParts[2].slice(0, allParts[2].length - allParts[3].length) + }; +}; -var constants = __webpack_require__(25) -var origCwd = process.cwd -var cwd = null +if (isWindows) + module.exports = win32.parse; +else /* posix */ + module.exports = posix.parse; -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform +module.exports.posix = posix.parse; +module.exports.win32 = win32.parse; -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd -} -try { - process.cwd() -} catch (er) {} -var chdir = process.chdir -process.chdir = function(d) { - cwd = null - chdir.call(process, d) -} +/***/ }), +/* 539 */ +/***/ (function(module, exports) { -module.exports = patch +module.exports = function (x, opts) { + /** + * This file is purposefully a passthrough. It's expected that third-party + * environments will override it at runtime in order to inject special logic + * into `resolve` (by manipulating the options). One such example is the PnP + * code path in Yarn. + */ -function patch (fs) { - // (re-)implement some things that are known busted or missing. + return opts || {}; +}; - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs) - } - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) - } +/***/ }), +/* 540 */ +/***/ (function(module, exports, __webpack_require__) { - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. +var core = __webpack_require__(533); +var fs = __webpack_require__(349); +var path = __webpack_require__(4); +var caller = __webpack_require__(536); +var nodeModulesPaths = __webpack_require__(537); +var normalizeOptions = __webpack_require__(539); - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) +var defaultIsFile = function isFile(file) { + try { + var stat = fs.statSync(file); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + return stat.isFile() || stat.isFIFO(); +}; - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) +module.exports = function (x, options) { + if (typeof x !== 'string') { + throw new TypeError('Path must be a string.'); + } + var opts = normalizeOptions(x, options); - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) + var isFile = opts.isFile || defaultIsFile; + var readFileSync = opts.readFileSync || fs.readFileSync; - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) + var extensions = opts.extensions || ['.js']; + var basedir = opts.basedir || path.dirname(caller()); + var parent = opts.filename || basedir; - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) + opts.paths = opts.paths || []; - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) + // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory + var absoluteStart = path.resolve(basedir); - // if lchmod/lchown do not exist, then make them no-ops - if (!fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb) + if (opts.preserveSymlinks === false) { + try { + absoluteStart = fs.realpathSync(absoluteStart); + } catch (realPathErr) { + if (realPathErr.code !== 'ENOENT') { + throw realPathErr; + } + } } - fs.lchmodSync = function () {} - } - if (!fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) + + if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { + var res = path.resolve(absoluteStart, x); + if (x === '..' || x.slice(-1) === '/') res += '/'; + var m = loadAsFileSync(res) || loadAsDirectorySync(res); + if (m) return m; + } else { + var n = loadNodeModulesSync(x, absoluteStart); + if (n) return n; } - fs.lchownSync = function () {} - } - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. + if (core[x]) return x; - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform === "win32") { - fs.rename = (function (fs$rename) { return function (from, to, cb) { - var start = Date.now() - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er) - }) - }, backoff) - if (backoff < 100) - backoff += 10; - return; + var err = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + err.code = 'MODULE_NOT_FOUND'; + throw err; + + function loadAsFileSync(x) { + var pkg = loadpkg(path.dirname(x)); + + if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) { + var rfile = path.relative(pkg.dir, x); + var r = opts.pathFilter(pkg.pkg, x, rfile); + if (r) { + x = path.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign + } } - if (cb) cb(er) - }) - }})(fs.rename) - } - // if read() returns EAGAIN, then just try it again. - fs.read = (function (fs$read) { return function (fd, buffer, offset, length, position, callback_) { - var callback - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0 - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - return fs$read.call(fs, fd, buffer, offset, length, position, callback) + if (isFile(x)) { + return x; } - callback_.apply(this, arguments) - } - } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - }})(fs.read) - fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0 - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - continue + for (var i = 0; i < extensions.length; i++) { + var file = x + extensions[i]; + if (isFile(file)) { + return file; + } } - throw er - } } - }})(fs.readSync) - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return + function loadpkg(dir) { + if (dir === '' || dir === '/') return; + if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { + return; } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) - } + if ((/[/\\]node_modules[/\\]*$/).test(dir)) return; - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + var pkgfile = path.join(dir, 'package.json'); - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) + if (!isFile(pkgfile)) { + return loadpkg(path.dirname(dir)); } - } - return ret - } - } - function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK")) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) - }) - }) - }) - } + var body = readFileSync(pkgfile); - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret - var threw = true try { - ret = fs.futimesSync(fd, at, mt) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } + var pkg = JSON.parse(body); + } catch (jsonErr) {} + + if (pkg && opts.packageFilter) { + pkg = opts.packageFilter(pkg, dir); } - return ret - } - } else { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} + return { pkg: pkg, dir: dir }; } - } - function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } + function loadAsDirectorySync(x) { + var pkgfile = path.join(x, '/package.json'); + if (isFile(pkgfile)) { + try { + var body = readFileSync(pkgfile, 'UTF8'); + var pkg = JSON.parse(body); + } catch (e) {} - function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } + if (opts.packageFilter) { + pkg = opts.packageFilter(pkg, x); + } + if (pkg.main) { + if (typeof pkg.main !== 'string') { + var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); + mainError.code = 'INVALID_PACKAGE_MAIN'; + throw mainError; + } + if (pkg.main === '.' || pkg.main === './') { + pkg.main = 'index'; + } + try { + var m = loadAsFileSync(path.resolve(x, pkg.main)); + if (m) return m; + var n = loadAsDirectorySync(path.resolve(x, pkg.main)); + if (n) return n; + } catch (e) {} + } + } - function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) + return loadAsFileSync(path.join(x, '/index')); } - } - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er - } + function loadNodeModulesSync(x, start) { + var dirs = nodeModulesPaths(start, opts, x); + for (var i = 0; i < dirs.length; i++) { + var dir = dirs[i]; + var m = loadAsFileSync(path.join(dir, '/', x)); + if (m) return m; + var n = loadAsDirectorySync(path.join(dir, '/', x)); + if (n) return n; + } } - } - +}; - function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, cb) { - return orig.call(fs, target, function (er, stats) { - if (!stats) return cb.apply(this, arguments) - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - if (cb) cb.apply(this, arguments) - }) - } - } - function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target) { - var stats = orig.call(fs, target) - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - return stats; - } - } +/***/ }), +/* 541 */ +/***/ (function(module, exports) { - // ENOSYS means that the fs doesn't support the op. Just ignore - // that, because it doesn't matter. - // - // if there's no getuid, or if getuid() is something other - // than 0, and the error is EINVAL or EPERM, then just ignore - // it. - // - // This specific case is a silent failure in cp, install, tar, - // and most other unix tools that manage permissions. - // - // When running as root, or if other types of errors are - // encountered, then it's strict. - function chownErOk (er) { - if (!er) - return true +module.exports = extractDescription - if (er.code === "ENOSYS") - return true +// Extracts description from contents of a readme file in markdown format +function extractDescription (d) { + if (!d) return; + if (d === "ERROR: No README data found!") return; + // the first block of text before the first heading + // that isn't the first line heading + d = d.trim().split('\n') + for (var s = 0; d[s] && d[s].trim().match(/^(#|$)/); s ++); + var l = d.length + for (var e = s + 1; e < l && d[e].trim(); e ++); + return d.slice(s, e).join(' ').trim() +} - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true - } - return false - } -} +/***/ }), +/* 542 */ +/***/ (function(module) { +module.exports = JSON.parse("{\"topLevel\":{\"dependancies\":\"dependencies\",\"dependecies\":\"dependencies\",\"depdenencies\":\"dependencies\",\"devEependencies\":\"devDependencies\",\"depends\":\"dependencies\",\"dev-dependencies\":\"devDependencies\",\"devDependences\":\"devDependencies\",\"devDepenencies\":\"devDependencies\",\"devdependencies\":\"devDependencies\",\"repostitory\":\"repository\",\"repo\":\"repository\",\"prefereGlobal\":\"preferGlobal\",\"hompage\":\"homepage\",\"hampage\":\"homepage\",\"autohr\":\"author\",\"autor\":\"author\",\"contributers\":\"contributors\",\"publicationConfig\":\"publishConfig\",\"script\":\"scripts\"},\"bugs\":{\"web\":\"url\",\"name\":\"url\"},\"script\":{\"server\":\"start\",\"tests\":\"test\"}}"); /***/ }), -/* 549 */ +/* 543 */ /***/ (function(module, exports, __webpack_require__) { -var Stream = __webpack_require__(27).Stream - -module.exports = legacy +var util = __webpack_require__(397) +var messages = __webpack_require__(544) -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream +module.exports = function() { + var args = Array.prototype.slice.call(arguments, 0) + var warningName = args.shift() + if (warningName == "typo") { + return makeTypoWarning.apply(null,args) } + else { + var msgTemplate = messages[warningName] ? messages[warningName] : warningName + ": '%s'" + args.unshift(msgTemplate) + return util.format.apply(null, args) + } +} - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); - - Stream.call(this); - - var self = this; - - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; - - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; - - options = options || {}; - - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } - - if (this.encoding) this.setEncoding(this.encoding); - - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); - } - - if (this.start > this.end) { - throw new Error('start must be <= end'); - } - - this.pos = this.start; - } - - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; - } - - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; - } - - self.fd = fd; - self.emit('open', fd); - self._read(); - }) +function makeTypoWarning (providedName, probableName, field) { + if (field) { + providedName = field + "['" + providedName + "']" + probableName = field + "['" + probableName + "']" } + return util.format(messages.typo, providedName, probableName) +} - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); - Stream.call(this); +/***/ }), +/* 544 */ +/***/ (function(module) { - this.path = path; - this.fd = null; - this.writable = true; +module.exports = JSON.parse("{\"repositories\":\"'repositories' (plural) Not supported. Please pick one as the 'repository' field\",\"missingRepository\":\"No repository field.\",\"brokenGitUrl\":\"Probably broken git url: %s\",\"nonObjectScripts\":\"scripts must be an object\",\"nonStringScript\":\"script values must be string commands\",\"nonArrayFiles\":\"Invalid 'files' member\",\"invalidFilename\":\"Invalid filename in 'files' list: %s\",\"nonArrayBundleDependencies\":\"Invalid 'bundleDependencies' list. Must be array of package names\",\"nonStringBundleDependency\":\"Invalid bundleDependencies member: %s\",\"nonDependencyBundleDependency\":\"Non-dependency in bundleDependencies: %s\",\"nonObjectDependencies\":\"%s field must be an object\",\"nonStringDependency\":\"Invalid dependency: %s %s\",\"deprecatedArrayDependencies\":\"specifying %s as array is deprecated\",\"deprecatedModules\":\"modules field is deprecated\",\"nonArrayKeywords\":\"keywords should be an array of strings\",\"nonStringKeyword\":\"keywords should be an array of strings\",\"conflictingName\":\"%s is also the name of a node core module.\",\"nonStringDescription\":\"'description' field should be a string\",\"missingDescription\":\"No description\",\"missingReadme\":\"No README data\",\"missingLicense\":\"No license field.\",\"nonEmailUrlBugsString\":\"Bug string field must be url, email, or {email,url}\",\"nonUrlBugsUrlField\":\"bugs.url field must be a string url. Deleted.\",\"nonEmailBugsEmailField\":\"bugs.email field must be a string email. Deleted.\",\"emptyNormalizedBugs\":\"Normalized value of bugs field is an empty object. Deleted.\",\"nonUrlHomepage\":\"homepage field must be a string url. Deleted.\",\"invalidLicense\":\"license should be a valid SPDX license expression\",\"typo\":\"%s should probably be %s.\"}"); - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; +/***/ }), +/* 545 */ +/***/ (function(module, exports, __webpack_require__) { - options = options || {}; +"use strict"; - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } +const path = __webpack_require__(4); +const writeJsonFile = __webpack_require__(546); +const sortKeys = __webpack_require__(558); - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } +const dependencyKeys = new Set([ + 'dependencies', + 'devDependencies', + 'optionalDependencies', + 'peerDependencies' +]); - this.pos = this.start; - } +function normalize(packageJson) { + const result = {}; - this.busy = false; - this._queue = []; + for (const key of Object.keys(packageJson)) { + if (!dependencyKeys.has(key)) { + result[key] = packageJson[key]; + } else if (Object.keys(packageJson[key]).length !== 0) { + result[key] = sortKeys(packageJson[key]); + } + } - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); - } - } + return result; } +module.exports = async (filePath, data, options) => { + if (typeof filePath !== 'string') { + options = data; + data = filePath; + filePath = '.'; + } -/***/ }), -/* 550 */ -/***/ (function(module, exports, __webpack_require__) { + options = { + normalize: true, + ...options, + detectIndent: true + }; -"use strict"; + filePath = path.basename(filePath) === 'package.json' ? filePath : path.join(filePath, 'package.json'); + data = options.normalize ? normalize(data) : data; -module.exports = clone + return writeJsonFile(filePath, data, options); +}; -function clone (obj) { - if (obj === null || typeof obj !== 'object') - return obj +module.exports.sync = (filePath, data, options) => { + if (typeof filePath !== 'string') { + options = data; + data = filePath; + filePath = '.'; + } - if (obj instanceof Object) - var copy = { __proto__: obj.__proto__ } - else - var copy = Object.create(null) + options = { + normalize: true, + ...options, + detectIndent: true + }; - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) - }) + filePath = path.basename(filePath) === 'package.json' ? filePath : path.join(filePath, 'package.json'); - return copy -} + data = options.normalize ? normalize(data) : data; + + writeJsonFile.sync(filePath, data, options); +}; /***/ }), -/* 551 */ +/* 546 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = writeFile -module.exports.sync = writeFileSync -module.exports._getTmpname = getTmpname // for testing -module.exports._cleanupOnExit = cleanupOnExit +const path = __webpack_require__(4); +const fs = __webpack_require__(547); +const writeFileAtomic = __webpack_require__(551); +const sortKeys = __webpack_require__(558); +const makeDir = __webpack_require__(560); +const pify = __webpack_require__(561); +const detectIndent = __webpack_require__(562); -var fs = __webpack_require__(552) -var MurmurHash3 = __webpack_require__(556) -var onExit = __webpack_require__(397) -var path = __webpack_require__(16) -var activeFiles = {} +const init = (fn, filePath, data, options) => { + if (!filePath) { + throw new TypeError('Expected a filepath'); + } -// if we run inside of a worker_thread, `process.pid` is not unique -/* istanbul ignore next */ -var threadId = (function getId () { - try { - var workerThreads = __webpack_require__(557) + if (data === undefined) { + throw new TypeError('Expected data to stringify'); + } - /// if we are in main thread, this is set to `0` - return workerThreads.threadId - } catch (e) { - // worker_threads are not available, fallback to 0 - return 0 - } -})() + options = Object.assign({ + indent: '\t', + sortKeys: false + }, options); -var invocations = 0 -function getTmpname (filename) { - return filename + '.' + - MurmurHash3(__filename) - .hash(String(process.pid)) - .hash(String(threadId)) - .hash(String(++invocations)) - .result() -} + if (options.sortKeys) { + data = sortKeys(data, { + deep: true, + compare: typeof options.sortKeys === 'function' ? options.sortKeys : undefined + }); + } -function cleanupOnExit (tmpfile) { - return function () { - try { - fs.unlinkSync(typeof tmpfile === 'function' ? tmpfile() : tmpfile) - } catch (_) {} - } -} + return fn(filePath, data, options); +}; -function writeFile (filename, data, options, callback) { - if (options) { - if (options instanceof Function) { - callback = options - options = {} - } else if (typeof options === 'string') { - options = { encoding: options } - } - } else { - options = {} - } +const readFile = filePath => pify(fs.readFile)(filePath, 'utf8').catch(() => {}); - var Promise = options.Promise || global.Promise - var truename - var fd - var tmpfile - /* istanbul ignore next -- The closure only gets called when onExit triggers */ - var removeOnExitHandler = onExit(cleanupOnExit(() => tmpfile)) - var absoluteName = path.resolve(filename) +const main = (filePath, data, options) => { + return (options.detectIndent ? readFile(filePath) : Promise.resolve()) + .then(string => { + const indent = string ? detectIndent(string).indent : options.indent; + const json = JSON.stringify(data, options.replacer, indent); - new Promise(function serializeSameFile (resolve) { - // make a queue if it doesn't already exist - if (!activeFiles[absoluteName]) activeFiles[absoluteName] = [] + return pify(writeFileAtomic)(filePath, `${json}\n`, {mode: options.mode}); + }); +}; - activeFiles[absoluteName].push(resolve) // add this job to the queue - if (activeFiles[absoluteName].length === 1) resolve() // kick off the first one - }).then(function getRealPath () { - return new Promise(function (resolve) { - fs.realpath(filename, function (_, realname) { - truename = realname || filename - tmpfile = getTmpname(truename) - resolve() - }) - }) - }).then(function stat () { - return new Promise(function stat (resolve) { - if (options.mode && options.chown) resolve() - else { - // Either mode or chown is not explicitly set - // Default behavior is to copy it from original file - fs.stat(truename, function (err, stats) { - if (err || !stats) resolve() - else { - options = Object.assign({}, options) +const mainSync = (filePath, data, options) => { + let {indent} = options; - if (options.mode == null) { - options.mode = stats.mode - } - if (options.chown == null && process.getuid) { - options.chown = { uid: stats.uid, gid: stats.gid } - } - resolve() - } - }) - } - }) - }).then(function thenWriteFile () { - return new Promise(function (resolve, reject) { - fs.open(tmpfile, 'w', options.mode, function (err, _fd) { - fd = _fd - if (err) reject(err) - else resolve() - }) - }) - }).then(function write () { - return new Promise(function (resolve, reject) { - if (Buffer.isBuffer(data)) { - fs.write(fd, data, 0, data.length, 0, function (err) { - if (err) reject(err) - else resolve() - }) - } else if (data != null) { - fs.write(fd, String(data), 0, String(options.encoding || 'utf8'), function (err) { - if (err) reject(err) - else resolve() - }) - } else resolve() - }) - }).then(function syncAndClose () { - return new Promise(function (resolve, reject) { - if (options.fsync !== false) { - fs.fsync(fd, function (err) { - if (err) fs.close(fd, () => reject(err)) - else fs.close(fd, resolve) - }) - } else { - fs.close(fd, resolve) - } - }) - }).then(function chown () { - fd = null - if (options.chown) { - return new Promise(function (resolve, reject) { - fs.chown(tmpfile, options.chown.uid, options.chown.gid, function (err) { - if (err) reject(err) - else resolve() - }) - }) - } - }).then(function chmod () { - if (options.mode) { - return new Promise(function (resolve, reject) { - fs.chmod(tmpfile, options.mode, function (err) { - if (err) reject(err) - else resolve() - }) - }) - } - }).then(function rename () { - return new Promise(function (resolve, reject) { - fs.rename(tmpfile, truename, function (err) { - if (err) reject(err) - else resolve() - }) - }) - }).then(function success () { - removeOnExitHandler() - callback() - }, function fail (err) { - return new Promise(resolve => { - return fd ? fs.close(fd, resolve) : resolve() - }).then(() => { - removeOnExitHandler() - fs.unlink(tmpfile, function () { - callback(err) - }) - }) - }).then(function checkQueue () { - activeFiles[absoluteName].shift() // remove the element added by serializeSameFile - if (activeFiles[absoluteName].length > 0) { - activeFiles[absoluteName][0]() // start next job if one is pending - } else delete activeFiles[absoluteName] - }) -} + if (options.detectIndent) { + try { + const file = fs.readFileSync(filePath, 'utf8'); + indent = detectIndent(file).indent; + } catch (error) { + if (error.code !== 'ENOENT') { + throw error; + } + } + } -function writeFileSync (filename, data, options) { - if (typeof options === 'string') options = { encoding: options } - else if (!options) options = {} - try { - filename = fs.realpathSync(filename) - } catch (ex) { - // it's ok, it'll happen on a not yet existing file - } - var tmpfile = getTmpname(filename) + const json = JSON.stringify(data, options.replacer, indent); - if (!options.mode || !options.chown) { - // Either mode or chown is not explicitly set - // Default behavior is to copy it from original file - try { - var stats = fs.statSync(filename) - options = Object.assign({}, options) - if (!options.mode) { - options.mode = stats.mode - } - if (!options.chown && process.getuid) { - options.chown = { uid: stats.uid, gid: stats.gid } - } - } catch (ex) { - // ignore stat errors - } - } + return writeFileAtomic.sync(filePath, `${json}\n`, {mode: options.mode}); +}; - var fd - var cleanup = cleanupOnExit(tmpfile) - var removeOnExitHandler = onExit(cleanup) +const writeJsonFile = (filePath, data, options) => { + return makeDir(path.dirname(filePath), {fs}) + .then(() => init(main, filePath, data, options)); +}; - try { - fd = fs.openSync(tmpfile, 'w', options.mode) - if (Buffer.isBuffer(data)) { - fs.writeSync(fd, data, 0, data.length, 0) - } else if (data != null) { - fs.writeSync(fd, String(data), 0, String(options.encoding || 'utf8')) - } - if (options.fsync !== false) { - fs.fsyncSync(fd) - } - fs.closeSync(fd) - if (options.chown) fs.chownSync(tmpfile, options.chown.uid, options.chown.gid) - if (options.mode) fs.chmodSync(tmpfile, options.mode) - fs.renameSync(tmpfile, filename) - removeOnExitHandler() - } catch (err) { - if (fd) { - try { - fs.closeSync(fd) - } catch (ex) { - // ignore close errors at this stage, error may have closed fd already. - } - } - removeOnExitHandler() - cleanup() - throw err - } -} +module.exports = writeJsonFile; +// TODO: Remove this for the next major release +module.exports.default = writeJsonFile; +module.exports.sync = (filePath, data, options) => { + makeDir.sync(path.dirname(filePath), {fs}); + init(mainSync, filePath, data, options); +}; /***/ }), -/* 552 */ +/* 547 */ /***/ (function(module, exports, __webpack_require__) { -var fs = __webpack_require__(23) -var polyfills = __webpack_require__(553) -var legacy = __webpack_require__(555) +var fs = __webpack_require__(349) +var polyfills = __webpack_require__(548) +var legacy = __webpack_require__(549) +var clone = __webpack_require__(550) + var queue = [] -var util = __webpack_require__(29) +var util = __webpack_require__(397) function noop () {} @@ -53880,21 +52895,21 @@ else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { process.on('exit', function() { debug(queue) - __webpack_require__(30).equal(queue.length, 0) + __webpack_require__(371).equal(queue.length, 0) }) } -module.exports = patch(__webpack_require__(554)) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH) { - module.exports = patch(fs) +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; } // Always patch fs.close/closeSync, because we want to // retry() whenever a close happens *anywhere* in the program. // This is essential when multiple graceful-fs instances are // in play at the same time. -module.exports.close = -fs.close = (function (fs$close) { return function (fd, cb) { +module.exports.close = (function (fs$close) { return function (fd, cb) { return fs$close.call(fs, fd, function (err) { if (!err) retry() @@ -53904,8 +52919,7 @@ fs.close = (function (fs$close) { return function (fd, cb) { }) }})(fs.close) -module.exports.closeSync = -fs.closeSync = (function (fs$closeSync) { return function (fd) { +module.exports.closeSync = (function (fs$closeSync) { return function (fd) { // Note that graceful-fs also retries when fs.closeSync() fails. // Looks like a bug to me, although it's probably a harmless one. var rval = fs$closeSync.apply(fs, arguments) @@ -53913,6 +52927,17 @@ fs.closeSync = (function (fs$closeSync) { return function (fd) { return rval }})(fs.closeSync) +// Only patch fs once, otherwise we'll run into a memory leak if +// graceful-fs is loaded multiple times, such as in test environments that +// reset the loaded modules between tests. +// We look for the string `graceful-fs` from the comment above. This +// way we are not adding any extra properties and it will detect if older +// versions of graceful-fs are installed. +if (!/\bgraceful-fs\b/.test(fs.closeSync.toString())) { + fs.closeSync = module.exports.closeSync; + fs.close = module.exports.close; +} + function patch (fs) { // Everything that references the open() function needs to be in here polyfills(fs) @@ -54004,6 +53029,7 @@ function patch (fs) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$readdir, [args]]) + else { if (typeof cb === 'function') cb.apply(this, arguments) @@ -54023,12 +53049,16 @@ function patch (fs) { } var fs$ReadStream = fs.ReadStream - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open + } var fs$WriteStream = fs.WriteStream - WriteStream.prototype = Object.create(fs$WriteStream.prototype) - WriteStream.prototype.open = WriteStream$open + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } fs.ReadStream = ReadStream fs.WriteStream = WriteStream @@ -54123,11 +53153,10 @@ function retry () { /***/ }), -/* 553 */ +/* 548 */ /***/ (function(module, exports, __webpack_require__) { -var fs = __webpack_require__(554) -var constants = __webpack_require__(25) +var constants = __webpack_require__(411) var origCwd = process.cwd var cwd = null @@ -54273,73 +53302,36 @@ function patch (fs) { } } }})(fs.readSync) -} - -function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return - } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) - } - - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) - - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } -} -function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK")) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) return } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) }) }) }) } - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. var threw = true + var ret try { - ret = fs.futimesSync(fd, at, mt) + ret = fs.fchmodSync(fd, mode) threw = false } finally { if (threw) { @@ -54352,122 +53344,281 @@ function patchLutimes (fs) { } return ret } + } - } else { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK")) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } + + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + + } else { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} + } } -} -function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } } -} -function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } } } -} -function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } } -} -function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } } } -} -function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, cb) { - return orig.call(fs, target, function (er, stats) { - if (!stats) return cb.apply(this, arguments) + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, cb) { + return orig.call(fs, target, function (er, stats) { + if (!stats) return cb.apply(this, arguments) + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + if (cb) cb.apply(this, arguments) + }) + } + } + + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target) { + var stats = orig.call(fs, target) if (stats.uid < 0) stats.uid += 0x100000000 if (stats.gid < 0) stats.gid += 0x100000000 - if (cb) cb.apply(this, arguments) - }) + return stats; + } } -} -function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target) { - var stats = orig.call(fs, target) - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - return stats; + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true + + if (er.code === "ENOSYS") + return true + + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } + + return false } } -// ENOSYS means that the fs doesn't support the op. Just ignore -// that, because it doesn't matter. -// -// if there's no getuid, or if getuid() is something other -// than 0, and the error is EINVAL or EPERM, then just ignore -// it. -// -// This specific case is a silent failure in cp, install, tar, -// and most other unix tools that manage permissions. -// -// When running as root, or if other types of errors are -// encountered, then it's strict. -function chownErOk (er) { - if (!er) - return true - if (er.code === "ENOSYS") - return true +/***/ }), +/* 549 */ +/***/ (function(module, exports, __webpack_require__) { - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true +var Stream = __webpack_require__(382).Stream + +module.exports = legacy + +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream } - return false + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); + + Stream.call(this); + + var self = this; + + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; + + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.encoding) this.setEncoding(this.encoding); + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); + } + + if (this.start > this.end) { + throw new Error('start must be <= end'); + } + + this.pos = this.start; + } + + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } + + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } + + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } + + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); + + Stream.call(this); + + this.path = path; + this.fd = null; + this.writable = true; + + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.start < 0) { + throw new Error('start must be >= zero'); + } + + this.pos = this.start; + } + + this.busy = false; + this._queue = []; + + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); + } + } } /***/ }), -/* 554 */ +/* 550 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var fs = __webpack_require__(23) - -module.exports = clone(fs) +module.exports = clone function clone (obj) { if (obj === null || typeof obj !== 'object') @@ -54487,1575 +53638,1767 @@ function clone (obj) { /***/ }), -/* 555 */ +/* 551 */ /***/ (function(module, exports, __webpack_require__) { -var Stream = __webpack_require__(27).Stream +"use strict"; -module.exports = legacy +module.exports = writeFile +module.exports.sync = writeFileSync +module.exports._getTmpname = getTmpname // for testing +module.exports._cleanupOnExit = cleanupOnExit -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream +var fs = __webpack_require__(552) +var MurmurHash3 = __webpack_require__(556) +var onExit = __webpack_require__(370) +var path = __webpack_require__(4) +var activeFiles = {} + +// if we run inside of a worker_thread, `process.pid` is not unique +/* istanbul ignore next */ +var threadId = (function getId () { + try { + var workerThreads = __webpack_require__(557) + + /// if we are in main thread, this is set to `0` + return workerThreads.threadId + } catch (e) { + // worker_threads are not available, fallback to 0 + return 0 } +})() - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); +var invocations = 0 +function getTmpname (filename) { + return filename + '.' + + MurmurHash3(__filename) + .hash(String(process.pid)) + .hash(String(threadId)) + .hash(String(++invocations)) + .result() +} - Stream.call(this); +function cleanupOnExit (tmpfile) { + return function () { + try { + fs.unlinkSync(typeof tmpfile === 'function' ? tmpfile() : tmpfile) + } catch (_) {} + } +} - var self = this; +function writeFile (filename, data, options, callback) { + if (options) { + if (options instanceof Function) { + callback = options + options = {} + } else if (typeof options === 'string') { + options = { encoding: options } + } + } else { + options = {} + } - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; + var Promise = options.Promise || global.Promise + var truename + var fd + var tmpfile + /* istanbul ignore next -- The closure only gets called when onExit triggers */ + var removeOnExitHandler = onExit(cleanupOnExit(() => tmpfile)) + var absoluteName = path.resolve(filename) - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; + new Promise(function serializeSameFile (resolve) { + // make a queue if it doesn't already exist + if (!activeFiles[absoluteName]) activeFiles[absoluteName] = [] - options = options || {}; + activeFiles[absoluteName].push(resolve) // add this job to the queue + if (activeFiles[absoluteName].length === 1) resolve() // kick off the first one + }).then(function getRealPath () { + return new Promise(function (resolve) { + fs.realpath(filename, function (_, realname) { + truename = realname || filename + tmpfile = getTmpname(truename) + resolve() + }) + }) + }).then(function stat () { + return new Promise(function stat (resolve) { + if (options.mode && options.chown) resolve() + else { + // Either mode or chown is not explicitly set + // Default behavior is to copy it from original file + fs.stat(truename, function (err, stats) { + if (err || !stats) resolve() + else { + options = Object.assign({}, options) - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; + if (options.mode == null) { + options.mode = stats.mode + } + if (options.chown == null && process.getuid) { + options.chown = { uid: stats.uid, gid: stats.gid } + } + resolve() + } + }) + } + }) + }).then(function thenWriteFile () { + return new Promise(function (resolve, reject) { + fs.open(tmpfile, 'w', options.mode, function (err, _fd) { + fd = _fd + if (err) reject(err) + else resolve() + }) + }) + }).then(function write () { + return new Promise(function (resolve, reject) { + if (Buffer.isBuffer(data)) { + fs.write(fd, data, 0, data.length, 0, function (err) { + if (err) reject(err) + else resolve() + }) + } else if (data != null) { + fs.write(fd, String(data), 0, String(options.encoding || 'utf8'), function (err) { + if (err) reject(err) + else resolve() + }) + } else resolve() + }) + }).then(function syncAndClose () { + return new Promise(function (resolve, reject) { + if (options.fsync !== false) { + fs.fsync(fd, function (err) { + if (err) fs.close(fd, () => reject(err)) + else fs.close(fd, resolve) + }) + } else { + fs.close(fd, resolve) + } + }) + }).then(function chown () { + fd = null + if (options.chown) { + return new Promise(function (resolve, reject) { + fs.chown(tmpfile, options.chown.uid, options.chown.gid, function (err) { + if (err) reject(err) + else resolve() + }) + }) + } + }).then(function chmod () { + if (options.mode) { + return new Promise(function (resolve, reject) { + fs.chmod(tmpfile, options.mode, function (err) { + if (err) reject(err) + else resolve() + }) + }) } + }).then(function rename () { + return new Promise(function (resolve, reject) { + fs.rename(tmpfile, truename, function (err) { + if (err) reject(err) + else resolve() + }) + }) + }).then(function success () { + removeOnExitHandler() + callback() + }, function fail (err) { + return new Promise(resolve => { + return fd ? fs.close(fd, resolve) : resolve() + }).then(() => { + removeOnExitHandler() + fs.unlink(tmpfile, function () { + callback(err) + }) + }) + }).then(function checkQueue () { + activeFiles[absoluteName].shift() // remove the element added by serializeSameFile + if (activeFiles[absoluteName].length > 0) { + activeFiles[absoluteName][0]() // start next job if one is pending + } else delete activeFiles[absoluteName] + }) +} - if (this.encoding) this.setEncoding(this.encoding); +function writeFileSync (filename, data, options) { + if (typeof options === 'string') options = { encoding: options } + else if (!options) options = {} + try { + filename = fs.realpathSync(filename) + } catch (ex) { + // it's ok, it'll happen on a not yet existing file + } + var tmpfile = getTmpname(filename) - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); + if (!options.mode || !options.chown) { + // Either mode or chown is not explicitly set + // Default behavior is to copy it from original file + try { + var stats = fs.statSync(filename) + options = Object.assign({}, options) + if (!options.mode) { + options.mode = stats.mode } - - if (this.start > this.end) { - throw new Error('start must be <= end'); + if (!options.chown && process.getuid) { + options.chown = { uid: stats.uid, gid: stats.gid } } - - this.pos = this.start; - } - - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; + } catch (ex) { + // ignore stat errors } - - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; - } - - self.fd = fd; - self.emit('open', fd); - self._read(); - }) } - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); - - Stream.call(this); - - this.path = path; - this.fd = null; - this.writable = true; - - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; - - options = options || {}; + var fd + var cleanup = cleanupOnExit(tmpfile) + var removeOnExitHandler = onExit(cleanup) - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; + try { + fd = fs.openSync(tmpfile, 'w', options.mode) + if (Buffer.isBuffer(data)) { + fs.writeSync(fd, data, 0, data.length, 0) + } else if (data != null) { + fs.writeSync(fd, String(data), 0, String(options.encoding || 'utf8')) } - - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } - - this.pos = this.start; + if (options.fsync !== false) { + fs.fsyncSync(fd) } - - this.busy = false; - this._queue = []; - - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); + fs.closeSync(fd) + if (options.chown) fs.chownSync(tmpfile, options.chown.uid, options.chown.gid) + if (options.mode) fs.chmodSync(tmpfile, options.mode) + fs.renameSync(tmpfile, filename) + removeOnExitHandler() + } catch (err) { + if (fd) { + try { + fs.closeSync(fd) + } catch (ex) { + // ignore close errors at this stage, error may have closed fd already. + } } + removeOnExitHandler() + cleanup() + throw err } } /***/ }), -/* 556 */ +/* 552 */ /***/ (function(module, exports, __webpack_require__) { -/** - * @preserve - * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) - * - * @author Jens Taylor - * @see http://github.com/homebrewing/brauhaus-diff - * @author Gary Court - * @see http://github.com/garycourt/murmurhash-js - * @author Austin Appleby - * @see http://sites.google.com/site/murmurhash/ - */ -(function(){ - var cache; +var fs = __webpack_require__(349) +var polyfills = __webpack_require__(553) +var legacy = __webpack_require__(555) +var queue = [] - // Call this function without `new` to use the cached object (good for - // single-threaded environments), or with `new` to create a new object. - // - // @param {string} key A UTF-16 or ASCII string - // @param {number} seed An optional positive integer - // @return {object} A MurmurHash3 object for incremental hashing - function MurmurHash3(key, seed) { - var m = this instanceof MurmurHash3 ? this : cache; - m.reset(seed) - if (typeof key === 'string' && key.length > 0) { - m.hash(key); - } +var util = __webpack_require__(397) - if (m !== this) { - return m; - } - }; +function noop () {} - // Incrementally add a string to this hash - // - // @param {string} key A UTF-16 or ASCII string - // @return {object} this - MurmurHash3.prototype.hash = function(key) { - var h1, k1, i, top, len; +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) + } - len = key.length; - this.len += len; +if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(queue) + __webpack_require__(371).equal(queue.length, 0) + }) +} - k1 = this.k1; - i = 0; - switch (this.rem) { - case 0: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) : 0; - case 1: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 8 : 0; - case 2: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 16 : 0; - case 3: - k1 ^= len > i ? (key.charCodeAt(i) & 0xff) << 24 : 0; - k1 ^= len > i ? (key.charCodeAt(i++) & 0xff00) >> 8 : 0; - } +module.exports = patch(__webpack_require__(554)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH) { + module.exports = patch(fs) +} - this.rem = (len + this.rem) & 3; // & 3 is same as % 4 - len -= this.rem; - if (len > 0) { - h1 = this.h1; - while (1) { - k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; - k1 = (k1 << 15) | (k1 >>> 17); - k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; +// Always patch fs.close/closeSync, because we want to +// retry() whenever a close happens *anywhere* in the program. +// This is essential when multiple graceful-fs instances are +// in play at the same time. +module.exports.close = +fs.close = (function (fs$close) { return function (fd, cb) { + return fs$close.call(fs, fd, function (err) { + if (!err) + retry() - h1 ^= k1; - h1 = (h1 << 13) | (h1 >>> 19); - h1 = (h1 * 5 + 0xe6546b64) & 0xffffffff; + if (typeof cb === 'function') + cb.apply(this, arguments) + }) +}})(fs.close) - if (i >= len) { - break; - } +module.exports.closeSync = +fs.closeSync = (function (fs$closeSync) { return function (fd) { + // Note that graceful-fs also retries when fs.closeSync() fails. + // Looks like a bug to me, although it's probably a harmless one. + var rval = fs$closeSync.apply(fs, arguments) + retry() + return rval +}})(fs.closeSync) - k1 = ((key.charCodeAt(i++) & 0xffff)) ^ - ((key.charCodeAt(i++) & 0xffff) << 8) ^ - ((key.charCodeAt(i++) & 0xffff) << 16); - top = key.charCodeAt(i++); - k1 ^= ((top & 0xff) << 24) ^ - ((top & 0xff00) >> 8); - } +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch + fs.FileReadStream = ReadStream; // Legacy name. + fs.FileWriteStream = WriteStream; // Legacy name. + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null - k1 = 0; - switch (this.rem) { - case 3: k1 ^= (key.charCodeAt(i + 2) & 0xffff) << 16; - case 2: k1 ^= (key.charCodeAt(i + 1) & 0xffff) << 8; - case 1: k1 ^= (key.charCodeAt(i) & 0xffff); - } + return go$readFile(path, options, cb) - this.h1 = h1; + function go$readFile (path, options, cb) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() } + }) + } + } - this.k1 = k1; - return this; - }; + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null - // Get the result of this hash - // - // @return {number} The 32-bit hash - MurmurHash3.prototype.result = function() { - var k1, h1; - - k1 = this.k1; - h1 = this.h1; + return go$writeFile(path, data, options, cb) - if (k1 > 0) { - k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; - k1 = (k1 << 15) | (k1 >>> 17); - k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; - h1 ^= k1; + function go$writeFile (path, data, options, cb) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() } + }) + } + } - h1 ^= this.len; - - h1 ^= h1 >>> 16; - h1 = (h1 * 0xca6b + (h1 & 0xffff) * 0x85eb0000) & 0xffffffff; - h1 ^= h1 >>> 13; - h1 = (h1 * 0xae35 + (h1 & 0xffff) * 0xc2b20000) & 0xffffffff; - h1 ^= h1 >>> 16; - - return h1 >>> 0; - }; - - // Reset the hash object for reuse - // - // @param {number} seed An optional positive integer - MurmurHash3.prototype.reset = function(seed) { - this.h1 = typeof seed === 'number' ? seed : 0; - this.rem = this.k1 = this.len = 0; - return this; - }; - - // A cached object to use. This can be safely used if you're in a single- - // threaded environment, otherwise you need to create new hashes to use. - cache = new MurmurHash3(); - - if (true) { - module.exports = MurmurHash3; - } else {} -}()); - - -/***/ }), -/* 557 */ -/***/ (function(module, exports) { - -module.exports = require(undefined); - -/***/ }), -/* 558 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const isPlainObj = __webpack_require__(559); - -module.exports = (obj, opts) => { - if (!isPlainObj(obj)) { - throw new TypeError('Expected a plain object'); - } - - opts = opts || {}; - - // DEPRECATED - if (typeof opts === 'function') { - throw new TypeError('Specify the compare function as an option instead'); - } - - const deep = opts.deep; - const seenInput = []; - const seenOutput = []; - - const sortKeys = x => { - const seenIndex = seenInput.indexOf(x); - - if (seenIndex !== -1) { - return seenOutput[seenIndex]; - } - - const ret = {}; - const keys = Object.keys(x).sort(opts.compare); - - seenInput.push(x); - seenOutput.push(ret); - - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - const val = x[key]; - - if (deep && Array.isArray(val)) { - const retArr = []; - - for (let j = 0; j < val.length; j++) { - retArr[j] = isPlainObj(val[j]) ? sortKeys(val[j]) : val[j]; - } - - ret[key] = retArr; - continue; - } - - ret[key] = deep && isPlainObj(val) ? sortKeys(val) : val; - } - - return ret; - }; - - return sortKeys(obj); -}; - - -/***/ }), -/* 559 */ -/***/ (function(module, exports, __webpack_require__) { + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null -"use strict"; + return go$appendFile(path, data, options, cb) -var toString = Object.prototype.toString; + function go$appendFile (path, data, options, cb) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } + } -module.exports = function (x) { - var prototype; - return toString.call(x) === '[object Object]' && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({})); -}; + var fs$readdir = fs.readdir + fs.readdir = readdir + function readdir (path, options, cb) { + var args = [path] + if (typeof options !== 'function') { + args.push(options) + } else { + cb = options + } + args.push(go$readdir$cb) + return go$readdir(args) -/***/ }), -/* 560 */ -/***/ (function(module, exports, __webpack_require__) { + function go$readdir$cb (err, files) { + if (files && files.sort) + files.sort() -"use strict"; + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readdir, [args]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + } + } -const fs = __webpack_require__(23); -const path = __webpack_require__(16); -const pify = __webpack_require__(561); -const semver = __webpack_require__(523); + function go$readdir (args) { + return fs$readdir.apply(fs, args) + } -const defaults = { - mode: 0o777 & (~process.umask()), - fs -}; + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream + } -const useNativeRecursiveOption = semver.satisfies(process.version, '>=10.12.0'); + var fs$ReadStream = fs.ReadStream + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open -// 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, '')); + var fs$WriteStream = fs.WriteStream + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open - if (pathHasInvalidWinCharacters) { - const error = new Error(`Path contains invalid characters: ${pth}`); - error.code = 'EINVAL'; - throw error; - } - } -}; + fs.ReadStream = ReadStream + fs.WriteStream = WriteStream -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; -}; + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + } -const makeDir = (input, options) => Promise.resolve().then(() => { - checkPath(input); - options = Object.assign({}, defaults, options); + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() - // TODO: Use util.promisify when targeting Node.js 8 - const mkdir = pify(options.fs.mkdir); - const stat = pify(options.fs.stat); + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + that.read() + } + }) + } - if (useNativeRecursiveOption && options.fs.mkdir === fs.mkdir) { - const pth = path.resolve(input); + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } - return mkdir(pth, { - mode: options.mode, - recursive: true - }).then(() => pth); - } + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + } + }) + } - const make = pth => { - return mkdir(pth, options.mode) - .then(() => pth) - .catch(error => { - if (error.code === 'EPERM') { - throw error; - } + function createReadStream (path, options) { + return new ReadStream(path, options) + } - if (error.code === 'ENOENT') { - if (path.dirname(pth) === pth) { - throw permissionError(pth); - } + function createWriteStream (path, options) { + return new WriteStream(path, options) + } - if (error.message.includes('null bytes')) { - throw error; - } + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null - return make(path.dirname(pth)).then(() => make(pth)); - } + return go$open(path, flags, mode, cb) - return stat(pth) - .then(stats => stats.isDirectory() ? pth : Promise.reject()) - .catch(() => { - throw error; - }); - }); - }; + function go$open (path, flags, mode, cb) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } + } - return make(path.resolve(input)); -}); + return fs +} -module.exports = makeDir; -module.exports.default = makeDir; +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + queue.push(elem) +} -module.exports.sync = (input, options) => { - checkPath(input); - options = Object.assign({}, defaults, options); +function retry () { + var elem = queue.shift() + if (elem) { + debug('RETRY', elem[0].name, elem[1]) + elem[0].apply(null, elem[1]) + } +} - if (useNativeRecursiveOption && options.fs.mkdirSync === fs.mkdirSync) { - const pth = path.resolve(input); - fs.mkdirSync(pth, { - mode: options.mode, - recursive: true - }); +/***/ }), +/* 553 */ +/***/ (function(module, exports, __webpack_require__) { - return pth; - } +var fs = __webpack_require__(554) +var constants = __webpack_require__(411) - const make = pth => { - try { - options.fs.mkdirSync(pth, options.mode); - } catch (error) { - if (error.code === 'EPERM') { - throw error; - } +var origCwd = process.cwd +var cwd = null - if (error.code === 'ENOENT') { - if (path.dirname(pth) === pth) { - throw permissionError(pth); - } +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform - if (error.message.includes('null bytes')) { - throw error; - } +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd +} +try { + process.cwd() +} catch (er) {} - make(path.dirname(pth)); - return make(pth); - } +var chdir = process.chdir +process.chdir = function(d) { + cwd = null + chdir.call(process, d) +} - try { - if (!options.fs.statSync(pth).isDirectory()) { - throw new Error('The path is not a directory'); - } - } catch (_) { - throw error; - } - } +module.exports = patch - return pth; - }; +function patch (fs) { + // (re-)implement some things that are known busted or missing. - return make(path.resolve(input)); -}; + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) + } + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } -/***/ }), -/* 561 */ -/***/ (function(module, exports, __webpack_require__) { + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. -"use strict"; + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) -const processFn = (fn, options) => function (...args) { - const P = options.promiseModule; + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) - return new P((resolve, reject) => { - if (options.multiArgs) { - args.push((...result) => { - if (options.errorFirst) { - if (result[0]) { - reject(result); - } else { - result.shift(); - resolve(result); - } - } else { - resolve(result); - } - }); - } else if (options.errorFirst) { - args.push((error, result) => { - if (error) { - reject(error); - } else { - resolve(result); - } - }); - } else { - args.push(resolve); - } + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) - fn.apply(this, args); - }); -}; + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) -module.exports = (input, options) => { - options = Object.assign({ - exclude: [/.+(Sync|Stream)$/], - errorFirst: true, - promiseModule: Promise - }, options); + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) - const objType = typeof input; - if (!(input !== null && (objType === 'object' || objType === 'function'))) { - throw new TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${input === null ? 'null' : objType}\``); - } + // if lchmod/lchown do not exist, then make them no-ops + if (!fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) + } + fs.lchmodSync = function () {} + } + if (!fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) + } + fs.lchownSync = function () {} + } - const filter = key => { - const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key); - return options.include ? options.include.some(match) : !options.exclude.some(match); - }; + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. - let ret; - if (objType === 'function') { - ret = function (...args) { - return options.excludeMain ? input(...args) : processFn(input, options).apply(this, args); - }; - } else { - ret = Object.create(Object.getPrototypeOf(input)); - } + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = (function (fs$rename) { return function (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + }})(fs.rename) + } - for (const key in input) { // eslint-disable-line guard-for-in - const property = input[key]; - ret[key] = typeof property === 'function' && filter(key) ? processFn(property, options) : property; - } + // if read() returns EAGAIN, then just try it again. + fs.read = (function (fs$read) { return function (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + }})(fs.read) - return ret; -}; + fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } + }})(fs.readSync) +} +function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } -/***/ }), -/* 562 */ -/***/ (function(module, exports, __webpack_require__) { + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) -"use strict"; + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } +} +function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK")) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } -// detect either spaces or tabs but not both to properly handle tabs -// for indentation and spaces for alignment -const INDENT_RE = /^(?:( )+|\t+)/; + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } -function getMostUsed(indents) { - let result = 0; - let maxUsed = 0; - let maxWeight = 0; + } else { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} + } +} - for (const entry of indents) { - // TODO: use destructuring when targeting Node.js 6 - const key = entry[0]; - const val = entry[1]; +function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } +} - const u = val[0]; - const w = val[1]; +function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } + } +} - if (u > maxUsed || (u === maxUsed && w > maxWeight)) { - maxUsed = u; - maxWeight = w; - result = Number(key); - } - } - return result; +function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } } -module.exports = str => { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } +function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } +} - // used to see if tabs or spaces are the most used - let tabs = 0; - let spaces = 0; - // remember the size of previous line's indentation - let prev = 0; +function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, cb) { + return orig.call(fs, target, function (er, stats) { + if (!stats) return cb.apply(this, arguments) + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + if (cb) cb.apply(this, arguments) + }) + } +} + +function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target) { + var stats = orig.call(fs, target) + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + return stats; + } +} + +// ENOSYS means that the fs doesn't support the op. Just ignore +// that, because it doesn't matter. +// +// if there's no getuid, or if getuid() is something other +// than 0, and the error is EINVAL or EPERM, then just ignore +// it. +// +// This specific case is a silent failure in cp, install, tar, +// and most other unix tools that manage permissions. +// +// When running as root, or if other types of errors are +// encountered, then it's strict. +function chownErOk (er) { + if (!er) + return true - // remember how many indents/unindents as occurred for a given size - // and how much lines follow a given indentation - // - // indents = { - // 3: [1, 0], - // 4: [1, 5], - // 5: [1, 0], - // 12: [1, 0], - // } - const indents = new Map(); + if (er.code === "ENOSYS") + return true - // pointer to the array of last used indent - let current; + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } - // whether the last action was an indent (opposed to an unindent) - let isIndent; + return false +} - for (const line of str.split(/\n/g)) { - if (!line) { - // ignore empty lines - continue; - } - let indent; - const matches = line.match(INDENT_RE); +/***/ }), +/* 554 */ +/***/ (function(module, exports, __webpack_require__) { - if (matches) { - indent = matches[0].length; +"use strict"; - if (matches[1]) { - spaces++; - } else { - tabs++; - } - } else { - indent = 0; - } - const diff = indent - prev; - prev = indent; +var fs = __webpack_require__(349) - if (diff) { - // an indent or unindent has been detected +module.exports = clone(fs) - isIndent = diff > 0; +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj - current = indents.get(isIndent ? diff : -diff); + if (obj instanceof Object) + var copy = { __proto__: obj.__proto__ } + else + var copy = Object.create(null) - if (current) { - current[0]++; - } else { - current = [1, 0]; - indents.set(diff, current); - } - } else if (current) { - // if the last action was an indent, increment the weight - current[1] += Number(isIndent); - } - } + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) - const amount = getMostUsed(indents); + return copy +} - let type; - let indent; - if (!amount) { - type = null; - indent = ''; - } else if (spaces >= tabs) { - type = 'space'; - indent = ' '.repeat(amount); - } else { - type = 'tab'; - indent = '\t'.repeat(amount); - } - return { - amount, - type, - indent - }; -}; +/***/ }), +/* 555 */ +/***/ (function(module, exports, __webpack_require__) { +var Stream = __webpack_require__(382).Stream -/***/ }), -/* 563 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +module.exports = legacy -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "installInDir", function() { return installInDir; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runScriptInPackage", function() { return runScriptInPackage; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runScriptInPackageStreaming", function() { return runScriptInPackageStreaming; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yarnWorkspacesInfo", function() { return yarnWorkspacesInfo; }); -/* harmony import */ var _child_process__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(564); -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream + } + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); -/** - * Install all dependencies in the given directory - */ -async function installInDir(directory, extraArgs = []) { - const options = ['install', '--non-interactive', ...extraArgs]; // We pass the mutex flag to ensure only one instance of yarn runs at any - // given time (e.g. to avoid conflicts). + Stream.call(this); - await Object(_child_process__WEBPACK_IMPORTED_MODULE_0__["spawn"])('yarn', options, { - cwd: directory - }); -} -/** - * Run script in the given directory - */ + var self = this; -async function runScriptInPackage(script, args, pkg) { - const execOpts = { - cwd: pkg.path - }; - await Object(_child_process__WEBPACK_IMPORTED_MODULE_0__["spawn"])('yarn', ['run', script, ...args], execOpts); -} -/** - * Run script in the given directory - */ + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; -function runScriptInPackageStreaming(script, args, pkg) { - const execOpts = { - cwd: pkg.path - }; - return Object(_child_process__WEBPACK_IMPORTED_MODULE_0__["spawnStreaming"])('yarn', ['run', script, ...args], execOpts, { - prefix: pkg.name - }); -} -async function yarnWorkspacesInfo(directory) { - const { - stdout - } = await Object(_child_process__WEBPACK_IMPORTED_MODULE_0__["spawn"])('yarn', ['--json', 'workspaces', 'info'], { - cwd: directory, - stdio: 'pipe' - }); + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; - try { - return JSON.parse(JSON.parse(stdout).data); - } catch (error) { - throw new Error(`'yarn workspaces info --json' produced unexpected output: \n${stdout}`); - } -} + options = options || {}; -/***/ }), -/* 564 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "spawn", function() { return spawn; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "spawnStreaming", function() { return spawnStreaming; }); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(chalk__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var execa__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(371); -/* harmony import */ var execa__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(execa__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var log_symbols__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(565); -/* harmony import */ var log_symbols__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(log_symbols__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var strong_log_transformer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(570); -/* harmony import */ var strong_log_transformer__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(strong_log_transformer__WEBPACK_IMPORTED_MODULE_3__); -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + if (this.encoding) this.setEncoding(this.encoding); -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); + } -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; } + if (this.start > this.end) { + throw new Error('start must be <= end'); + } -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ + this.pos = this.start; + } + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); -function generateColors() { - const colorWheel = [chalk__WEBPACK_IMPORTED_MODULE_0___default.a.cyan, chalk__WEBPACK_IMPORTED_MODULE_0___default.a.magenta, chalk__WEBPACK_IMPORTED_MODULE_0___default.a.blue, chalk__WEBPACK_IMPORTED_MODULE_0___default.a.yellow, chalk__WEBPACK_IMPORTED_MODULE_0___default.a.green]; - const count = colorWheel.length; - let children = 0; - return () => colorWheel[children++ % count]; -} + Stream.call(this); -function spawn(command, args, opts) { - return execa__WEBPACK_IMPORTED_MODULE_1___default()(command, args, _objectSpread({ - stdio: 'inherit', - preferLocal: true - }, opts)); -} -const nextColor = generateColors(); -function spawnStreaming(command, args, opts, { - prefix -}) { - const spawned = execa__WEBPACK_IMPORTED_MODULE_1___default()(command, args, _objectSpread({ - stdio: ['ignore', 'pipe', 'pipe'], - preferLocal: true - }, opts)); - const color = nextColor(); - const prefixedStdout = strong_log_transformer__WEBPACK_IMPORTED_MODULE_3___default()({ - tag: `${color.bold(prefix)}:` - }); - const prefixedStderr = strong_log_transformer__WEBPACK_IMPORTED_MODULE_3___default()({ - mergeMultiline: true, - tag: `${log_symbols__WEBPACK_IMPORTED_MODULE_2___default.a.error} ${color.bold(prefix)}:` - }); - spawned.stdout.pipe(prefixedStdout).pipe(process.stdout); - spawned.stderr.pipe(prefixedStderr).pipe(process.stderr); - return spawned; -} + this.path = path; + this.fd = null; + this.writable = true; -/***/ }), -/* 565 */ -/***/ (function(module, exports, __webpack_require__) { + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; -"use strict"; + options = options || {}; -const chalk = __webpack_require__(566); + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } -const isSupported = process.platform !== 'win32' || process.env.CI || process.env.TERM === 'xterm-256color'; + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.start < 0) { + throw new Error('start must be >= zero'); + } -const main = { - info: chalk.blue('ℹ'), - success: chalk.green('✔'), - warning: chalk.yellow('⚠'), - error: chalk.red('✖') -}; + this.pos = this.start; + } -const fallbacks = { - info: chalk.blue('i'), - success: chalk.green('√'), - warning: chalk.yellow('‼'), - error: chalk.red('×') -}; + this.busy = false; + this._queue = []; -module.exports = isSupported ? main : fallbacks; + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); + } + } +} /***/ }), -/* 566 */ +/* 556 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - -const escapeStringRegexp = __webpack_require__(3); -const ansiStyles = __webpack_require__(567); -const stdoutColor = __webpack_require__(568).stdout; - -const template = __webpack_require__(569); - -const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); - -// `supportsColor.level` → `ansiStyles.color[name]` mapping -const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; +/** + * @preserve + * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) + * + * @author Jens Taylor + * @see http://github.com/homebrewing/brauhaus-diff + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + */ +(function(){ + var cache; -// `color-convert` models to exclude from the Chalk API due to conflicts and such -const skipModels = new Set(['gray']); + // Call this function without `new` to use the cached object (good for + // single-threaded environments), or with `new` to create a new object. + // + // @param {string} key A UTF-16 or ASCII string + // @param {number} seed An optional positive integer + // @return {object} A MurmurHash3 object for incremental hashing + function MurmurHash3(key, seed) { + var m = this instanceof MurmurHash3 ? this : cache; + m.reset(seed) + if (typeof key === 'string' && key.length > 0) { + m.hash(key); + } -const styles = Object.create(null); + if (m !== this) { + return m; + } + }; -function applyOptions(obj, options) { - options = options || {}; + // Incrementally add a string to this hash + // + // @param {string} key A UTF-16 or ASCII string + // @return {object} this + MurmurHash3.prototype.hash = function(key) { + var h1, k1, i, top, len; - // Detect level if not set manually - const scLevel = stdoutColor ? stdoutColor.level : 0; - obj.level = options.level === undefined ? scLevel : options.level; - obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; -} + len = key.length; + this.len += len; -function Chalk(options) { - // We check for this.template here since calling `chalk.constructor()` - // by itself will have a `this` of a previously constructed chalk object - if (!this || !(this instanceof Chalk) || this.template) { - const chalk = {}; - applyOptions(chalk, options); + k1 = this.k1; + i = 0; + switch (this.rem) { + case 0: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) : 0; + case 1: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 8 : 0; + case 2: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 16 : 0; + case 3: + k1 ^= len > i ? (key.charCodeAt(i) & 0xff) << 24 : 0; + k1 ^= len > i ? (key.charCodeAt(i++) & 0xff00) >> 8 : 0; + } - chalk.template = function () { - const args = [].slice.call(arguments); - return chalkTag.apply(null, [chalk.template].concat(args)); - }; + this.rem = (len + this.rem) & 3; // & 3 is same as % 4 + len -= this.rem; + if (len > 0) { + h1 = this.h1; + while (1) { + k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; - Object.setPrototypeOf(chalk, Chalk.prototype); - Object.setPrototypeOf(chalk.template, chalk); + h1 ^= k1; + h1 = (h1 << 13) | (h1 >>> 19); + h1 = (h1 * 5 + 0xe6546b64) & 0xffffffff; - chalk.template.constructor = Chalk; + if (i >= len) { + break; + } - return chalk.template; - } + k1 = ((key.charCodeAt(i++) & 0xffff)) ^ + ((key.charCodeAt(i++) & 0xffff) << 8) ^ + ((key.charCodeAt(i++) & 0xffff) << 16); + top = key.charCodeAt(i++); + k1 ^= ((top & 0xff) << 24) ^ + ((top & 0xff00) >> 8); + } - applyOptions(this, options); -} + k1 = 0; + switch (this.rem) { + case 3: k1 ^= (key.charCodeAt(i + 2) & 0xffff) << 16; + case 2: k1 ^= (key.charCodeAt(i + 1) & 0xffff) << 8; + case 1: k1 ^= (key.charCodeAt(i) & 0xffff); + } -// Use bright blue on Windows as the normal blue color is illegible -if (isSimpleWindowsTerm) { - ansiStyles.blue.open = '\u001B[94m'; -} + this.h1 = h1; + } -for (const key of Object.keys(ansiStyles)) { - ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + this.k1 = k1; + return this; + }; - styles[key] = { - get() { - const codes = ansiStyles[key]; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); - } - }; -} + // Get the result of this hash + // + // @return {number} The 32-bit hash + MurmurHash3.prototype.result = function() { + var k1, h1; + + k1 = this.k1; + h1 = this.h1; -styles.visible = { - get() { - return build.call(this, this._styles || [], true, 'visible'); - } -}; + if (k1 > 0) { + k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; + h1 ^= k1; + } -ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); -for (const model of Object.keys(ansiStyles.color.ansi)) { - if (skipModels.has(model)) { - continue; - } + h1 ^= this.len; - styles[model] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles.color.close, - closeRe: ansiStyles.color.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; -} + h1 ^= h1 >>> 16; + h1 = (h1 * 0xca6b + (h1 & 0xffff) * 0x85eb0000) & 0xffffffff; + h1 ^= h1 >>> 13; + h1 = (h1 * 0xae35 + (h1 & 0xffff) * 0xc2b20000) & 0xffffffff; + h1 ^= h1 >>> 16; -ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); -for (const model of Object.keys(ansiStyles.bgColor.ansi)) { - if (skipModels.has(model)) { - continue; - } + return h1 >>> 0; + }; - const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); - styles[bgModel] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles.bgColor.close, - closeRe: ansiStyles.bgColor.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; -} + // Reset the hash object for reuse + // + // @param {number} seed An optional positive integer + MurmurHash3.prototype.reset = function(seed) { + this.h1 = typeof seed === 'number' ? seed : 0; + this.rem = this.k1 = this.len = 0; + return this; + }; -const proto = Object.defineProperties(() => {}, styles); + // A cached object to use. This can be safely used if you're in a single- + // threaded environment, otherwise you need to create new hashes to use. + cache = new MurmurHash3(); -function build(_styles, _empty, key) { - const builder = function () { - return applyStyle.apply(builder, arguments); - }; + if (true) { + module.exports = MurmurHash3; + } else {} +}()); - builder._styles = _styles; - builder._empty = _empty; - const self = this; +/***/ }), +/* 557 */ +/***/ (function(module, exports) { - Object.defineProperty(builder, 'level', { - enumerable: true, - get() { - return self.level; - }, - set(level) { - self.level = level; - } - }); +module.exports = require(undefined); - Object.defineProperty(builder, 'enabled', { - enumerable: true, - get() { - return self.enabled; - }, - set(enabled) { - self.enabled = enabled; - } - }); +/***/ }), +/* 558 */ +/***/ (function(module, exports, __webpack_require__) { - // See below for fix regarding invisible grey/dim combination on Windows - builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; +"use strict"; - // `__proto__` is used because we must return a function, but there is - // no way to create a function with a different prototype - builder.__proto__ = proto; // eslint-disable-line no-proto +const isPlainObj = __webpack_require__(559); - return builder; -} +module.exports = (obj, opts) => { + if (!isPlainObj(obj)) { + throw new TypeError('Expected a plain object'); + } -function applyStyle() { - // Support varags, but simply cast to string in case there's only one arg - const args = arguments; - const argsLen = args.length; - let str = String(arguments[0]); + opts = opts || {}; - if (argsLen === 0) { - return ''; + // DEPRECATED + if (typeof opts === 'function') { + throw new TypeError('Specify the compare function as an option instead'); } - if (argsLen > 1) { - // Don't slice `arguments`, it prevents V8 optimizations - for (let a = 1; a < argsLen; a++) { - str += ' ' + args[a]; + const deep = opts.deep; + const seenInput = []; + const seenOutput = []; + + const sortKeys = x => { + const seenIndex = seenInput.indexOf(x); + + if (seenIndex !== -1) { + return seenOutput[seenIndex]; } - } - if (!this.enabled || this.level <= 0 || !str) { - return this._empty ? '' : str; - } + const ret = {}; + const keys = Object.keys(x).sort(opts.compare); - // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, - // see https://github.com/chalk/chalk/issues/58 - // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. - const originalDim = ansiStyles.dim.open; - if (isSimpleWindowsTerm && this.hasGrey) { - ansiStyles.dim.open = ''; - } + seenInput.push(x); + seenOutput.push(ret); - for (const code of this._styles.slice().reverse()) { - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - str = code.open + str.replace(code.closeRe, code.open) + code.close; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const val = x[key]; - // Close the styling before a linebreak and reopen - // after next line to fix a bleed issue on macOS - // https://github.com/chalk/chalk/pull/92 - str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); - } + if (deep && Array.isArray(val)) { + const retArr = []; - // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue - ansiStyles.dim.open = originalDim; + for (let j = 0; j < val.length; j++) { + retArr[j] = isPlainObj(val[j]) ? sortKeys(val[j]) : val[j]; + } - return str; -} + ret[key] = retArr; + continue; + } -function chalkTag(chalk, strings) { - if (!Array.isArray(strings)) { - // If chalk() was called by itself or with a string, - // return the string itself as a string. - return [].slice.call(arguments, 1).join(' '); - } + ret[key] = deep && isPlainObj(val) ? sortKeys(val) : val; + } - const args = [].slice.call(arguments, 2); - const parts = [strings.raw[0]]; + return ret; + }; - for (let i = 1; i < strings.length; i++) { - parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); - parts.push(String(strings.raw[i])); - } + return sortKeys(obj); +}; - return template(chalk, parts.join('')); -} -Object.defineProperties(Chalk.prototype, styles); +/***/ }), +/* 559 */ +/***/ (function(module, exports, __webpack_require__) { -module.exports = Chalk(); // eslint-disable-line new-cap -module.exports.supportsColor = stdoutColor; -module.exports.default = module.exports; // For TypeScript +"use strict"; + +var toString = Object.prototype.toString; + +module.exports = function (x) { + var prototype; + return toString.call(x) === '[object Object]' && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({})); +}; /***/ }), -/* 567 */ +/* 560 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* WEBPACK VAR INJECTION */(function(module) { -const colorConvert = __webpack_require__(6); -const wrapAnsi16 = (fn, offset) => function () { - const code = fn.apply(colorConvert, arguments); - return `\u001B[${code + offset}m`; +const fs = __webpack_require__(349); +const path = __webpack_require__(4); +const pify = __webpack_require__(561); +const semver = __webpack_require__(523); + +const defaults = { + mode: 0o777 & (~process.umask()), + fs }; -const wrapAnsi256 = (fn, offset) => function () { - const code = fn.apply(colorConvert, arguments); - return `\u001B[${38 + offset};5;${code}m`; +const useNativeRecursiveOption = semver.satisfies(process.version, '>=10.12.0'); + +// 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, '')); + + if (pathHasInvalidWinCharacters) { + const error = new Error(`Path contains invalid characters: ${pth}`); + error.code = 'EINVAL'; + throw error; + } + } }; -const wrapAnsi16m = (fn, offset) => function () { - const rgb = fn.apply(colorConvert, arguments); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +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; }; -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39], +const makeDir = (input, options) => Promise.resolve().then(() => { + checkPath(input); + options = Object.assign({}, defaults, options); - // Bright color - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], + // TODO: Use util.promisify when targeting Node.js 8 + const mkdir = pify(options.fs.mkdir); + const stat = pify(options.fs.stat); - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; + if (useNativeRecursiveOption && options.fs.mkdir === fs.mkdir) { + const pth = path.resolve(input); - // Fix humans - styles.color.grey = styles.color.gray; + return mkdir(pth, { + mode: options.mode, + recursive: true + }).then(() => pth); + } - for (const groupName of Object.keys(styles)) { - const group = styles[groupName]; + const make = pth => { + return mkdir(pth, options.mode) + .then(() => pth) + .catch(error => { + if (error.code === 'EPERM') { + throw error; + } - for (const styleName of Object.keys(group)) { - const style = group[styleName]; + if (error.code === 'ENOENT') { + if (path.dirname(pth) === pth) { + throw permissionError(pth); + } - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; + if (error.message.includes('null bytes')) { + throw error; + } - group[styleName] = styles[styleName]; + return make(path.dirname(pth)).then(() => make(pth)); + } - codes.set(style[0], style[1]); - } + return stat(pth) + .then(stats => stats.isDirectory() ? pth : Promise.reject()) + .catch(() => { + throw error; + }); + }); + }; - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); + return make(path.resolve(input)); +}); - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false +module.exports = makeDir; +module.exports.default = makeDir; + +module.exports.sync = (input, options) => { + checkPath(input); + options = Object.assign({}, defaults, options); + + if (useNativeRecursiveOption && options.fs.mkdirSync === fs.mkdirSync) { + const pth = path.resolve(input); + + fs.mkdirSync(pth, { + mode: options.mode, + recursive: true }); + + return pth; } - const ansi2ansi = n => n; - const rgb2rgb = (r, g, b) => [r, g, b]; + const make = pth => { + try { + options.fs.mkdirSync(pth, options.mode); + } catch (error) { + if (error.code === 'EPERM') { + throw error; + } - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; + if (error.code === 'ENOENT') { + if (path.dirname(pth) === pth) { + throw permissionError(pth); + } - styles.color.ansi = { - ansi: wrapAnsi16(ansi2ansi, 0) - }; - styles.color.ansi256 = { - ansi256: wrapAnsi256(ansi2ansi, 0) - }; - styles.color.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 0) - }; + if (error.message.includes('null bytes')) { + throw error; + } - styles.bgColor.ansi = { - ansi: wrapAnsi16(ansi2ansi, 10) - }; - styles.bgColor.ansi256 = { - ansi256: wrapAnsi256(ansi2ansi, 10) - }; - styles.bgColor.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 10) - }; + make(path.dirname(pth)); + return make(pth); + } - for (let key of Object.keys(colorConvert)) { - if (typeof colorConvert[key] !== 'object') { - continue; + try { + if (!options.fs.statSync(pth).isDirectory()) { + throw new Error('The path is not a directory'); + } + } catch (_) { + throw error; + } } - const suite = colorConvert[key]; + return pth; + }; - if (key === 'ansi16') { - key = 'ansi'; - } + return make(path.resolve(input)); +}; - if ('ansi16' in suite) { - styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); - styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); - } - if ('ansi256' in suite) { - styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); - styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); - } +/***/ }), +/* 561 */ +/***/ (function(module, exports, __webpack_require__) { - if ('rgb' in suite) { - styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); - styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); +"use strict"; + + +const processFn = (fn, options) => function (...args) { + const P = options.promiseModule; + + return new P((resolve, reject) => { + if (options.multiArgs) { + args.push((...result) => { + if (options.errorFirst) { + if (result[0]) { + reject(result); + } else { + result.shift(); + resolve(result); + } + } else { + resolve(result); + } + }); + } else if (options.errorFirst) { + args.push((error, result) => { + if (error) { + reject(error); + } else { + resolve(result); + } + }); + } else { + args.push(resolve); } + + fn.apply(this, args); + }); +}; + +module.exports = (input, options) => { + options = Object.assign({ + exclude: [/.+(Sync|Stream)$/], + errorFirst: true, + promiseModule: Promise + }, options); + + const objType = typeof input; + if (!(input !== null && (objType === 'object' || objType === 'function'))) { + throw new TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${input === null ? 'null' : objType}\``); } - return styles; -} + const filter = key => { + const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key); + return options.include ? options.include.some(match) : !options.exclude.some(match); + }; -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); + let ret; + if (objType === 'function') { + ret = function (...args) { + return options.excludeMain ? input(...args) : processFn(input, options).apply(this, args); + }; + } else { + ret = Object.create(Object.getPrototypeOf(input)); + } + + for (const key in input) { // eslint-disable-line guard-for-in + const property = input[key]; + ret[key] = typeof property === 'function' && filter(key) ? processFn(property, options) : property; + } + + return ret; +}; -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(5)(module))) /***/ }), -/* 568 */ +/* 562 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const os = __webpack_require__(11); -const hasFlag = __webpack_require__(12); -const env = process.env; +// detect either spaces or tabs but not both to properly handle tabs +// for indentation and spaces for alignment +const INDENT_RE = /^(?:( )+|\t+)/; + +function getMostUsed(indents) { + let result = 0; + let maxUsed = 0; + let maxWeight = 0; + + for (const entry of indents) { + // TODO: use destructuring when targeting Node.js 6 + const key = entry[0]; + const val = entry[1]; -let forceColor; -if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false')) { - forceColor = false; -} else if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - forceColor = true; -} -if ('FORCE_COLOR' in env) { - forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; -} + const u = val[0]; + const w = val[1]; -function translateLevel(level) { - if (level === 0) { - return false; + if (u > maxUsed || (u === maxUsed && w > maxWeight)) { + maxUsed = u; + maxWeight = w; + result = Number(key); + } } - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; + return result; } -function supportsColor(stream) { - if (forceColor === false) { - return 0; +module.exports = str => { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); } - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; - } + // used to see if tabs or spaces are the most used + let tabs = 0; + let spaces = 0; - if (hasFlag('color=256')) { - return 2; - } + // remember the size of previous line's indentation + let prev = 0; - if (stream && !stream.isTTY && forceColor !== true) { - // VS code debugger doesn't have isTTY set - if (env.VSCODE_PID) { - return 1; - } - return 0; - } + // remember how many indents/unindents as occurred for a given size + // and how much lines follow a given indentation + // + // indents = { + // 3: [1, 0], + // 4: [1, 5], + // 5: [1, 0], + // 12: [1, 0], + // } + const indents = new Map(); - const min = forceColor ? 1 : 0; + // pointer to the array of last used indent + let current; - if (process.platform === 'win32') { - // Node.js 7.5.0 is the first version of Node.js to include a patch to - // libuv that enables 256 color output on Windows. Anything earlier and it - // won't work. However, here we target Node.js 8 at minimum as it is an LTS - // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows - // release that supports 256 colors. Windows 10 build 14931 is the first release - // that supports 16m/TrueColor. - const osRelease = os.release().split('.'); - if ( - Number(process.versions.node.split('.')[0]) >= 8 && - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; + // whether the last action was an indent (opposed to an unindent) + let isIndent; + + for (const line of str.split(/\n/g)) { + if (!line) { + // ignore empty lines + continue; } - return 1; - } + let indent; + const matches = line.match(INDENT_RE); - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; + if (matches) { + indent = matches[0].length; + + if (matches[1]) { + spaces++; + } else { + tabs++; + } + } else { + indent = 0; } - return min; - } + const diff = indent - prev; + prev = indent; - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } + if (diff) { + // an indent or unindent has been detected - if (env.COLORTERM === 'truecolor') { - return 3; - } + isIndent = diff > 0; - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + current = indents.get(isIndent ? diff : -diff); - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default + if (current) { + current[0]++; + } else { + current = [1, 0]; + indents.set(diff, current); + } + } else if (current) { + // if the last action was an indent, increment the weight + current[1] += Number(isIndent); } } - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } - - if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } - - if ('COLORTERM' in env) { - return 1; - } + const amount = getMostUsed(indents); - if (env.TERM === 'dumb') { - return min; + let type; + let indent; + if (!amount) { + type = null; + indent = ''; + } else if (spaces >= tabs) { + type = 'space'; + indent = ' '.repeat(amount); + } else { + type = 'tab'; + indent = '\t'.repeat(amount); } - return min; -} - -function getSupportLevel(stream) { - const level = supportsColor(stream); - return translateLevel(level); -} - -module.exports = { - supportsColor: getSupportLevel, - stdout: getSupportLevel(process.stdout), - stderr: getSupportLevel(process.stderr) + return { + amount, + type, + indent + }; }; /***/ }), -/* 569 */ -/***/ (function(module, exports, __webpack_require__) { +/* 563 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "installInDir", function() { return installInDir; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runScriptInPackage", function() { return runScriptInPackage; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runScriptInPackageStreaming", function() { return runScriptInPackageStreaming; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yarnWorkspacesInfo", function() { return yarnWorkspacesInfo; }); +/* harmony import */ var _child_process__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(564); +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ -const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; -const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; -const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; -const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; - -const ESCAPES = new Map([ - ['n', '\n'], - ['r', '\r'], - ['t', '\t'], - ['b', '\b'], - ['f', '\f'], - ['v', '\v'], - ['0', '\0'], - ['\\', '\\'], - ['e', '\u001B'], - ['a', '\u0007'] -]); +const YARN_EXEC = process.env.npm_execpath || 'yarn'; -function unescape(c) { - if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { - return String.fromCharCode(parseInt(c.slice(1), 16)); - } +/** + * Install all dependencies in the given directory + */ +async function installInDir(directory, extraArgs = []) { + const options = ['install', '--non-interactive', ...extraArgs]; // We pass the mutex flag to ensure only one instance of yarn runs at any + // given time (e.g. to avoid conflicts). - return ESCAPES.get(c) || c; + await Object(_child_process__WEBPACK_IMPORTED_MODULE_0__["spawn"])(YARN_EXEC, options, { + cwd: directory + }); } +/** + * Run script in the given directory + */ -function parseArguments(name, args) { - const results = []; - const chunks = args.trim().split(/\s*,\s*/g); - let matches; +async function runScriptInPackage(script, args, pkg) { + const execOpts = { + cwd: pkg.path + }; + await Object(_child_process__WEBPACK_IMPORTED_MODULE_0__["spawn"])(YARN_EXEC, ['run', script, ...args], execOpts); +} +/** + * Run script in the given directory + */ - for (const chunk of chunks) { - if (!isNaN(chunk)) { - results.push(Number(chunk)); - } else if ((matches = chunk.match(STRING_REGEX))) { - results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); - } else { - throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); - } - } +function runScriptInPackageStreaming({ + script, + args, + pkg, + debug +}) { + const execOpts = { + cwd: pkg.path + }; + return Object(_child_process__WEBPACK_IMPORTED_MODULE_0__["spawnStreaming"])(YARN_EXEC, ['run', script, ...args], execOpts, { + prefix: pkg.name, + debug + }); +} +async function yarnWorkspacesInfo(directory) { + const { + stdout + } = await Object(_child_process__WEBPACK_IMPORTED_MODULE_0__["spawn"])(YARN_EXEC, ['--json', 'workspaces', 'info'], { + cwd: directory, + stdio: 'pipe' + }); - return results; + try { + return JSON.parse(JSON.parse(stdout).data); + } catch (error) { + throw new Error(`'yarn workspaces info --json' produced unexpected output: \n${stdout}`); + } } -function parseStyle(style) { - STYLE_REGEX.lastIndex = 0; +/***/ }), +/* 564 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - const results = []; - let matches; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "spawn", function() { return spawn; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "spawnStreaming", function() { return spawnStreaming; }); +/* harmony import */ var stream__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(382); +/* harmony import */ var stream__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(stream__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(386); +/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(chalk__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var execa__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(342); +/* harmony import */ var execa__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(execa__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var strong_log_transformer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(565); +/* harmony import */ var strong_log_transformer__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(strong_log_transformer__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(500); +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - while ((matches = STYLE_REGEX.exec(style)) !== null) { - const name = matches[1]; +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - if (matches[2]) { - const args = parseArguments(name, matches[2]); - results.push([name].concat(args)); - } else { - results.push([name]); - } - } +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; } - return results; -} +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ -function buildStyle(chalk, styles) { - const enabled = {}; - for (const layer of styles) { - for (const style of layer.styles) { - enabled[style[0]] = layer.inverse ? null : style.slice(1); - } - } - let current = chalk; - for (const styleName of Object.keys(enabled)) { - if (Array.isArray(enabled[styleName])) { - if (!(styleName in current)) { - throw new Error(`Unknown Chalk style: ${styleName}`); - } - if (enabled[styleName].length > 0) { - current = current[styleName].apply(current, enabled[styleName]); - } else { - current = current[styleName]; - } - } - } - return current; -} +const colorWheel = [chalk__WEBPACK_IMPORTED_MODULE_1___default.a.cyan, chalk__WEBPACK_IMPORTED_MODULE_1___default.a.magenta, chalk__WEBPACK_IMPORTED_MODULE_1___default.a.blue, chalk__WEBPACK_IMPORTED_MODULE_1___default.a.yellow, chalk__WEBPACK_IMPORTED_MODULE_1___default.a.green]; -module.exports = (chalk, tmp) => { - const styles = []; - const chunks = []; - let chunk = []; +const getColor = () => { + const color = colorWheel.shift(); + colorWheel.push(color); + return color; +}; - // eslint-disable-next-line max-params - tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { - if (escapeChar) { - chunk.push(unescape(escapeChar)); - } else if (style) { - const str = chunk.join(''); - chunk = []; - chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); - styles.push({inverse, styles: parseStyle(style)}); - } else if (close) { - if (styles.length === 0) { - throw new Error('Found extraneous } in Chalk template literal'); - } +function spawn(command, args, opts) { + return execa__WEBPACK_IMPORTED_MODULE_2___default()(command, args, _objectSpread({ + stdio: 'inherit', + preferLocal: true + }, opts)); +} - chunks.push(buildStyle(chalk, styles)(chunk.join(''))); - chunk = []; - styles.pop(); - } else { - chunk.push(chr); - } - }); +function streamToLog(debug = true) { + return new stream__WEBPACK_IMPORTED_MODULE_0__["Writable"]({ + objectMode: true, - chunks.push(chunk.join('')); + write(line, _, cb) { + if (line.endsWith('\n')) { + _log__WEBPACK_IMPORTED_MODULE_4__["log"][debug ? 'debug' : 'write'](line.slice(0, -1)); + } else { + _log__WEBPACK_IMPORTED_MODULE_4__["log"][debug ? 'debug' : 'write'](line); + } - if (styles.length > 0) { - const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; - throw new Error(errMsg); - } + cb(); + } - return chunks.join(''); -}; + }); +} +function spawnStreaming(command, args, opts, { + prefix, + debug +}) { + const spawned = execa__WEBPACK_IMPORTED_MODULE_2___default()(command, args, _objectSpread({ + stdio: ['ignore', 'pipe', 'pipe'], + preferLocal: true + }, opts)); + const color = getColor(); + const prefixedStdout = strong_log_transformer__WEBPACK_IMPORTED_MODULE_3___default()({ + tag: color.bold(prefix) + }); + const prefixedStderr = strong_log_transformer__WEBPACK_IMPORTED_MODULE_3___default()({ + mergeMultiline: true, + tag: color.bold(prefix) + }); + spawned.stdout.pipe(prefixedStdout).pipe(streamToLog(debug)); + spawned.stderr.pipe(prefixedStderr).pipe(streamToLog(debug)); + return spawned; +} /***/ }), -/* 570 */ +/* 565 */ /***/ (function(module, exports, __webpack_require__) { // Copyright IBM Corp. 2014,2018. All Rights Reserved. @@ -56063,12 +55406,12 @@ module.exports = (chalk, tmp) => { // This file is licensed under the Apache License 2.0. // License text available at https://opensource.org/licenses/Apache-2.0 -module.exports = __webpack_require__(571); -module.exports.cli = __webpack_require__(575); +module.exports = __webpack_require__(566); +module.exports.cli = __webpack_require__(570); /***/ }), -/* 571 */ +/* 566 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -56079,13 +55422,13 @@ module.exports.cli = __webpack_require__(575); -var stream = __webpack_require__(27); -var util = __webpack_require__(29); -var fs = __webpack_require__(23); +var stream = __webpack_require__(382); +var util = __webpack_require__(397); +var fs = __webpack_require__(349); -var through = __webpack_require__(572); -var duplexer = __webpack_require__(573); -var StringDecoder = __webpack_require__(574).StringDecoder; +var through = __webpack_require__(567); +var duplexer = __webpack_require__(568); +var StringDecoder = __webpack_require__(569).StringDecoder; module.exports = Logger; @@ -56274,10 +55617,10 @@ function lineMerger(host) { /***/ }), -/* 572 */ +/* 567 */ /***/ (function(module, exports, __webpack_require__) { -var Stream = __webpack_require__(27) +var Stream = __webpack_require__(382) // through // @@ -56388,10 +55731,10 @@ function through (write, end, opts) { /***/ }), -/* 573 */ +/* 568 */ /***/ (function(module, exports, __webpack_require__) { -var Stream = __webpack_require__(27) +var Stream = __webpack_require__(382) var writeMethods = ["write", "end", "destroy"] var readMethods = ["resume", "pause"] var readEvents = ["data", "close"] @@ -56481,13 +55824,13 @@ function duplex(writer, reader) { /***/ }), -/* 574 */ +/* 569 */ /***/ (function(module, exports) { module.exports = require("string_decoder"); /***/ }), -/* 575 */ +/* 570 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -56498,11 +55841,11 @@ module.exports = require("string_decoder"); -var minimist = __webpack_require__(576); -var path = __webpack_require__(16); +var minimist = __webpack_require__(571); +var path = __webpack_require__(4); -var Logger = __webpack_require__(571); -var pkg = __webpack_require__(577); +var Logger = __webpack_require__(566); +var pkg = __webpack_require__(572); module.exports = cli; @@ -56556,7 +55899,7 @@ function usage($0, p) { /***/ }), -/* 576 */ +/* 571 */ /***/ (function(module, exports) { module.exports = function (args, opts) { @@ -56798,13 +56141,13 @@ function isNumber (x) { /***/ }), -/* 577 */ +/* 572 */ /***/ (function(module) { module.exports = JSON.parse("{\"name\":\"strong-log-transformer\",\"version\":\"2.1.0\",\"description\":\"Stream transformer that prefixes lines with timestamps and other things.\",\"author\":\"Ryan Graham \",\"license\":\"Apache-2.0\",\"repository\":{\"type\":\"git\",\"url\":\"git://github.com/strongloop/strong-log-transformer\"},\"keywords\":[\"logging\",\"streams\"],\"bugs\":{\"url\":\"https://github.com/strongloop/strong-log-transformer/issues\"},\"homepage\":\"https://github.com/strongloop/strong-log-transformer\",\"directories\":{\"test\":\"test\"},\"bin\":{\"sl-log-transformer\":\"bin/sl-log-transformer.js\"},\"main\":\"index.js\",\"scripts\":{\"test\":\"tap --100 test/test-*\"},\"dependencies\":{\"duplexer\":\"^0.1.1\",\"minimist\":\"^1.2.0\",\"through\":\"^2.3.4\"},\"devDependencies\":{\"tap\":\"^12.0.1\"},\"engines\":{\"node\":\">=4\"}}"); /***/ }), -/* 578 */ +/* 573 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -56813,12 +56156,12 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "copyWorkspacePackages", function() { return copyWorkspacePackages; }); /* harmony import */ var glob__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(503); /* harmony import */ var glob__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(glob__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16); +/* 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 util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(397); /* harmony import */ var util__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(579); -/* harmony import */ var _fs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(20); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(574); +/* harmony import */ var _fs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(491); /* harmony import */ var _package_json__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(518); /* harmony import */ var _projects__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(502); /* @@ -56912,13 +56255,13 @@ function packagesFromGlobPattern({ } /***/ }), -/* 579 */ +/* 574 */ /***/ (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__(16); +/* 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__); /* * Licensed to Elasticsearch B.V. under one or more contributor @@ -56982,21 +56325,21 @@ function getProjectPaths({ } /***/ }), -/* 580 */ +/* 575 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAllChecksums", function() { return getAllChecksums; }); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(23); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(349); /* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(581); +/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(576); /* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(crypto__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(397); /* harmony import */ var util__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var execa__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(371); +/* harmony import */ var execa__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(342); /* harmony import */ var execa__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(execa__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var _yarn_lock__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(582); +/* harmony import */ var _yarn_lock__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(577); /* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with @@ -57225,21 +56568,21 @@ async function getAllChecksums(kbn, log) { } /***/ }), -/* 581 */ +/* 576 */ /***/ (function(module, exports) { module.exports = require("crypto"); /***/ }), -/* 582 */ +/* 577 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readYarnLock", function() { return readYarnLock; }); -/* harmony import */ var _yarnpkg_lockfile__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(583); +/* harmony import */ var _yarnpkg_lockfile__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(578); /* harmony import */ var _yarnpkg_lockfile__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_yarnpkg_lockfile__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _utils_fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(20); +/* harmony import */ var _utils_fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(491); /* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with @@ -57281,7 +56624,7 @@ async function readYarnLock(kbn) { } /***/ }), -/* 583 */ +/* 578 */ /***/ (function(module, exports, __webpack_require__) { module.exports = @@ -57357,7 +56700,7 @@ module.exports = /* 0 */ /***/ (function(module, exports) { -module.exports = __webpack_require__(16); +module.exports = __webpack_require__(4); /***/ }), /* 1 */ @@ -57407,13 +56750,13 @@ exports.default = function (fn) { /* 2 */ /***/ (function(module, exports) { -module.exports = __webpack_require__(29); +module.exports = __webpack_require__(397); /***/ }), /* 3 */ /***/ (function(module, exports) { -module.exports = __webpack_require__(23); +module.exports = __webpack_require__(349); /***/ }), /* 4 */ @@ -58840,7 +58183,7 @@ module.exports = invariant; /* 9 */ /***/ (function(module, exports) { -module.exports = __webpack_require__(581); +module.exports = __webpack_require__(576); /***/ }), /* 10 */, @@ -59266,7 +58609,7 @@ exports.default = Lockfile; /* 17 */ /***/ (function(module, exports) { -module.exports = __webpack_require__(27); +module.exports = __webpack_require__(382); /***/ }), /* 18 */, @@ -59318,7 +58661,7 @@ function nullify(obj = {}) { /* 22 */ /***/ (function(module, exports) { -module.exports = __webpack_require__(30); +module.exports = __webpack_require__(371); /***/ }), /* 23 */ @@ -59505,7 +58848,7 @@ module.exports = {}; /* 36 */ /***/ (function(module, exports) { -module.exports = __webpack_require__(11); +module.exports = __webpack_require__(364); /***/ }), /* 37 */, @@ -59790,7 +59133,7 @@ exports.f = __webpack_require__(33) ? Object.defineProperty : function definePro /* 54 */ /***/ (function(module, exports) { -module.exports = __webpack_require__(399); +module.exports = __webpack_require__(373); /***/ }), /* 55 */ @@ -61164,7 +60507,7 @@ function onceStrict (fn) { /* 63 */ /***/ (function(module, exports) { -module.exports = __webpack_require__(584); +module.exports = __webpack_require__(579); /***/ }), /* 64 */, @@ -62102,7 +61445,7 @@ module.exports.win32 = win32; /* 79 */ /***/ (function(module, exports) { -module.exports = __webpack_require__(484); +module.exports = __webpack_require__(471); /***/ }), /* 80 */, @@ -67559,21 +66902,21 @@ module.exports = process && support(supportLevel); /******/ ]); /***/ }), -/* 584 */ +/* 579 */ /***/ (function(module, exports) { module.exports = require("buffer"); /***/ }), -/* 585 */ +/* 580 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BootstrapCacheFile", function() { return BootstrapCacheFile; }); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(23); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(349); /* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16); +/* 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__); 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; } @@ -67662,22 +67005,20 @@ class BootstrapCacheFile { } /***/ }), -/* 586 */ +/* 581 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CleanCommand", function() { return CleanCommand; }); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(chalk__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var del__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(587); -/* 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__(675); -/* 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__(16); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var _utils_fs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(20); -/* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(34); +/* harmony import */ var del__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(582); +/* harmony import */ var del__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(del__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var ora__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(670); +/* harmony import */ var ora__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(ora__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 _utils_fs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(491); +/* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(500); /* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with @@ -67701,7 +67042,6 @@ __webpack_require__.r(__webpack_exports__); - const CleanCommand = { description: 'Remove the node_modules and target directories from all projects.', name: 'clean', @@ -67710,17 +67050,17 @@ const CleanCommand = { const toDelete = []; for (const project of projects.values()) { - if (await Object(_utils_fs__WEBPACK_IMPORTED_MODULE_4__["isDirectory"])(project.nodeModulesLocation)) { + if (await Object(_utils_fs__WEBPACK_IMPORTED_MODULE_3__["isDirectory"])(project.nodeModulesLocation)) { toDelete.push({ cwd: project.path, - pattern: Object(path__WEBPACK_IMPORTED_MODULE_3__["relative"])(project.path, project.nodeModulesLocation) + pattern: Object(path__WEBPACK_IMPORTED_MODULE_2__["relative"])(project.path, project.nodeModulesLocation) }); } - if (await Object(_utils_fs__WEBPACK_IMPORTED_MODULE_4__["isDirectory"])(project.targetLocation)) { + if (await Object(_utils_fs__WEBPACK_IMPORTED_MODULE_3__["isDirectory"])(project.targetLocation)) { toDelete.push({ cwd: project.path, - pattern: Object(path__WEBPACK_IMPORTED_MODULE_3__["relative"])(project.path, project.targetLocation) + pattern: Object(path__WEBPACK_IMPORTED_MODULE_2__["relative"])(project.path, project.targetLocation) }); } @@ -67737,9 +67077,8 @@ const CleanCommand = { } if (toDelete.length === 0) { - _utils_log__WEBPACK_IMPORTED_MODULE_5__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.bold.green('\n\nNothing to delete')); + _utils_log__WEBPACK_IMPORTED_MODULE_4__["log"].success('Nothing to delete'); } else { - _utils_log__WEBPACK_IMPORTED_MODULE_5__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.bold.red('\n\nDeleting:\n')); /** * In order to avoid patterns like `/build` in packages from accidentally * impacting files outside the package we use `process.chdir()` to change @@ -67749,7 +67088,6 @@ const CleanCommand = { * `del()` does support a `cwd` option, but it's only for resolving the * patterns and does not impact the cwd check. */ - const originalCwd = process.cwd(); try { @@ -67758,8 +67096,12 @@ const CleanCommand = { cwd } of toDelete) { process.chdir(cwd); - const promise = del__WEBPACK_IMPORTED_MODULE_1___default()(pattern); - ora__WEBPACK_IMPORTED_MODULE_2___default.a.promise(promise, Object(path__WEBPACK_IMPORTED_MODULE_3__["relative"])(originalCwd, Object(path__WEBPACK_IMPORTED_MODULE_3__["join"])(cwd, String(pattern)))); + const promise = del__WEBPACK_IMPORTED_MODULE_0___default()(pattern); + + if (_utils_log__WEBPACK_IMPORTED_MODULE_4__["log"].wouldLogLevel('info')) { + ora__WEBPACK_IMPORTED_MODULE_1___default.a.promise(promise, Object(path__WEBPACK_IMPORTED_MODULE_2__["relative"])(originalCwd, Object(path__WEBPACK_IMPORTED_MODULE_2__["join"])(cwd, String(pattern)))); + } + await promise; } } finally { @@ -67771,21 +67113,21 @@ const CleanCommand = { }; /***/ }), -/* 587 */ +/* 582 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const {promisify} = __webpack_require__(29); -const path = __webpack_require__(16); -const globby = __webpack_require__(588); -const isGlob = __webpack_require__(605); -const slash = __webpack_require__(666); -const gracefulFs = __webpack_require__(22); -const isPathCwd = __webpack_require__(668); -const isPathInside = __webpack_require__(669); -const rimraf = __webpack_require__(670); -const pMap = __webpack_require__(671); +const {promisify} = __webpack_require__(397); +const path = __webpack_require__(4); +const globby = __webpack_require__(583); +const isGlob = __webpack_require__(600); +const slash = __webpack_require__(661); +const gracefulFs = __webpack_require__(493); +const isPathCwd = __webpack_require__(663); +const isPathInside = __webpack_require__(664); +const rimraf = __webpack_require__(665); +const pMap = __webpack_require__(666); const rimrafP = promisify(rimraf); @@ -67899,19 +67241,19 @@ module.exports.sync = (patterns, {force, dryRun, cwd = process.cwd(), ...options /***/ }), -/* 588 */ +/* 583 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const fs = __webpack_require__(23); -const arrayUnion = __webpack_require__(589); -const merge2 = __webpack_require__(590); -const glob = __webpack_require__(591); -const fastGlob = __webpack_require__(596); -const dirGlob = __webpack_require__(662); -const gitignore = __webpack_require__(664); -const {FilterStream, UniqueStream} = __webpack_require__(667); +const fs = __webpack_require__(349); +const arrayUnion = __webpack_require__(584); +const merge2 = __webpack_require__(585); +const glob = __webpack_require__(586); +const fastGlob = __webpack_require__(591); +const dirGlob = __webpack_require__(657); +const gitignore = __webpack_require__(659); +const {FilterStream, UniqueStream} = __webpack_require__(662); const DEFAULT_FILTER = () => false; @@ -68084,7 +67426,7 @@ module.exports.gitignore = gitignore; /***/ }), -/* 589 */ +/* 584 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -68096,7 +67438,7 @@ module.exports = (...arguments_) => { /***/ }), -/* 590 */ +/* 585 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -68108,7 +67450,7 @@ module.exports = (...arguments_) => { * Copyright (c) 2014-2016 Teambition * Licensed under the MIT license. */ -const Stream = __webpack_require__(27) +const Stream = __webpack_require__(382) const PassThrough = Stream.PassThrough const slice = Array.prototype.slice @@ -68210,7 +67552,7 @@ function pauseStreams (streams, options) { /***/ }), -/* 591 */ +/* 586 */ /***/ (function(module, exports, __webpack_require__) { // Approach: @@ -68255,27 +67597,27 @@ function pauseStreams (streams, options) { module.exports = glob -var fs = __webpack_require__(23) +var fs = __webpack_require__(349) var rp = __webpack_require__(504) var minimatch = __webpack_require__(506) var Minimatch = minimatch.Minimatch -var inherits = __webpack_require__(592) -var EE = __webpack_require__(399).EventEmitter -var path = __webpack_require__(16) -var assert = __webpack_require__(30) +var inherits = __webpack_require__(587) +var EE = __webpack_require__(373).EventEmitter +var path = __webpack_require__(4) +var assert = __webpack_require__(371) var isAbsolute = __webpack_require__(512) -var globSync = __webpack_require__(594) -var common = __webpack_require__(595) +var globSync = __webpack_require__(589) +var common = __webpack_require__(590) var alphasort = common.alphasort var alphasorti = common.alphasorti var setopts = common.setopts var ownProp = common.ownProp var inflight = __webpack_require__(515) -var util = __webpack_require__(29) +var util = __webpack_require__(397) var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored -var once = __webpack_require__(404) +var once = __webpack_require__(378) function glob (pattern, options, cb) { if (typeof options === 'function') cb = options, options = {} @@ -69006,22 +68348,22 @@ Glob.prototype._stat2 = function (f, abs, er, stat, cb) { /***/ }), -/* 592 */ +/* 587 */ /***/ (function(module, exports, __webpack_require__) { try { - var util = __webpack_require__(29); + var util = __webpack_require__(397); /* istanbul ignore next */ if (typeof util.inherits !== 'function') throw ''; module.exports = util.inherits; } catch (e) { /* istanbul ignore next */ - module.exports = __webpack_require__(593); + module.exports = __webpack_require__(588); } /***/ }), -/* 593 */ +/* 588 */ /***/ (function(module, exports) { if (typeof Object.create === 'function') { @@ -69054,22 +68396,22 @@ if (typeof Object.create === 'function') { /***/ }), -/* 594 */ +/* 589 */ /***/ (function(module, exports, __webpack_require__) { module.exports = globSync globSync.GlobSync = GlobSync -var fs = __webpack_require__(23) +var fs = __webpack_require__(349) var rp = __webpack_require__(504) var minimatch = __webpack_require__(506) var Minimatch = minimatch.Minimatch -var Glob = __webpack_require__(591).Glob -var util = __webpack_require__(29) -var path = __webpack_require__(16) -var assert = __webpack_require__(30) +var Glob = __webpack_require__(586).Glob +var util = __webpack_require__(397) +var path = __webpack_require__(4) +var assert = __webpack_require__(371) var isAbsolute = __webpack_require__(512) -var common = __webpack_require__(595) +var common = __webpack_require__(590) var alphasort = common.alphasort var alphasorti = common.alphasorti var setopts = common.setopts @@ -69546,7 +68888,7 @@ GlobSync.prototype._makeAbs = function (f) { /***/ }), -/* 595 */ +/* 590 */ /***/ (function(module, exports, __webpack_require__) { exports.alphasort = alphasort @@ -69563,7 +68905,7 @@ function ownProp (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } -var path = __webpack_require__(16) +var path = __webpack_require__(4) var minimatch = __webpack_require__(506) var isAbsolute = __webpack_require__(512) var Minimatch = minimatch.Minimatch @@ -69792,17 +69134,17 @@ function childrenIgnored (self, path) { /***/ }), -/* 596 */ +/* 591 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const taskManager = __webpack_require__(597); -const async_1 = __webpack_require__(625); -const stream_1 = __webpack_require__(658); -const sync_1 = __webpack_require__(659); -const settings_1 = __webpack_require__(661); -const utils = __webpack_require__(598); +const taskManager = __webpack_require__(592); +const async_1 = __webpack_require__(620); +const stream_1 = __webpack_require__(653); +const sync_1 = __webpack_require__(654); +const settings_1 = __webpack_require__(656); +const utils = __webpack_require__(593); function FastGlob(source, options) { try { assertPatternsInput(source); @@ -69860,13 +69202,13 @@ module.exports = FastGlob; /***/ }), -/* 597 */ +/* 592 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const utils = __webpack_require__(598); +const utils = __webpack_require__(593); function generate(patterns, settings) { const positivePatterns = getPositivePatterns(patterns); const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore); @@ -69934,28 +69276,28 @@ exports.convertPatternGroupToTask = convertPatternGroupToTask; /***/ }), -/* 598 */ +/* 593 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const array = __webpack_require__(599); +const array = __webpack_require__(594); exports.array = array; -const errno = __webpack_require__(600); +const errno = __webpack_require__(595); exports.errno = errno; -const fs = __webpack_require__(601); +const fs = __webpack_require__(596); exports.fs = fs; -const path = __webpack_require__(602); +const path = __webpack_require__(597); exports.path = path; -const pattern = __webpack_require__(603); +const pattern = __webpack_require__(598); exports.pattern = pattern; -const stream = __webpack_require__(624); +const stream = __webpack_require__(619); exports.stream = stream; /***/ }), -/* 599 */ +/* 594 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -69968,7 +69310,7 @@ exports.flatten = flatten; /***/ }), -/* 600 */ +/* 595 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -69981,7 +69323,7 @@ exports.isEnoentCodeError = isEnoentCodeError; /***/ }), -/* 601 */ +/* 596 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -70006,13 +69348,13 @@ exports.createDirentFromStats = createDirentFromStats; /***/ }), -/* 602 */ +/* 597 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const path = __webpack_require__(16); +const path = __webpack_require__(4); /** * Designed to work only with simple paths: `dir\\file`. */ @@ -70027,16 +69369,16 @@ exports.makeAbsolute = makeAbsolute; /***/ }), -/* 603 */ +/* 598 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const path = __webpack_require__(16); -const globParent = __webpack_require__(604); -const isGlob = __webpack_require__(605); -const micromatch = __webpack_require__(607); +const path = __webpack_require__(4); +const globParent = __webpack_require__(599); +const isGlob = __webpack_require__(600); +const micromatch = __webpack_require__(602); const GLOBSTAR = '**'; function isStaticPattern(pattern) { return !isDynamicPattern(pattern); @@ -70125,15 +69467,15 @@ exports.matchAny = matchAny; /***/ }), -/* 604 */ +/* 599 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isGlob = __webpack_require__(605); -var pathPosixDirname = __webpack_require__(16).posix.dirname; -var isWin32 = __webpack_require__(11).platform() === 'win32'; +var isGlob = __webpack_require__(600); +var pathPosixDirname = __webpack_require__(4).posix.dirname; +var isWin32 = __webpack_require__(364).platform() === 'win32'; var slash = '/'; var backslash = /\\/g; @@ -70166,7 +69508,7 @@ module.exports = function globParent(str) { /***/ }), -/* 605 */ +/* 600 */ /***/ (function(module, exports, __webpack_require__) { /*! @@ -70176,7 +69518,7 @@ module.exports = function globParent(str) { * Released under the MIT License. */ -var isExtglob = __webpack_require__(606); +var isExtglob = __webpack_require__(601); var chars = { '{': '}', '(': ')', '[': ']'}; var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/; var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/; @@ -70220,7 +69562,7 @@ module.exports = function isGlob(str, options) { /***/ }), -/* 606 */ +/* 601 */ /***/ (function(module, exports) { /*! @@ -70246,16 +69588,16 @@ module.exports = function isExtglob(str) { /***/ }), -/* 607 */ +/* 602 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const util = __webpack_require__(29); -const braces = __webpack_require__(608); -const picomatch = __webpack_require__(618); -const utils = __webpack_require__(621); +const util = __webpack_require__(397); +const braces = __webpack_require__(603); +const picomatch = __webpack_require__(613); +const utils = __webpack_require__(616); const isEmptyString = val => typeof val === 'string' && (val === '' || val === './'); /** @@ -70720,16 +70062,16 @@ module.exports = micromatch; /***/ }), -/* 608 */ +/* 603 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const stringify = __webpack_require__(609); -const compile = __webpack_require__(611); -const expand = __webpack_require__(615); -const parse = __webpack_require__(616); +const stringify = __webpack_require__(604); +const compile = __webpack_require__(606); +const expand = __webpack_require__(610); +const parse = __webpack_require__(611); /** * Expand the given pattern or create a regex-compatible string. @@ -70897,13 +70239,13 @@ module.exports = braces; /***/ }), -/* 609 */ +/* 604 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const utils = __webpack_require__(610); +const utils = __webpack_require__(605); module.exports = (ast, options = {}) => { let stringify = (node, parent = {}) => { @@ -70936,7 +70278,7 @@ module.exports = (ast, options = {}) => { /***/ }), -/* 610 */ +/* 605 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -71055,14 +70397,14 @@ exports.flatten = (...args) => { /***/ }), -/* 611 */ +/* 606 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const fill = __webpack_require__(612); -const utils = __webpack_require__(610); +const fill = __webpack_require__(607); +const utils = __webpack_require__(605); const compile = (ast, options = {}) => { let walk = (node, parent = {}) => { @@ -71119,7 +70461,7 @@ module.exports = compile; /***/ }), -/* 612 */ +/* 607 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -71132,8 +70474,8 @@ module.exports = compile; -const util = __webpack_require__(29); -const toRegexRange = __webpack_require__(613); +const util = __webpack_require__(397); +const toRegexRange = __webpack_require__(608); const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); @@ -71375,7 +70717,7 @@ module.exports = fill; /***/ }), -/* 613 */ +/* 608 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -71388,7 +70730,7 @@ module.exports = fill; -const isNumber = __webpack_require__(614); +const isNumber = __webpack_require__(609); const toRegexRange = (min, max, options) => { if (isNumber(min) === false) { @@ -71670,7 +71012,7 @@ module.exports = toRegexRange; /***/ }), -/* 614 */ +/* 609 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -71695,15 +71037,15 @@ module.exports = function(num) { /***/ }), -/* 615 */ +/* 610 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const fill = __webpack_require__(612); -const stringify = __webpack_require__(609); -const utils = __webpack_require__(610); +const fill = __webpack_require__(607); +const stringify = __webpack_require__(604); +const utils = __webpack_require__(605); const append = (queue = '', stash = '', enclose = false) => { let result = []; @@ -71815,13 +71157,13 @@ module.exports = expand; /***/ }), -/* 616 */ +/* 611 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const stringify = __webpack_require__(609); +const stringify = __webpack_require__(604); /** * Constants @@ -71843,7 +71185,7 @@ const { CHAR_SINGLE_QUOTE, /* ' */ CHAR_NO_BREAK_SPACE, CHAR_ZERO_WIDTH_NOBREAK_SPACE -} = __webpack_require__(617); +} = __webpack_require__(612); /** * parse @@ -72155,7 +71497,7 @@ module.exports = parse; /***/ }), -/* 617 */ +/* 612 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -72219,26 +71561,26 @@ module.exports = { /***/ }), -/* 618 */ +/* 613 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = __webpack_require__(619); +module.exports = __webpack_require__(614); /***/ }), -/* 619 */ +/* 614 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const path = __webpack_require__(16); -const scan = __webpack_require__(620); -const parse = __webpack_require__(623); -const utils = __webpack_require__(621); +const path = __webpack_require__(4); +const scan = __webpack_require__(615); +const parse = __webpack_require__(618); +const utils = __webpack_require__(616); /** * Creates a matcher function from one or more glob patterns. The @@ -72541,7 +71883,7 @@ picomatch.toRegex = (source, options) => { * @return {Object} */ -picomatch.constants = __webpack_require__(622); +picomatch.constants = __webpack_require__(617); /** * Expose "picomatch" @@ -72551,13 +71893,13 @@ module.exports = picomatch; /***/ }), -/* 620 */ +/* 615 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const utils = __webpack_require__(621); +const utils = __webpack_require__(616); const { CHAR_ASTERISK, /* * */ @@ -72575,7 +71917,7 @@ const { CHAR_RIGHT_CURLY_BRACE, /* } */ CHAR_RIGHT_PARENTHESES, /* ) */ CHAR_RIGHT_SQUARE_BRACKET /* ] */ -} = __webpack_require__(622); +} = __webpack_require__(617); const isPathSeparator = code => { return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; @@ -72777,19 +72119,19 @@ module.exports = (input, options) => { /***/ }), -/* 621 */ +/* 616 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const path = __webpack_require__(16); +const path = __webpack_require__(4); const win32 = process.platform === 'win32'; const { REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL, REGEX_REMOVE_BACKSLASH -} = __webpack_require__(622); +} = __webpack_require__(617); exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); @@ -72827,13 +72169,13 @@ exports.escapeLast = (input, char, lastIdx) => { /***/ }), -/* 622 */ +/* 617 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const path = __webpack_require__(16); +const path = __webpack_require__(4); const WIN_SLASH = '\\\\/'; const WIN_NO_SLASH = `[^${WIN_SLASH}]`; @@ -73013,14 +72355,14 @@ module.exports = { /***/ }), -/* 623 */ +/* 618 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const utils = __webpack_require__(621); -const constants = __webpack_require__(622); +const utils = __webpack_require__(616); +const constants = __webpack_require__(617); /** * Constants @@ -73175,2463 +72517,3370 @@ const parse = (input, options) => { state.consumed += token.value || ''; }; - const increment = type => { - state[type]++; - stack.push(type); - }; + const increment = type => { + state[type]++; + stack.push(type); + }; + + const decrement = type => { + state[type]--; + stack.pop(); + }; + + /** + * Push tokens onto the tokens array. This helper speeds up + * tokenizing by 1) helping us avoid backtracking as much as possible, + * and 2) helping us avoid creating extra tokens when consecutive + * characters are plain text. This improves performance and simplifies + * lookbehinds. + */ + + const push = tok => { + if (prev.type === 'globstar') { + let isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); + let isExtglob = extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'); + if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { + state.output = state.output.slice(0, -prev.output.length); + prev.type = 'star'; + prev.value = '*'; + prev.output = star; + state.output += prev.output; + } + } + + if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) { + extglobs[extglobs.length - 1].inner += tok.value; + } + + if (tok.value || tok.output) append(tok); + if (prev && prev.type === 'text' && tok.type === 'text') { + prev.value += tok.value; + return; + } + + tok.prev = prev; + tokens.push(tok); + prev = tok; + }; + + const extglobOpen = (type, value) => { + let token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; + + token.prev = prev; + token.parens = state.parens; + token.output = state.output; + let output = (opts.capture ? '(' : '') + token.open; + + push({ type, value, output: state.output ? '' : ONE_CHAR }); + push({ type: 'paren', extglob: true, value: advance(), output }); + increment('parens'); + extglobs.push(token); + }; + + const extglobClose = token => { + let output = token.close + (opts.capture ? ')' : ''); + + if (token.type === 'negate') { + let extglobStar = star; + + if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { + extglobStar = globstar(opts); + } + + if (extglobStar !== star || eos() || /^\)+$/.test(input.slice(state.index + 1))) { + output = token.close = ')$))' + extglobStar; + } + + if (token.prev.type === 'bos' && eos()) { + state.negatedExtglob = true; + } + } + + push({ type: 'paren', extglob: true, value, output }); + decrement('parens'); + }; + + if (opts.fastpaths !== false && !/(^[*!]|[/{[()\]}"])/.test(input)) { + let backslashes = false; + + let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { + if (first === '\\') { + backslashes = true; + return m; + } + + if (first === '?') { + if (esc) { + return esc + first + (rest ? QMARK.repeat(rest.length) : ''); + } + if (index === 0) { + return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); + } + return QMARK.repeat(chars.length); + } + + if (first === '.') { + return DOT_LITERAL.repeat(chars.length); + } + + if (first === '*') { + if (esc) { + return esc + first + (rest ? star : ''); + } + return star; + } + return esc ? m : '\\' + m; + }); + + if (backslashes === true) { + if (opts.unescape === true) { + output = output.replace(/\\/g, ''); + } else { + output = output.replace(/\\+/g, m => { + return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); + }); + } + } + + state.output = output; + return state; + } + + /** + * Tokenize input until we reach end-of-string + */ + + while (!eos()) { + value = advance(); + + if (value === '\u0000') { + continue; + } + + /** + * Escaped characters + */ + + if (value === '\\') { + let next = peek(); + + if (next === '/' && opts.bash !== true) { + continue; + } + + if (next === '.' || next === ';') { + continue; + } + + if (!next) { + value += '\\'; + push({ type: 'text', value }); + continue; + } + + // collapse slashes to reduce potential for exploits + let match = /^\\+/.exec(input.slice(state.index + 1)); + let slashes = 0; + + if (match && match[0].length > 2) { + slashes = match[0].length; + state.index += slashes; + if (slashes % 2 !== 0) { + value += '\\'; + } + } + + if (opts.unescape === true) { + value = advance() || ''; + } else { + value += advance() || ''; + } + + if (state.brackets === 0) { + push({ type: 'text', value }); + continue; + } + } + + /** + * If we're inside a regex character class, continue + * until we reach the closing bracket. + */ + + if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { + if (opts.posix !== false && value === ':') { + let inner = prev.value.slice(1); + if (inner.includes('[')) { + prev.posix = true; + + if (inner.includes(':')) { + let idx = prev.value.lastIndexOf('['); + let pre = prev.value.slice(0, idx); + let rest = prev.value.slice(idx + 2); + let posix = POSIX_REGEX_SOURCE[rest]; + if (posix) { + prev.value = pre + posix; + state.backtrack = true; + advance(); + + if (!bos.output && tokens.indexOf(prev) === 1) { + bos.output = ONE_CHAR; + } + continue; + } + } + } + } + + if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { + value = '\\' + value; + } + + if (value === ']' && (prev.value === '[' || prev.value === '[^')) { + value = '\\' + value; + } + + if (opts.posix === true && value === '!' && prev.value === '[') { + value = '^'; + } + + prev.value += value; + append({ value }); + continue; + } + + /** + * If we're inside a quoted string, continue + * until we reach the closing double quote. + */ + + if (state.quotes === 1 && value !== '"') { + value = utils.escapeRegex(value); + prev.value += value; + append({ value }); + continue; + } + + /** + * Double quotes + */ + + if (value === '"') { + state.quotes = state.quotes === 1 ? 0 : 1; + if (opts.keepQuotes === true) { + push({ type: 'text', value }); + } + continue; + } + + /** + * Parentheses + */ + + if (value === '(') { + push({ type: 'paren', value }); + increment('parens'); + continue; + } + + if (value === ')') { + if (state.parens === 0 && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '(')); + } + + let extglob = extglobs[extglobs.length - 1]; + if (extglob && state.parens === extglob.parens + 1) { + extglobClose(extglobs.pop()); + continue; + } + + push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); + decrement('parens'); + continue; + } + + /** + * Brackets + */ + + if (value === '[') { + if (opts.nobracket === true || !input.slice(state.index + 1).includes(']')) { + if (opts.nobracket !== true && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('closing', ']')); + } + + value = '\\' + value; + } else { + increment('brackets'); + } + + push({ type: 'bracket', value }); + continue; + } + + if (value === ']') { + if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { + push({ type: 'text', value, output: '\\' + value }); + continue; + } + + if (state.brackets === 0) { + if (opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '[')); + } + + push({ type: 'text', value, output: '\\' + value }); + continue; + } + + decrement('brackets'); + + let prevValue = prev.value.slice(1); + if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { + value = '/' + value; + } + + prev.value += value; + append({ value }); + + // when literal brackets are explicitly disabled + // assume we should match with a regex character class + if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { + continue; + } + + let escaped = utils.escapeRegex(prev.value); + state.output = state.output.slice(0, -prev.value.length); + + // when literal brackets are explicitly enabled + // assume we should escape the brackets to match literal characters + if (opts.literalBrackets === true) { + state.output += escaped; + prev.value = escaped; + continue; + } + + // when the user specifies nothing, try to match both + prev.value = `(${capture}${escaped}|${prev.value})`; + state.output += prev.value; + continue; + } + + /** + * Braces + */ + + if (value === '{' && opts.nobrace !== true) { + push({ type: 'brace', value, output: '(' }); + increment('braces'); + continue; + } + + if (value === '}') { + if (opts.nobrace === true || state.braces === 0) { + push({ type: 'text', value, output: '\\' + value }); + continue; + } + + let output = ')'; + + if (state.dots === true) { + let arr = tokens.slice(); + let range = []; + + for (let i = arr.length - 1; i >= 0; i--) { + tokens.pop(); + if (arr[i].type === 'brace') { + break; + } + if (arr[i].type !== 'dots') { + range.unshift(arr[i].value); + } + } + + output = expandRange(range, opts); + state.backtrack = true; + } + + push({ type: 'brace', value, output }); + decrement('braces'); + continue; + } + + /** + * Pipes + */ + + if (value === '|') { + if (extglobs.length > 0) { + extglobs[extglobs.length - 1].conditions++; + } + push({ type: 'text', value }); + continue; + } - const decrement = type => { - state[type]--; - stack.pop(); - }; + /** + * Commas + */ - /** - * Push tokens onto the tokens array. This helper speeds up - * tokenizing by 1) helping us avoid backtracking as much as possible, - * and 2) helping us avoid creating extra tokens when consecutive - * characters are plain text. This improves performance and simplifies - * lookbehinds. - */ + if (value === ',') { + let output = value; - const push = tok => { - if (prev.type === 'globstar') { - let isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); - let isExtglob = extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'); - if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { - state.output = state.output.slice(0, -prev.output.length); - prev.type = 'star'; - prev.value = '*'; - prev.output = star; - state.output += prev.output; + if (state.braces > 0 && stack[stack.length - 1] === 'braces') { + output = '|'; } - } - if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) { - extglobs[extglobs.length - 1].inner += tok.value; + push({ type: 'comma', value, output }); + continue; } - if (tok.value || tok.output) append(tok); - if (prev && prev.type === 'text' && tok.type === 'text') { - prev.value += tok.value; - return; + /** + * Slashes + */ + + if (value === '/') { + // if the beginning of the glob is "./", advance the start + // to the current index, and don't add the "./" characters + // to the state. This greatly simplifies lookbehinds when + // checking for BOS characters like "!" and "." (not "./") + if (prev.type === 'dot' && state.index === 1) { + state.start = state.index + 1; + state.consumed = ''; + state.output = ''; + tokens.pop(); + prev = bos; // reset "prev" to the first token + continue; + } + + push({ type: 'slash', value, output: SLASH_LITERAL }); + continue; } - tok.prev = prev; - tokens.push(tok); - prev = tok; - }; + /** + * Dots + */ - const extglobOpen = (type, value) => { - let token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; + if (value === '.') { + if (state.braces > 0 && prev.type === 'dot') { + if (prev.value === '.') prev.output = DOT_LITERAL; + prev.type = 'dots'; + prev.output += value; + prev.value += value; + state.dots = true; + continue; + } - token.prev = prev; - token.parens = state.parens; - token.output = state.output; - let output = (opts.capture ? '(' : '') + token.open; + push({ type: 'dot', value, output: DOT_LITERAL }); + continue; + } - push({ type, value, output: state.output ? '' : ONE_CHAR }); - push({ type: 'paren', extglob: true, value: advance(), output }); - increment('parens'); - extglobs.push(token); - }; + /** + * Question marks + */ - const extglobClose = token => { - let output = token.close + (opts.capture ? ')' : ''); + if (value === '?') { + if (prev && prev.type === 'paren') { + let next = peek(); + let output = value; - if (token.type === 'negate') { - let extglobStar = star; + if (next === '<' && !utils.supportsLookbehinds()) { + throw new Error('Node.js v10 or higher is required for regex lookbehinds'); + } - if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { - extglobStar = globstar(opts); + if (prev.value === '(' && !/[!=<:]/.test(next) || (next === '<' && !/[!=]/.test(peek(2)))) { + output = '\\' + value; + } + + push({ type: 'text', value, output }); + continue; } - if (extglobStar !== star || eos() || /^\)+$/.test(input.slice(state.index + 1))) { - output = token.close = ')$))' + extglobStar; + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('qmark', value); + continue; } - if (token.prev.type === 'bos' && eos()) { - state.negatedExtglob = true; + if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { + push({ type: 'qmark', value, output: QMARK_NO_DOT }); + continue; } + + push({ type: 'qmark', value, output: QMARK }); + continue; } - push({ type: 'paren', extglob: true, value, output }); - decrement('parens'); - }; + /** + * Exclamation + */ - if (opts.fastpaths !== false && !/(^[*!]|[/{[()\]}"])/.test(input)) { - let backslashes = false; + if (value === '!') { + if (opts.noextglob !== true && peek() === '(') { + if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { + extglobOpen('negate', value); + continue; + } + } - let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { - if (first === '\\') { - backslashes = true; - return m; + if (opts.nonegate !== true && state.index === 0) { + negate(state); + continue; } + } - if (first === '?') { - if (esc) { - return esc + first + (rest ? QMARK.repeat(rest.length) : ''); - } - if (index === 0) { - return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); - } - return QMARK.repeat(chars.length); + /** + * Plus + */ + + if (value === '+') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('plus', value); + continue; } - if (first === '.') { - return DOT_LITERAL.repeat(chars.length); + if (prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) { + let output = prev.extglob === true ? '\\' + value : value; + push({ type: 'plus', value, output }); + continue; } - if (first === '*') { - if (esc) { - return esc + first + (rest ? star : ''); - } - return star; + // use regex behavior inside parens + if (state.parens > 0 && opts.regex !== false) { + push({ type: 'plus', value }); + continue; } - return esc ? m : '\\' + m; - }); - if (backslashes === true) { - if (opts.unescape === true) { - output = output.replace(/\\/g, ''); - } else { - output = output.replace(/\\+/g, m => { - return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); - }); + push({ type: 'plus', value: PLUS_LITERAL }); + continue; + } + + /** + * Plain text + */ + + if (value === '@') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + push({ type: 'at', value, output: '' }); + continue; } + + push({ type: 'text', value }); + continue; } - state.output = output; - return state; - } + /** + * Plain text + */ - /** - * Tokenize input until we reach end-of-string - */ + if (value !== '*') { + if (value === '$' || value === '^') { + value = '\\' + value; + } - while (!eos()) { - value = advance(); + let match = REGEX_NON_SPECIAL_CHAR.exec(input.slice(state.index + 1)); + if (match) { + value += match[0]; + state.index += match[0].length; + } - if (value === '\u0000') { + push({ type: 'text', value }); continue; } /** - * Escaped characters + * Stars */ - if (value === '\\') { - let next = peek(); + if (prev && (prev.type === 'globstar' || prev.star === true)) { + prev.type = 'star'; + prev.star = true; + prev.value += value; + prev.output = star; + state.backtrack = true; + state.consumed += value; + continue; + } - if (next === '/' && opts.bash !== true) { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('star', value); + continue; + } + + if (prev.type === 'star') { + if (opts.noglobstar === true) { + state.consumed += value; continue; } - if (next === '.' || next === ';') { + let prior = prev.prev; + let before = prior.prev; + let isStart = prior.type === 'slash' || prior.type === 'bos'; + let afterStar = before && (before.type === 'star' || before.type === 'globstar'); + + if (opts.bash === true && (!isStart || (!eos() && peek() !== '/'))) { + push({ type: 'star', value, output: '' }); continue; } - if (!next) { - value += '\\'; - push({ type: 'text', value }); + let isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); + let isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); + if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { + push({ type: 'star', value, output: '' }); continue; } - // collapse slashes to reduce potential for exploits - let match = /^\\+/.exec(input.slice(state.index + 1)); - let slashes = 0; - - if (match && match[0].length > 2) { - slashes = match[0].length; - state.index += slashes; - if (slashes % 2 !== 0) { - value += '\\'; + // strip consecutive `/**/` + while (input.slice(state.index + 1, state.index + 4) === '/**') { + let after = input[state.index + 4]; + if (after && after !== '/') { + break; } + state.consumed += '/**'; + state.index += 3; } - if (opts.unescape === true) { - value = advance() || ''; - } else { - value += advance() || ''; + if (prior.type === 'bos' && eos()) { + prev.type = 'globstar'; + prev.value += value; + prev.output = globstar(opts); + state.output = prev.output; + state.consumed += value; + continue; } - if (state.brackets === 0) { - push({ type: 'text', value }); + if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = '(?:' + prior.output; + + prev.type = 'globstar'; + prev.output = globstar(opts) + '|$)'; + prev.value += value; + + state.output += prior.output + prev.output; + state.consumed += value; continue; } - } - /** - * If we're inside a regex character class, continue - * until we reach the closing bracket. - */ + let next = peek(); + if (prior.type === 'slash' && prior.prev.type !== 'bos' && next === '/') { + let end = peek(2) !== void 0 ? '|$' : ''; - if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { - if (opts.posix !== false && value === ':') { - let inner = prev.value.slice(1); - if (inner.includes('[')) { - prev.posix = true; + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = '(?:' + prior.output; - if (inner.includes(':')) { - let idx = prev.value.lastIndexOf('['); - let pre = prev.value.slice(0, idx); - let rest = prev.value.slice(idx + 2); - let posix = POSIX_REGEX_SOURCE[rest]; - if (posix) { - prev.value = pre + posix; - state.backtrack = true; - advance(); + prev.type = 'globstar'; + prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; + prev.value += value; - if (!bos.output && tokens.indexOf(prev) === 1) { - bos.output = ONE_CHAR; - } - continue; - } - } - } + state.output += prior.output + prev.output; + state.consumed += value + advance(); + + push({ type: 'slash', value, output: '' }); + continue; } - if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { - value = '\\' + value; + if (prior.type === 'bos' && next === '/') { + prev.type = 'globstar'; + prev.value += value; + prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; + state.output = prev.output; + state.consumed += value + advance(); + push({ type: 'slash', value, output: '' }); + continue; } - if (value === ']' && (prev.value === '[' || prev.value === '[^')) { - value = '\\' + value; + // remove single star from output + state.output = state.output.slice(0, -prev.output.length); + + // reset previous token to globstar + prev.type = 'globstar'; + prev.output = globstar(opts); + prev.value += value; + + // reset output with globstar + state.output += prev.output; + state.consumed += value; + continue; + } + + let token = { type: 'star', value, output: star }; + + if (opts.bash === true) { + token.output = '.*?'; + if (prev.type === 'bos' || prev.type === 'slash') { + token.output = nodot + token.output; + } + push(token); + continue; + } + + if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { + token.output = value; + push(token); + continue; + } + + if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { + if (prev.type === 'dot') { + state.output += NO_DOT_SLASH; + prev.output += NO_DOT_SLASH; + + } else if (opts.dot === true) { + state.output += NO_DOTS_SLASH; + prev.output += NO_DOTS_SLASH; + + } else { + state.output += nodot; + prev.output += nodot; } - if (opts.posix === true && value === '!' && prev.value === '[') { - value = '^'; + if (peek() !== '*') { + state.output += ONE_CHAR; + prev.output += ONE_CHAR; + } + } + + push(token); + } + + while (state.brackets > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); + state.output = utils.escapeLast(state.output, '['); + decrement('brackets'); + } + + while (state.parens > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); + state.output = utils.escapeLast(state.output, '('); + decrement('parens'); + } + + while (state.braces > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); + state.output = utils.escapeLast(state.output, '{'); + decrement('braces'); + } + + if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { + push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); + } + + // rebuild the output if we had to backtrack at any point + if (state.backtrack === true) { + state.output = ''; + + for (let token of state.tokens) { + state.output += token.output != null ? token.output : token.value; + + if (token.suffix) { + state.output += token.suffix; } + } + } + + return state; +}; + +/** + * Fast paths for creating regular expressions for common glob patterns. + * This can significantly speed up processing and has very little downside + * impact when none of the fast paths match. + */ + +parse.fastpaths = (input, options) => { + let opts = { ...options }; + let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + let len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + input = REPLACEMENTS[input] || input; + let win32 = utils.isWindows(options); + + // create constants based on platform, for windows or posix + const { + DOT_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOTS_SLASH, + STAR, + START_ANCHOR + } = constants.globChars(win32); + + let capture = opts.capture ? '' : '?:'; + let star = opts.bash === true ? '.*?' : STAR; + let nodot = opts.dot ? NO_DOTS : NO_DOT; + let slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; + + if (opts.capture) { + star = `(${star})`; + } + + const globstar = (opts) => { + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const create = str => { + switch (str) { + case '*': + return `${nodot}${ONE_CHAR}${star}`; + + case '.*': + return `${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*.*': + return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*/*': + return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; + + case '**': + return nodot + globstar(opts); + + case '**/*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; - prev.value += value; - append({ value }); - continue; - } + case '**/*.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; - /** - * If we're inside a quoted string, continue - * until we reach the closing double quote. - */ + case '**/.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; - if (state.quotes === 1 && value !== '"') { - value = utils.escapeRegex(value); - prev.value += value; - append({ value }); - continue; - } + default: { + let match = /^(.*?)\.(\w+)$/.exec(str); + if (!match) return; - /** - * Double quotes - */ + let source = create(match[1], options); + if (!source) return; - if (value === '"') { - state.quotes = state.quotes === 1 ? 0 : 1; - if (opts.keepQuotes === true) { - push({ type: 'text', value }); + return source + DOT_LITERAL + match[2]; } - continue; } + }; - /** - * Parentheses - */ + let output = create(input); + if (output && opts.strictSlashes !== true) { + output += `${SLASH_LITERAL}?`; + } - if (value === '(') { - push({ type: 'paren', value }); - increment('parens'); - continue; - } + return output; +}; - if (value === ')') { - if (state.parens === 0 && opts.strictBrackets === true) { - throw new SyntaxError(syntaxError('opening', '(')); - } +module.exports = parse; - let extglob = extglobs[extglobs.length - 1]; - if (extglob && state.parens === extglob.parens + 1) { - extglobClose(extglobs.pop()); - continue; - } - push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); - decrement('parens'); - continue; - } +/***/ }), +/* 619 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Brackets - */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const merge2 = __webpack_require__(585); +function merge(streams) { + const mergedStream = merge2(streams); + streams.forEach((stream) => { + stream.once('error', (err) => mergedStream.emit('error', err)); + }); + return mergedStream; +} +exports.merge = merge; - if (value === '[') { - if (opts.nobracket === true || !input.slice(state.index + 1).includes(']')) { - if (opts.nobracket !== true && opts.strictBrackets === true) { - throw new SyntaxError(syntaxError('closing', ']')); - } - value = '\\' + value; - } else { - increment('brackets'); - } +/***/ }), +/* 620 */ +/***/ (function(module, exports, __webpack_require__) { - push({ type: 'bracket', value }); - continue; - } +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const stream_1 = __webpack_require__(621); +const provider_1 = __webpack_require__(648); +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; - if (value === ']') { - if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { - push({ type: 'text', value, output: '\\' + value }); - continue; - } - if (state.brackets === 0) { - if (opts.strictBrackets === true) { - throw new SyntaxError(syntaxError('opening', '[')); - } +/***/ }), +/* 621 */ +/***/ (function(module, exports, __webpack_require__) { - push({ type: 'text', value, output: '\\' + value }); - continue; - } +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const stream_1 = __webpack_require__(382); +const fsStat = __webpack_require__(622); +const fsWalk = __webpack_require__(627); +const reader_1 = __webpack_require__(647); +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) => { + error ? reject(error) : resolve(stats); + }); + }); + } +} +exports.default = ReaderStream; - decrement('brackets'); - let prevValue = prev.value.slice(1); - if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { - value = '/' + value; - } +/***/ }), +/* 622 */ +/***/ (function(module, exports, __webpack_require__) { - prev.value += value; - append({ value }); +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const async = __webpack_require__(623); +const sync = __webpack_require__(624); +const settings_1 = __webpack_require__(625); +exports.Settings = settings_1.default; +function stat(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + return async.read(path, getSettings(), optionsOrSettingsOrCallback); + } + async.read(path, getSettings(optionsOrSettingsOrCallback), callback); +} +exports.stat = stat; +function statSync(path, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return sync.read(path, settings); +} +exports.statSync = statSync; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1.default) { + return settingsOrOptions; + } + return new settings_1.default(settingsOrOptions); +} - // when literal brackets are explicitly disabled - // assume we should match with a regex character class - if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { - continue; - } - let escaped = utils.escapeRegex(prev.value); - state.output = state.output.slice(0, -prev.value.length); +/***/ }), +/* 623 */ +/***/ (function(module, exports, __webpack_require__) { - // when literal brackets are explicitly enabled - // assume we should escape the brackets to match literal characters - if (opts.literalBrackets === true) { - state.output += escaped; - prev.value = escaped; - continue; - } +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +function read(path, settings, callback) { + settings.fs.lstat(path, (lstatError, lstat) => { + if (lstatError) { + return callFailureCallback(callback, lstatError); + } + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + return callSuccessCallback(callback, lstat); + } + settings.fs.stat(path, (statError, stat) => { + if (statError) { + if (settings.throwErrorOnBrokenSymbolicLink) { + return callFailureCallback(callback, statError); + } + return callSuccessCallback(callback, lstat); + } + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + callSuccessCallback(callback, stat); + }); + }); +} +exports.read = read; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, result) { + callback(null, result); +} - // when the user specifies nothing, try to match both - prev.value = `(${capture}${escaped}|${prev.value})`; - state.output += prev.value; - continue; - } - /** - * Braces - */ +/***/ }), +/* 624 */ +/***/ (function(module, exports, __webpack_require__) { - if (value === '{' && opts.nobrace !== true) { - push({ type: 'brace', value, output: '(' }); - increment('braces'); - continue; - } +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +function read(path, settings) { + const lstat = settings.fs.lstatSync(path); + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + return lstat; + } + try { + const stat = settings.fs.statSync(path); + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + return stat; + } + catch (error) { + if (!settings.throwErrorOnBrokenSymbolicLink) { + return lstat; + } + throw error; + } +} +exports.read = read; - if (value === '}') { - if (opts.nobrace === true || state.braces === 0) { - push({ type: 'text', value, output: '\\' + value }); - continue; - } - let output = ')'; +/***/ }), +/* 625 */ +/***/ (function(module, exports, __webpack_require__) { - if (state.dots === true) { - let arr = tokens.slice(); - let range = []; +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const fs = __webpack_require__(626); +class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); + this.fs = fs.createFileSystemAdapter(this._options.fs); + this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + } + _getValue(option, value) { + return option === undefined ? value : option; + } +} +exports.default = Settings; - for (let i = arr.length - 1; i >= 0; i--) { - tokens.pop(); - if (arr[i].type === 'brace') { - break; - } - if (arr[i].type !== 'dots') { - range.unshift(arr[i].value); - } - } - output = expandRange(range, opts); - state.backtrack = true; - } +/***/ }), +/* 626 */ +/***/ (function(module, exports, __webpack_require__) { - push({ type: 'brace', value, output }); - decrement('braces'); - continue; - } +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const fs = __webpack_require__(349); +exports.FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + stat: fs.stat, + lstatSync: fs.lstatSync, + statSync: fs.statSync +}; +function createFileSystemAdapter(fsMethods) { + if (!fsMethods) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign({}, exports.FILE_SYSTEM_ADAPTER, fsMethods); +} +exports.createFileSystemAdapter = createFileSystemAdapter; - /** - * Pipes - */ - if (value === '|') { - if (extglobs.length > 0) { - extglobs[extglobs.length - 1].conditions++; - } - push({ type: 'text', value }); - continue; - } +/***/ }), +/* 627 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Commas - */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const async_1 = __webpack_require__(628); +const stream_1 = __webpack_require__(643); +const sync_1 = __webpack_require__(644); +const settings_1 = __webpack_require__(646); +exports.Settings = settings_1.default; +function walk(dir, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + return new async_1.default(dir, getSettings()).read(optionsOrSettingsOrCallback); + } + new async_1.default(dir, getSettings(optionsOrSettingsOrCallback)).read(callback); +} +exports.walk = walk; +function walkSync(dir, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new sync_1.default(dir, settings); + return provider.read(); +} +exports.walkSync = walkSync; +function walkStream(dir, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new stream_1.default(dir, settings); + return provider.read(); +} +exports.walkStream = walkStream; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1.default) { + return settingsOrOptions; + } + return new settings_1.default(settingsOrOptions); +} - if (value === ',') { - let output = value; - if (state.braces > 0 && stack[stack.length - 1] === 'braces') { - output = '|'; - } +/***/ }), +/* 628 */ +/***/ (function(module, exports, __webpack_require__) { - push({ type: 'comma', value, output }); - continue; - } +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const async_1 = __webpack_require__(629); +class AsyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1.default(this._root, this._settings); + this._storage = new Set(); + } + read(callback) { + this._reader.onError((error) => { + callFailureCallback(callback, error); + }); + this._reader.onEntry((entry) => { + this._storage.add(entry); + }); + this._reader.onEnd(() => { + callSuccessCallback(callback, Array.from(this._storage)); + }); + this._reader.read(); + } +} +exports.default = AsyncProvider; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, entries) { + callback(null, entries); +} - /** - * Slashes - */ - if (value === '/') { - // if the beginning of the glob is "./", advance the start - // to the current index, and don't add the "./" characters - // to the state. This greatly simplifies lookbehinds when - // checking for BOS characters like "!" and "." (not "./") - if (prev.type === 'dot' && state.index === 1) { - state.start = state.index + 1; - state.consumed = ''; - state.output = ''; - tokens.pop(); - prev = bos; // reset "prev" to the first token - continue; - } +/***/ }), +/* 629 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const events_1 = __webpack_require__(373); +const fsScandir = __webpack_require__(630); +const fastq = __webpack_require__(639); +const common = __webpack_require__(641); +const reader_1 = __webpack_require__(642); +class AsyncReader extends reader_1.default { + constructor(_root, _settings) { + super(_root, _settings); + this._settings = _settings; + this._scandir = fsScandir.scandir; + this._emitter = new events_1.EventEmitter(); + this._queue = fastq(this._worker.bind(this), this._settings.concurrency); + this._isFatalError = false; + this._isDestroyed = false; + this._queue.drain = () => { + if (!this._isFatalError) { + this._emitter.emit('end'); + } + }; + } + read() { + this._isFatalError = false; + this._isDestroyed = false; + setImmediate(() => { + this._pushToQueue(this._root, this._settings.basePath); + }); + return this._emitter; + } + destroy() { + if (this._isDestroyed) { + throw new Error('The reader is already destroyed'); + } + this._isDestroyed = true; + this._queue.killAndDrain(); + } + onEntry(callback) { + this._emitter.on('entry', callback); + } + onError(callback) { + this._emitter.once('error', callback); + } + onEnd(callback) { + this._emitter.once('end', callback); + } + _pushToQueue(dir, base) { + const queueItem = { dir, base }; + this._queue.push(queueItem, (error) => { + if (error) { + this._handleError(error); + } + }); + } + _worker(item, done) { + this._scandir(item.dir, this._settings.fsScandirSettings, (error, entries) => { + if (error) { + return done(error, undefined); + } + for (const entry of entries) { + this._handleEntry(entry, item.base); + } + done(null, undefined); + }); + } + _handleError(error) { + if (!common.isFatalError(this._settings, error)) { + return; + } + this._isFatalError = true; + this._isDestroyed = true; + this._emitter.emit('error', error); + } + _handleEntry(entry, base) { + if (this._isDestroyed || this._isFatalError) { + return; + } + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + if (common.isAppliedFilter(this._settings.entryFilter, entry)) { + this._emitEntry(entry); + } + if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, entry.path); + } + } + _emitEntry(entry) { + this._emitter.emit('entry', entry); + } +} +exports.default = AsyncReader; - push({ type: 'slash', value, output: SLASH_LITERAL }); - continue; - } - /** - * Dots - */ +/***/ }), +/* 630 */ +/***/ (function(module, exports, __webpack_require__) { - if (value === '.') { - if (state.braces > 0 && prev.type === 'dot') { - if (prev.value === '.') prev.output = DOT_LITERAL; - prev.type = 'dots'; - prev.output += value; - prev.value += value; - state.dots = true; - continue; - } +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const async = __webpack_require__(631); +const sync = __webpack_require__(636); +const settings_1 = __webpack_require__(637); +exports.Settings = settings_1.default; +function scandir(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + return async.read(path, getSettings(), optionsOrSettingsOrCallback); + } + async.read(path, getSettings(optionsOrSettingsOrCallback), callback); +} +exports.scandir = scandir; +function scandirSync(path, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return sync.read(path, settings); +} +exports.scandirSync = scandirSync; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1.default) { + return settingsOrOptions; + } + return new settings_1.default(settingsOrOptions); +} - push({ type: 'dot', value, output: DOT_LITERAL }); - continue; - } - /** - * Question marks - */ +/***/ }), +/* 631 */ +/***/ (function(module, exports, __webpack_require__) { - if (value === '?') { - if (prev && prev.type === 'paren') { - let next = peek(); - let output = value; +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const fsStat = __webpack_require__(622); +const rpl = __webpack_require__(632); +const constants_1 = __webpack_require__(633); +const utils = __webpack_require__(634); +function read(dir, settings, callback) { + if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + return readdirWithFileTypes(dir, settings, callback); + } + return readdir(dir, settings, callback); +} +exports.read = read; +function readdirWithFileTypes(dir, settings, callback) { + settings.fs.readdir(dir, { withFileTypes: true }, (readdirError, dirents) => { + if (readdirError) { + return callFailureCallback(callback, readdirError); + } + const entries = dirents.map((dirent) => ({ + dirent, + name: dirent.name, + path: `${dir}${settings.pathSegmentSeparator}${dirent.name}` + })); + if (!settings.followSymbolicLinks) { + return callSuccessCallback(callback, entries); + } + const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); + rpl(tasks, (rplError, rplEntries) => { + if (rplError) { + return callFailureCallback(callback, rplError); + } + callSuccessCallback(callback, rplEntries); + }); + }); +} +exports.readdirWithFileTypes = readdirWithFileTypes; +function makeRplTaskEntry(entry, settings) { + return (done) => { + if (!entry.dirent.isSymbolicLink()) { + return done(null, entry); + } + settings.fs.stat(entry.path, (statError, stats) => { + if (statError) { + if (settings.throwErrorOnBrokenSymbolicLink) { + return done(statError); + } + return done(null, entry); + } + entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); + return done(null, entry); + }); + }; +} +function readdir(dir, settings, callback) { + settings.fs.readdir(dir, (readdirError, names) => { + if (readdirError) { + return callFailureCallback(callback, readdirError); + } + const filepaths = names.map((name) => `${dir}${settings.pathSegmentSeparator}${name}`); + const tasks = filepaths.map((filepath) => { + return (done) => fsStat.stat(filepath, settings.fsStatSettings, done); + }); + rpl(tasks, (rplError, results) => { + if (rplError) { + return callFailureCallback(callback, rplError); + } + const entries = []; + for (let index = 0; index < names.length; index++) { + const name = names[index]; + const stats = results[index]; + const entry = { + name, + path: filepaths[index], + dirent: utils.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + entries.push(entry); + } + callSuccessCallback(callback, entries); + }); + }); +} +exports.readdir = readdir; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, result) { + callback(null, result); +} - if (next === '<' && !utils.supportsLookbehinds()) { - throw new Error('Node.js v10 or higher is required for regex lookbehinds'); - } - if (prev.value === '(' && !/[!=<:]/.test(next) || (next === '<' && !/[!=]/.test(peek(2)))) { - output = '\\' + value; - } +/***/ }), +/* 632 */ +/***/ (function(module, exports) { - push({ type: 'text', value, output }); - continue; - } +module.exports = runParallel - if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { - extglobOpen('qmark', value); - continue; - } +function runParallel (tasks, cb) { + var results, pending, keys + var isSync = true - if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { - push({ type: 'qmark', value, output: QMARK_NO_DOT }); - continue; - } + if (Array.isArray(tasks)) { + results = [] + pending = tasks.length + } else { + keys = Object.keys(tasks) + results = {} + pending = keys.length + } - push({ type: 'qmark', value, output: QMARK }); - continue; + function done (err) { + function end () { + if (cb) cb(err, results) + cb = null } + if (isSync) process.nextTick(end) + else end() + } - /** - * Exclamation - */ - - if (value === '!') { - if (opts.noextglob !== true && peek() === '(') { - if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { - extglobOpen('negate', value); - continue; - } - } - - if (opts.nonegate !== true && state.index === 0) { - negate(state); - continue; - } + function each (i, err, result) { + results[i] = result + if (--pending === 0 || err) { + done(err) } + } - /** - * Plus - */ - - if (value === '+') { - if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { - extglobOpen('plus', value); - continue; - } + if (!pending) { + // empty + done(null) + } else if (keys) { + // object + keys.forEach(function (key) { + tasks[key](function (err, result) { each(key, err, result) }) + }) + } else { + // array + tasks.forEach(function (task, i) { + task(function (err, result) { each(i, err, result) }) + }) + } - if (prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) { - let output = prev.extglob === true ? '\\' + value : value; - push({ type: 'plus', value, output }); - continue; - } + isSync = false +} - // use regex behavior inside parens - if (state.parens > 0 && opts.regex !== false) { - push({ type: 'plus', value }); - continue; - } - push({ type: 'plus', value: PLUS_LITERAL }); - continue; - } +/***/ }), +/* 633 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Plain text - */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); +const MAJOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); +const MINOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); +/** + * IS `true` for Node.js 10.10 and greater. + */ +exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = MAJOR_VERSION > 10 || (MAJOR_VERSION === 10 && MINOR_VERSION >= 10); - if (value === '@') { - if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { - push({ type: 'at', value, output: '' }); - continue; - } - push({ type: 'text', value }); - continue; - } +/***/ }), +/* 634 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Plain text - */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const fs = __webpack_require__(635); +exports.fs = fs; - if (value !== '*') { - if (value === '$' || value === '^') { - value = '\\' + value; - } - let match = REGEX_NON_SPECIAL_CHAR.exec(input.slice(state.index + 1)); - if (match) { - value += match[0]; - state.index += match[0].length; - } +/***/ }), +/* 635 */ +/***/ (function(module, exports, __webpack_require__) { - push({ type: 'text', value }); - continue; - } +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +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; - /** - * Stars - */ - if (prev && (prev.type === 'globstar' || prev.star === true)) { - prev.type = 'star'; - prev.star = true; - prev.value += value; - prev.output = star; - state.backtrack = true; - state.consumed += value; - continue; - } +/***/ }), +/* 636 */ +/***/ (function(module, exports, __webpack_require__) { - if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { - extglobOpen('star', value); - continue; - } +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const fsStat = __webpack_require__(622); +const constants_1 = __webpack_require__(633); +const utils = __webpack_require__(634); +function read(dir, settings) { + if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + return readdirWithFileTypes(dir, settings); + } + return readdir(dir, settings); +} +exports.read = read; +function readdirWithFileTypes(dir, settings) { + const dirents = settings.fs.readdirSync(dir, { withFileTypes: true }); + return dirents.map((dirent) => { + const entry = { + dirent, + name: dirent.name, + path: `${dir}${settings.pathSegmentSeparator}${dirent.name}` + }; + if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { + try { + const stats = settings.fs.statSync(entry.path); + entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); + } + catch (error) { + if (settings.throwErrorOnBrokenSymbolicLink) { + throw error; + } + } + } + return entry; + }); +} +exports.readdirWithFileTypes = readdirWithFileTypes; +function readdir(dir, settings) { + const names = settings.fs.readdirSync(dir); + return names.map((name) => { + const entryPath = `${dir}${settings.pathSegmentSeparator}${name}`; + const stats = fsStat.statSync(entryPath, settings.fsStatSettings); + const entry = { + name, + path: entryPath, + dirent: utils.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + return entry; + }); +} +exports.readdir = readdir; - if (prev.type === 'star') { - if (opts.noglobstar === true) { - state.consumed += value; - continue; - } - let prior = prev.prev; - let before = prior.prev; - let isStart = prior.type === 'slash' || prior.type === 'bos'; - let afterStar = before && (before.type === 'star' || before.type === 'globstar'); +/***/ }), +/* 637 */ +/***/ (function(module, exports, __webpack_require__) { - if (opts.bash === true && (!isStart || (!eos() && peek() !== '/'))) { - push({ type: 'star', value, output: '' }); - continue; - } +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const path = __webpack_require__(4); +const fsStat = __webpack_require__(622); +const fs = __webpack_require__(638); +class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); + this.fs = fs.createFileSystemAdapter(this._options.fs); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep); + this.stats = this._getValue(this._options.stats, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + this.fsStatSettings = new fsStat.Settings({ + followSymbolicLink: this.followSymbolicLinks, + fs: this.fs, + throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option === undefined ? value : option; + } +} +exports.default = Settings; - let isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); - let isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); - if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { - push({ type: 'star', value, output: '' }); - continue; - } - // strip consecutive `/**/` - while (input.slice(state.index + 1, state.index + 4) === '/**') { - let after = input[state.index + 4]; - if (after && after !== '/') { - break; - } - state.consumed += '/**'; - state.index += 3; - } +/***/ }), +/* 638 */ +/***/ (function(module, exports, __webpack_require__) { - if (prior.type === 'bos' && eos()) { - prev.type = 'globstar'; - prev.value += value; - prev.output = globstar(opts); - state.output = prev.output; - state.consumed += value; - continue; - } +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const fs = __webpack_require__(349); +exports.FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + stat: fs.stat, + lstatSync: fs.lstatSync, + statSync: fs.statSync, + readdir: fs.readdir, + readdirSync: fs.readdirSync +}; +function createFileSystemAdapter(fsMethods) { + if (!fsMethods) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign({}, exports.FILE_SYSTEM_ADAPTER, fsMethods); +} +exports.createFileSystemAdapter = createFileSystemAdapter; - if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { - state.output = state.output.slice(0, -(prior.output + prev.output).length); - prior.output = '(?:' + prior.output; - prev.type = 'globstar'; - prev.output = globstar(opts) + '|$)'; - prev.value += value; +/***/ }), +/* 639 */ +/***/ (function(module, exports, __webpack_require__) { - state.output += prior.output + prev.output; - state.consumed += value; - continue; - } +"use strict"; - let next = peek(); - if (prior.type === 'slash' && prior.prev.type !== 'bos' && next === '/') { - let end = peek(2) !== void 0 ? '|$' : ''; - state.output = state.output.slice(0, -(prior.output + prev.output).length); - prior.output = '(?:' + prior.output; +var reusify = __webpack_require__(640) - prev.type = 'globstar'; - prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; - prev.value += value; +function fastqueue (context, worker, concurrency) { + if (typeof context === 'function') { + concurrency = worker + worker = context + context = null + } - state.output += prior.output + prev.output; - state.consumed += value + advance(); + var cache = reusify(Task) + var queueHead = null + var queueTail = null + var _running = 0 - push({ type: 'slash', value, output: '' }); - continue; - } + var self = { + push: push, + drain: noop, + saturated: noop, + pause: pause, + paused: false, + concurrency: concurrency, + running: running, + resume: resume, + idle: idle, + length: length, + unshift: unshift, + empty: noop, + kill: kill, + killAndDrain: killAndDrain + } - if (prior.type === 'bos' && next === '/') { - prev.type = 'globstar'; - prev.value += value; - prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; - state.output = prev.output; - state.consumed += value + advance(); - push({ type: 'slash', value, output: '' }); - continue; - } + return self - // remove single star from output - state.output = state.output.slice(0, -prev.output.length); + function running () { + return _running + } - // reset previous token to globstar - prev.type = 'globstar'; - prev.output = globstar(opts); - prev.value += value; + function pause () { + self.paused = true + } - // reset output with globstar - state.output += prev.output; - state.consumed += value; - continue; + function length () { + var current = queueHead + var counter = 0 + + while (current) { + current = current.next + counter++ } - let token = { type: 'star', value, output: star }; + return counter + } - if (opts.bash === true) { - token.output = '.*?'; - if (prev.type === 'bos' || prev.type === 'slash') { - token.output = nodot + token.output; - } - push(token); - continue; + function resume () { + if (!self.paused) return + self.paused = false + for (var i = 0; i < self.concurrency; i++) { + _running++ + release() } + } - if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { - token.output = value; - push(token); - continue; - } + function idle () { + return _running === 0 && self.length() === 0 + } - if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { - if (prev.type === 'dot') { - state.output += NO_DOT_SLASH; - prev.output += NO_DOT_SLASH; + function push (value, done) { + var current = cache.get() - } else if (opts.dot === true) { - state.output += NO_DOTS_SLASH; - prev.output += NO_DOTS_SLASH; + current.context = context + current.release = release + current.value = value + current.callback = done || noop + if (_running === self.concurrency || self.paused) { + if (queueTail) { + queueTail.next = current + queueTail = current } else { - state.output += nodot; - prev.output += nodot; + queueHead = current + queueTail = current + self.saturated() } + } else { + _running++ + worker.call(context, current.value, current.worked) + } + } - if (peek() !== '*') { - state.output += ONE_CHAR; - prev.output += ONE_CHAR; + function unshift (value, done) { + var current = cache.get() + + current.context = context + current.release = release + current.value = value + current.callback = done || noop + + if (_running === self.concurrency || self.paused) { + if (queueHead) { + current.next = queueHead + queueHead = current + } else { + queueHead = current + queueTail = current + self.saturated() } + } else { + _running++ + worker.call(context, current.value, current.worked) } - - push(token); } - while (state.brackets > 0) { - if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); - state.output = utils.escapeLast(state.output, '['); - decrement('brackets'); + function release (holder) { + if (holder) { + cache.release(holder) + } + var next = queueHead + if (next) { + if (!self.paused) { + if (queueTail === queueHead) { + queueTail = null + } + queueHead = next.next + next.next = null + worker.call(context, next.value, next.worked) + if (queueTail === null) { + self.empty() + } + } else { + _running-- + } + } else if (--_running === 0) { + self.drain() + } } - while (state.parens > 0) { - if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); - state.output = utils.escapeLast(state.output, '('); - decrement('parens'); + function kill () { + queueHead = null + queueTail = null + self.drain = noop } - while (state.braces > 0) { - if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); - state.output = utils.escapeLast(state.output, '{'); - decrement('braces'); + function killAndDrain () { + queueHead = null + queueTail = null + self.drain() + self.drain = noop } +} - if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { - push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); - } +function noop () {} - // rebuild the output if we had to backtrack at any point - if (state.backtrack === true) { - state.output = ''; +function Task () { + this.value = null + this.callback = noop + this.next = null + this.release = noop + this.context = null - for (let token of state.tokens) { - state.output += token.output != null ? token.output : token.value; + var self = this - if (token.suffix) { - state.output += token.suffix; - } - } + this.worked = function worked (err, result) { + var callback = self.callback + self.value = null + self.callback = noop + callback.call(self.context, err, result) + self.release(self) } +} - return state; -}; +module.exports = fastqueue -/** - * Fast paths for creating regular expressions for common glob patterns. - * This can significantly speed up processing and has very little downside - * impact when none of the fast paths match. - */ -parse.fastpaths = (input, options) => { - let opts = { ...options }; - let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; - let len = input.length; - if (len > max) { - throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); - } +/***/ }), +/* 640 */ +/***/ (function(module, exports, __webpack_require__) { - input = REPLACEMENTS[input] || input; - let win32 = utils.isWindows(options); +"use strict"; - // create constants based on platform, for windows or posix - const { - DOT_LITERAL, - SLASH_LITERAL, - ONE_CHAR, - DOTS_SLASH, - NO_DOT, - NO_DOTS, - NO_DOTS_SLASH, - STAR, - START_ANCHOR - } = constants.globChars(win32); - let capture = opts.capture ? '' : '?:'; - let star = opts.bash === true ? '.*?' : STAR; - let nodot = opts.dot ? NO_DOTS : NO_DOT; - let slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; +function reusify (Constructor) { + var head = new Constructor() + var tail = head - if (opts.capture) { - star = `(${star})`; - } + function get () { + var current = head - const globstar = (opts) => { - return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; - }; + if (current.next) { + head = current.next + } else { + head = new Constructor() + tail = head + } - const create = str => { - switch (str) { - case '*': - return `${nodot}${ONE_CHAR}${star}`; + current.next = null - case '.*': - return `${DOT_LITERAL}${ONE_CHAR}${star}`; + return current + } - case '*.*': - return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + function release (obj) { + tail.next = obj + tail = obj + } - case '*/*': - return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; + return { + get: get, + release: release + } +} - case '**': - return nodot + globstar(opts); +module.exports = reusify - case '**/*': - return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; - case '**/*.*': - return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; +/***/ }), +/* 641 */ +/***/ (function(module, exports, __webpack_require__) { - case '**/.*': - return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +function isFatalError(settings, error) { + if (settings.errorFilter === null) { + return true; + } + return !settings.errorFilter(error); +} +exports.isFatalError = isFatalError; +function isAppliedFilter(filter, value) { + return filter === null || filter(value); +} +exports.isAppliedFilter = isAppliedFilter; +function replacePathSegmentSeparator(filepath, separator) { + return filepath.split(/[\\\/]/).join(separator); +} +exports.replacePathSegmentSeparator = replacePathSegmentSeparator; +function joinPathSegments(a, b, separator) { + if (a === '') { + return b; + } + return a + separator + b; +} +exports.joinPathSegments = joinPathSegments; - default: { - let match = /^(.*?)\.(\w+)$/.exec(str); - if (!match) return; - let source = create(match[1], options); - if (!source) return; +/***/ }), +/* 642 */ +/***/ (function(module, exports, __webpack_require__) { - return source + DOT_LITERAL + match[2]; - } - } - }; +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const common = __webpack_require__(641); +class Reader { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); + } +} +exports.default = Reader; - let output = create(input); - if (output && opts.strictSlashes !== true) { - output += `${SLASH_LITERAL}?`; - } - return output; -}; +/***/ }), +/* 643 */ +/***/ (function(module, exports, __webpack_require__) { -module.exports = parse; +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const stream_1 = __webpack_require__(382); +const async_1 = __webpack_require__(629); +class StreamProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1.default(this._root, this._settings); + this._stream = new stream_1.Readable({ + objectMode: true, + read: () => { }, + destroy: this._reader.destroy.bind(this._reader) + }); + } + read() { + this._reader.onError((error) => { + this._stream.emit('error', error); + }); + this._reader.onEntry((entry) => { + this._stream.push(entry); + }); + this._reader.onEnd(() => { + this._stream.push(null); + }); + this._reader.read(); + return this._stream; + } +} +exports.default = StreamProvider; /***/ }), -/* 624 */ +/* 644 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const merge2 = __webpack_require__(590); -function merge(streams) { - const mergedStream = merge2(streams); - streams.forEach((stream) => { - stream.once('error', (err) => mergedStream.emit('error', err)); - }); - return mergedStream; +const sync_1 = __webpack_require__(645); +class SyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new sync_1.default(this._root, this._settings); + } + read() { + return this._reader.read(); + } } -exports.merge = merge; +exports.default = SyncProvider; /***/ }), -/* 625 */ +/* 645 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const stream_1 = __webpack_require__(626); -const provider_1 = __webpack_require__(653); -class ProviderAsync extends provider_1.default { +const fsScandir = __webpack_require__(630); +const common = __webpack_require__(641); +const reader_1 = __webpack_require__(642); +class SyncReader extends reader_1.default { constructor() { super(...arguments); - this._reader = new stream_1.default(this._settings); + this._scandir = fsScandir.scandirSync; + this._storage = new Set(); + this._queue = new Set(); } - 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)); + read() { + this._pushToQueue(this._root, this._settings.basePath); + this._handleQueue(); + return Array.from(this._storage); + } + _pushToQueue(dir, base) { + this._queue.add({ dir, base }); + } + _handleQueue() { + for (const item of this._queue.values()) { + this._handleDirectory(item.dir, item.base); + } + } + _handleDirectory(dir, base) { + try { + const entries = this._scandir(dir, this._settings.fsScandirSettings); + for (const entry of entries) { + this._handleEntry(entry, base); + } + } + catch (error) { + this._handleError(error); + } + } + _handleError(error) { + if (!common.isFatalError(this._settings, error)) { + return; + } + throw error; + } + _handleEntry(entry, base) { + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + if (common.isAppliedFilter(this._settings.entryFilter, entry)) { + this._pushToStorage(entry); + } + if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, entry.path); + } + } + _pushToStorage(entry) { + this._storage.add(entry); + } +} +exports.default = SyncReader; + + +/***/ }), +/* 646 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const path = __webpack_require__(4); +const fsScandir = __webpack_require__(630); +class Settings { + constructor(_options = {}) { + this._options = _options; + this.basePath = this._getValue(this._options.basePath, undefined); + this.concurrency = this._getValue(this._options.concurrency, Infinity); + this.deepFilter = this._getValue(this._options.deepFilter, null); + this.entryFilter = this._getValue(this._options.entryFilter, null); + this.errorFilter = this._getValue(this._options.errorFilter, null); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep); + this.fsScandirSettings = new fsScandir.Settings({ + followSymbolicLinks: this._options.followSymbolicLinks, + fs: this._options.fs, + pathSegmentSeparator: this._options.pathSegmentSeparator, + stats: this._options.stats, + throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink }); } - api(root, task, options) { - if (task.dynamic) { - return this._reader.dynamic(root, options); - } - return this._reader.static(task.patterns, options); + _getValue(option, value) { + return option === undefined ? value : option; } } -exports.default = ProviderAsync; +exports.default = Settings; /***/ }), -/* 626 */ +/* 647 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const stream_1 = __webpack_require__(27); -const fsStat = __webpack_require__(627); -const fsWalk = __webpack_require__(632); -const reader_1 = __webpack_require__(652); -class ReaderStream extends reader_1.default { - constructor() { - super(...arguments); - this._walkStream = fsWalk.walkStream; - this._stat = fsStat.stat; +const path = __webpack_require__(4); +const fsStat = __webpack_require__(622); +const utils = __webpack_require__(593); +class Reader { + constructor(_settings) { + this._settings = _settings; + this._fsStatSettings = new fsStat.Settings({ + followSymbolicLink: this._settings.followSymbolicLinks, + fs: this._settings.fs, + throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks + }); } - dynamic(root, options) { - return this._walkStream(root, options); + _getFullEntryPath(filepath) { + return path.resolve(this._settings.cwd, filepath); } - 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); + _makeEntry(stats, pattern) { + const entry = { + name: pattern, + path: pattern, + dirent: utils.fs.createDirentFromStats(pattern, stats) }; - for (let i = 0; i < filepaths.length; i++) { - stream.write(i); + if (this._settings.stats) { + entry.stats = stats; } - 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; - }); + return entry; } - _getStat(filepath) { - return new Promise((resolve, reject) => { - this._stat(filepath, this._fsStatSettings, (error, stats) => { - error ? reject(error) : resolve(stats); - }); - }); + _isFatalError(error) { + return !utils.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; } } -exports.default = ReaderStream; +exports.default = Reader; /***/ }), -/* 627 */ +/* 648 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const async = __webpack_require__(628); -const sync = __webpack_require__(629); -const settings_1 = __webpack_require__(630); -exports.Settings = settings_1.default; -function stat(path, optionsOrSettingsOrCallback, callback) { - if (typeof optionsOrSettingsOrCallback === 'function') { - return async.read(path, getSettings(), optionsOrSettingsOrCallback); +const path = __webpack_require__(4); +const deep_1 = __webpack_require__(649); +const entry_1 = __webpack_require__(650); +const error_1 = __webpack_require__(651); +const entry_2 = __webpack_require__(652); +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); } - async.read(path, getSettings(optionsOrSettingsOrCallback), callback); -} -exports.stat = stat; -function statSync(path, optionsOrSettings) { - const settings = getSettings(optionsOrSettings); - return sync.read(path, settings); -} -exports.statSync = statSync; -function getSettings(settingsOrOptions = {}) { - if (settingsOrOptions instanceof settings_1.default) { - return settingsOrOptions; + _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 + }; } - return new settings_1.default(settingsOrOptions); } +exports.default = Provider; /***/ }), -/* 628 */ +/* 649 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -function read(path, settings, callback) { - settings.fs.lstat(path, (lstatError, lstat) => { - if (lstatError) { - return callFailureCallback(callback, lstatError); +const utils = __webpack_require__(593); +class DeepFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + } + getFilter(basePath, positive, negative) { + const maxPatternDepth = this._getMaxPatternDepth(positive); + const negativeRe = this._getNegativePatternsRe(negative); + return (entry) => this._filter(basePath, entry, negativeRe, maxPatternDepth); + } + _getMaxPatternDepth(patterns) { + const globstar = patterns.some(utils.pattern.hasGlobStar); + return globstar ? Infinity : utils.pattern.getMaxNaivePatternsDepth(patterns); + } + _getNegativePatternsRe(patterns) { + const affectDepthOfReadingPatterns = patterns.filter(utils.pattern.isAffectDepthOfReadingPattern); + return utils.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); + } + _filter(basePath, entry, negativeRe, maxPatternDepth) { + const depth = this._getEntryDepth(basePath, entry.path); + if (this._isSkippedByDeep(depth)) { + return false; } - if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { - return callSuccessCallback(callback, lstat); + if (this._isSkippedByMaxPatternDepth(depth, maxPatternDepth)) { + return false; } - settings.fs.stat(path, (statError, stat) => { - if (statError) { - if (settings.throwErrorOnBrokenSymbolicLink) { - return callFailureCallback(callback, statError); - } - return callSuccessCallback(callback, lstat); - } - if (settings.markSymbolicLink) { - stat.isSymbolicLink = () => true; - } - callSuccessCallback(callback, stat); - }); - }); -} -exports.read = read; -function callFailureCallback(callback, error) { - callback(error); -} -function callSuccessCallback(callback, result) { - callback(null, result); + if (this._isSkippedSymbolicLink(entry)) { + return false; + } + if (this._isSkippedDotDirectory(entry)) { + return false; + } + return this._isSkippedByNegativePatterns(entry, negativeRe); + } + _getEntryDepth(basePath, entryPath) { + const basePathDepth = basePath.split('/').length; + const entryPathDepth = entryPath.split('/').length; + return entryPathDepth - (basePath === '' ? 0 : basePathDepth); + } + _isSkippedByDeep(entryDepth) { + return entryDepth >= this._settings.deep; + } + _isSkippedByMaxPatternDepth(entryDepth, maxPatternDepth) { + return !this._settings.baseNameMatch && maxPatternDepth !== Infinity && entryDepth > maxPatternDepth; + } + _isSkippedSymbolicLink(entry) { + return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); + } + _isSkippedDotDirectory(entry) { + return !this._settings.dot && entry.name.startsWith('.'); + } + _isSkippedByNegativePatterns(entry, negativeRe) { + return !utils.pattern.matchAny(entry.path, negativeRe); + } } +exports.default = DeepFilter; /***/ }), -/* 629 */ +/* 650 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -function read(path, settings) { - const lstat = settings.fs.lstatSync(path); - if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { - return lstat; +const utils = __webpack_require__(593); +class EntryFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this.index = new Map(); } - try { - const stat = settings.fs.statSync(path); - if (settings.markSymbolicLink) { - stat.isSymbolicLink = () => true; + 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) { + if (this._isDuplicateEntry(entry)) { + return false; + } + this._createIndexRecord(entry); } - return stat; + if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { + return false; + } + if (this._isSkippedByAbsoluteNegativePatterns(entry, negativeRe)) { + return false; + } + const filepath = this._settings.baseNameMatch ? entry.name : entry.path; + return this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe); } - catch (error) { - if (!settings.throwErrorOnBrokenSymbolicLink) { - return lstat; + _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(entry, negativeRe) { + if (!this._settings.absolute) { + return false; } - throw error; + const fullpath = utils.path.makeAbsolute(this._settings.cwd, entry.path); + return this._isMatchToPatterns(fullpath, negativeRe); + } + _isMatchToPatterns(filepath, patternsRe) { + return utils.pattern.matchAny(filepath, patternsRe); } } -exports.read = read; +exports.default = EntryFilter; /***/ }), -/* 630 */ +/* 651 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const fs = __webpack_require__(631); -class Settings { - constructor(_options = {}) { - this._options = _options; - this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); - this.fs = fs.createFileSystemAdapter(this._options.fs); - this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); - this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); +const utils = __webpack_require__(593); +class ErrorFilter { + constructor(_settings) { + this._settings = _settings; } - _getValue(option, value) { - return option === undefined ? value : option; + getFilter() { + return (error) => this._isNonFatalError(error); + } + _isNonFatalError(error) { + return utils.errno.isEnoentCodeError(error) || this._settings.suppressErrors; } } -exports.default = Settings; +exports.default = ErrorFilter; /***/ }), -/* 631 */ +/* 652 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const fs = __webpack_require__(23); -exports.FILE_SYSTEM_ADAPTER = { - lstat: fs.lstat, - stat: fs.stat, - lstatSync: fs.lstatSync, - statSync: fs.statSync -}; -function createFileSystemAdapter(fsMethods) { - if (!fsMethods) { - return exports.FILE_SYSTEM_ADAPTER; +const utils = __webpack_require__(593); +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({}, entry, { path: filepath }); } - return Object.assign({}, exports.FILE_SYSTEM_ADAPTER, fsMethods); } -exports.createFileSystemAdapter = createFileSystemAdapter; +exports.default = EntryTransformer; /***/ }), -/* 632 */ +/* 653 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const async_1 = __webpack_require__(633); -const stream_1 = __webpack_require__(648); -const sync_1 = __webpack_require__(649); -const settings_1 = __webpack_require__(651); -exports.Settings = settings_1.default; -function walk(dir, optionsOrSettingsOrCallback, callback) { - if (typeof optionsOrSettingsOrCallback === 'function') { - return new async_1.default(dir, getSettings()).read(optionsOrSettingsOrCallback); +const stream_1 = __webpack_require__(382); +const stream_2 = __webpack_require__(621); +const provider_1 = __webpack_require__(648); +class ProviderStream extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new stream_2.default(this._settings); } - new async_1.default(dir, getSettings(optionsOrSettingsOrCallback)).read(callback); -} -exports.walk = walk; -function walkSync(dir, optionsOrSettings) { - const settings = getSettings(optionsOrSettings); - const provider = new sync_1.default(dir, settings); - return provider.read(); -} -exports.walkSync = walkSync; -function walkStream(dir, optionsOrSettings) { - const settings = getSettings(optionsOrSettings); - const provider = new stream_1.default(dir, settings); - return provider.read(); -} -exports.walkStream = walkStream; -function getSettings(settingsOrOptions = {}) { - if (settingsOrOptions instanceof settings_1.default) { - return settingsOrOptions; + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const source = this.api(root, task, options); + const dest = new stream_1.Readable({ objectMode: true, read: () => { } }); + source + .once('error', (error) => dest.emit('error', error)) + .on('data', (entry) => dest.emit('data', options.transform(entry))) + .once('end', () => dest.emit('end')); + return dest; + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); } - return new settings_1.default(settingsOrOptions); } +exports.default = ProviderStream; /***/ }), -/* 633 */ +/* 654 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const async_1 = __webpack_require__(634); -class AsyncProvider { - constructor(_root, _settings) { - this._root = _root; - this._settings = _settings; - this._reader = new async_1.default(this._root, this._settings); - this._storage = new Set(); +const sync_1 = __webpack_require__(655); +const provider_1 = __webpack_require__(648); +class ProviderSync extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new sync_1.default(this._settings); } - read(callback) { - this._reader.onError((error) => { - callFailureCallback(callback, error); - }); - this._reader.onEntry((entry) => { - this._storage.add(entry); - }); - this._reader.onEnd(() => { - callSuccessCallback(callback, Array.from(this._storage)); - }); - this._reader.read(); + 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 = AsyncProvider; -function callFailureCallback(callback, error) { - callback(error); -} -function callSuccessCallback(callback, entries) { - callback(null, entries); -} +exports.default = ProviderSync; /***/ }), -/* 634 */ +/* 655 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const events_1 = __webpack_require__(399); -const fsScandir = __webpack_require__(635); -const fastq = __webpack_require__(644); -const common = __webpack_require__(646); +const fsStat = __webpack_require__(622); +const fsWalk = __webpack_require__(627); const reader_1 = __webpack_require__(647); -class AsyncReader extends reader_1.default { - constructor(_root, _settings) { - super(_root, _settings); - this._settings = _settings; - this._scandir = fsScandir.scandir; - this._emitter = new events_1.EventEmitter(); - this._queue = fastq(this._worker.bind(this), this._settings.concurrency); - this._isFatalError = false; - this._isDestroyed = false; - this._queue.drain = () => { - if (!this._isFatalError) { - this._emitter.emit('end'); - } - }; - } - read() { - this._isFatalError = false; - this._isDestroyed = false; - setImmediate(() => { - this._pushToQueue(this._root, this._settings.basePath); - }); - return this._emitter; - } - destroy() { - if (this._isDestroyed) { - throw new Error('The reader is already destroyed'); - } - this._isDestroyed = true; - this._queue.killAndDrain(); - } - onEntry(callback) { - this._emitter.on('entry', callback); - } - onError(callback) { - this._emitter.once('error', callback); - } - onEnd(callback) { - this._emitter.once('end', callback); +class ReaderSync extends reader_1.default { + constructor() { + super(...arguments); + this._walkSync = fsWalk.walkSync; + this._statSync = fsStat.statSync; } - _pushToQueue(dir, base) { - const queueItem = { dir, base }; - this._queue.push(queueItem, (error) => { - if (error) { - this._handleError(error); - } - }); + dynamic(root, options) { + return this._walkSync(root, options); } - _worker(item, done) { - this._scandir(item.dir, this._settings.fsScandirSettings, (error, entries) => { - if (error) { - return done(error, undefined); - } - for (const entry of entries) { - this._handleEntry(entry, item.base); + 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; } - done(null, undefined); - }); - } - _handleError(error) { - if (!common.isFatalError(this._settings, error)) { - return; - } - this._isFatalError = true; - this._isDestroyed = true; - this._emitter.emit('error', error); - } - _handleEntry(entry, base) { - if (this._isDestroyed || this._isFatalError) { - return; - } - const fullpath = entry.path; - if (base !== undefined) { - entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + entries.push(entry); } - if (common.isAppliedFilter(this._settings.entryFilter, entry)) { - this._emitEntry(entry); + return entries; + } + _getEntry(filepath, pattern, options) { + try { + const stats = this._getStat(filepath); + return this._makeEntry(stats, pattern); } - if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { - this._pushToQueue(fullpath, entry.path); + catch (error) { + if (options.errorFilter(error)) { + return null; + } + throw error; } } - _emitEntry(entry) { - this._emitter.emit('entry', entry); + _getStat(filepath) { + return this._statSync(filepath, this._fsStatSettings); } } -exports.default = AsyncReader; +exports.default = ReaderSync; /***/ }), -/* 635 */ +/* 656 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const async = __webpack_require__(636); -const sync = __webpack_require__(641); -const settings_1 = __webpack_require__(642); -exports.Settings = settings_1.default; -function scandir(path, optionsOrSettingsOrCallback, callback) { - if (typeof optionsOrSettingsOrCallback === 'function') { - return async.read(path, getSettings(), optionsOrSettingsOrCallback); +const fs = __webpack_require__(349); +const os = __webpack_require__(364); +const CPU_COUNT = os.cpus().length; +exports.DEFAULT_FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + lstatSync: fs.lstatSync, + stat: fs.stat, + statSync: fs.statSync, + readdir: fs.readdir, + readdirSync: fs.readdirSync +}; +// tslint:enable no-redundant-jsdoc +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; + } } - async.read(path, getSettings(optionsOrSettingsOrCallback), callback); -} -exports.scandir = scandir; -function scandirSync(path, optionsOrSettings) { - const settings = getSettings(optionsOrSettings); - return sync.read(path, settings); -} -exports.scandirSync = scandirSync; -function getSettings(settingsOrOptions = {}) { - if (settingsOrOptions instanceof settings_1.default) { - return settingsOrOptions; + _getValue(option, value) { + return option === undefined ? value : option; + } + _getFileSystemMethods(methods = {}) { + return Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER, methods); } - return new settings_1.default(settingsOrOptions); } +exports.default = Settings; /***/ }), -/* 636 */ +/* 657 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const fsStat = __webpack_require__(627); -const rpl = __webpack_require__(637); -const constants_1 = __webpack_require__(638); -const utils = __webpack_require__(639); -function read(dir, settings, callback) { - if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { - return readdirWithFileTypes(dir, settings, callback); - } - return readdir(dir, settings, callback); -} -exports.read = read; -function readdirWithFileTypes(dir, settings, callback) { - settings.fs.readdir(dir, { withFileTypes: true }, (readdirError, dirents) => { - if (readdirError) { - return callFailureCallback(callback, readdirError); - } - const entries = dirents.map((dirent) => ({ - dirent, - name: dirent.name, - path: `${dir}${settings.pathSegmentSeparator}${dirent.name}` - })); - if (!settings.followSymbolicLinks) { - return callSuccessCallback(callback, entries); - } - const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); - rpl(tasks, (rplError, rplEntries) => { - if (rplError) { - return callFailureCallback(callback, rplError); - } - callSuccessCallback(callback, rplEntries); - }); - }); -} -exports.readdirWithFileTypes = readdirWithFileTypes; -function makeRplTaskEntry(entry, settings) { - return (done) => { - if (!entry.dirent.isSymbolicLink()) { - return done(null, entry); - } - settings.fs.stat(entry.path, (statError, stats) => { - if (statError) { - if (settings.throwErrorOnBrokenSymbolicLink) { - return done(statError); - } - return done(null, entry); - } - entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); - return done(null, entry); - }); - }; -} -function readdir(dir, settings, callback) { - settings.fs.readdir(dir, (readdirError, names) => { - if (readdirError) { - return callFailureCallback(callback, readdirError); - } - const filepaths = names.map((name) => `${dir}${settings.pathSegmentSeparator}${name}`); - const tasks = filepaths.map((filepath) => { - return (done) => fsStat.stat(filepath, settings.fsStatSettings, done); - }); - rpl(tasks, (rplError, results) => { - if (rplError) { - return callFailureCallback(callback, rplError); - } - const entries = []; - for (let index = 0; index < names.length; index++) { - const name = names[index]; - const stats = results[index]; - const entry = { - name, - path: filepaths[index], - dirent: utils.fs.createDirentFromStats(name, stats) - }; - if (settings.stats) { - entry.stats = stats; - } - entries.push(entry); - } - callSuccessCallback(callback, entries); - }); - }); -} -exports.readdir = readdir; -function callFailureCallback(callback, error) { - callback(error); -} -function callSuccessCallback(callback, result) { - callback(null, result); -} +const path = __webpack_require__(4); +const pathType = __webpack_require__(658); -/***/ }), -/* 637 */ -/***/ (function(module, exports) { +const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0]; -module.exports = runParallel +const getPath = (filepath, cwd) => { + const pth = filepath[0] === '!' ? filepath.slice(1) : filepath; + return path.isAbsolute(pth) ? pth : path.join(cwd, pth); +}; -function runParallel (tasks, cb) { - var results, pending, keys - var isSync = true +const addExtensions = (file, extensions) => { + if (path.extname(file)) { + return `**/${file}`; + } - if (Array.isArray(tasks)) { - results = [] - pending = tasks.length - } else { - keys = Object.keys(tasks) - results = {} - pending = keys.length - } + return `**/${file}.${getExtensions(extensions)}`; +}; - function done (err) { - function end () { - if (cb) cb(err, results) - cb = null - } - if (isSync) process.nextTick(end) - else end() - } +const getGlob = (directory, options) => { + if (options.files && !Array.isArray(options.files)) { + throw new TypeError(`Expected \`files\` to be of type \`Array\` but received type \`${typeof options.files}\``); + } - function each (i, err, result) { - results[i] = result - if (--pending === 0 || err) { - done(err) - } - } + if (options.extensions && !Array.isArray(options.extensions)) { + throw new TypeError(`Expected \`extensions\` to be of type \`Array\` but received type \`${typeof options.extensions}\``); + } - if (!pending) { - // empty - done(null) - } else if (keys) { - // object - keys.forEach(function (key) { - tasks[key](function (err, result) { each(key, err, result) }) - }) - } else { - // array - tasks.forEach(function (task, i) { - task(function (err, result) { each(i, err, result) }) - }) - } + if (options.files && options.extensions) { + return options.files.map(x => path.posix.join(directory, addExtensions(x, options.extensions))); + } - isSync = false -} + if (options.files) { + return options.files.map(x => path.posix.join(directory, `**/${x}`)); + } + if (options.extensions) { + return [path.posix.join(directory, `**/*.${getExtensions(options.extensions)}`)]; + } -/***/ }), -/* 638 */ -/***/ (function(module, exports, __webpack_require__) { + return [path.posix.join(directory, '**')]; +}; -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); -const MAJOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); -const MINOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); -/** - * IS `true` for Node.js 10.10 and greater. - */ -exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = MAJOR_VERSION > 10 || (MAJOR_VERSION === 10 && MINOR_VERSION >= 10); +module.exports = async (input, options) => { + options = { + cwd: process.cwd(), + ...options + }; + if (typeof options.cwd !== 'string') { + throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``); + } -/***/ }), -/* 639 */ -/***/ (function(module, exports, __webpack_require__) { + const globs = await Promise.all([].concat(input).map(async x => { + const isDirectory = await pathType.isDirectory(getPath(x, options.cwd)); + return isDirectory ? getGlob(x, options) : x; + })); -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const fs = __webpack_require__(640); -exports.fs = fs; + return [].concat.apply([], globs); // eslint-disable-line prefer-spread +}; + +module.exports.sync = (input, options) => { + options = { + cwd: process.cwd(), + ...options + }; + + if (typeof options.cwd !== 'string') { + throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``); + } + + const globs = [].concat(input).map(x => pathType.isDirectorySync(getPath(x, options.cwd)) ? getGlob(x, options) : x); + + return [].concat.apply([], globs); // eslint-disable-line prefer-spread +}; /***/ }), -/* 640 */ +/* 658 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -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; + +const {promisify} = __webpack_require__(397); +const fs = __webpack_require__(349); + +async function isType(fsStatType, statsMethodName, filePath) { + if (typeof filePath !== 'string') { + throw new TypeError(`Expected a string, got ${typeof filePath}`); + } + + try { + const stats = await promisify(fs[fsStatType])(filePath); + return stats[statsMethodName](); + } catch (error) { + if (error.code === 'ENOENT') { + return false; + } + + throw error; + } +} + +function isTypeSync(fsStatType, statsMethodName, filePath) { + if (typeof filePath !== 'string') { + throw new TypeError(`Expected a string, got ${typeof filePath}`); + } + + try { + return fs[fsStatType](filePath)[statsMethodName](); + } catch (error) { + if (error.code === 'ENOENT') { + return false; + } + + throw error; + } +} + +exports.isFile = isType.bind(null, 'stat', 'isFile'); +exports.isDirectory = isType.bind(null, 'stat', 'isDirectory'); +exports.isSymlink = isType.bind(null, 'lstat', 'isSymbolicLink'); +exports.isFileSync = isTypeSync.bind(null, 'statSync', 'isFile'); +exports.isDirectorySync = isTypeSync.bind(null, 'statSync', 'isDirectory'); +exports.isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink'); /***/ }), -/* 641 */ +/* 659 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const fsStat = __webpack_require__(627); -const constants_1 = __webpack_require__(638); -const utils = __webpack_require__(639); -function read(dir, settings) { - if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { - return readdirWithFileTypes(dir, settings); - } - return readdir(dir, settings); -} -exports.read = read; -function readdirWithFileTypes(dir, settings) { - const dirents = settings.fs.readdirSync(dir, { withFileTypes: true }); - return dirents.map((dirent) => { - const entry = { - dirent, - name: dirent.name, - path: `${dir}${settings.pathSegmentSeparator}${dirent.name}` - }; - if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { - try { - const stats = settings.fs.statSync(entry.path); - entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); - } - catch (error) { - if (settings.throwErrorOnBrokenSymbolicLink) { - throw error; - } - } - } - return entry; - }); -} -exports.readdirWithFileTypes = readdirWithFileTypes; -function readdir(dir, settings) { - const names = settings.fs.readdirSync(dir); - return names.map((name) => { - const entryPath = `${dir}${settings.pathSegmentSeparator}${name}`; - const stats = fsStat.statSync(entryPath, settings.fsStatSettings); - const entry = { - name, - path: entryPath, - dirent: utils.fs.createDirentFromStats(name, stats) - }; - if (settings.stats) { - entry.stats = stats; - } - return entry; - }); -} -exports.readdir = readdir; + +const {promisify} = __webpack_require__(397); +const fs = __webpack_require__(349); +const path = __webpack_require__(4); +const fastGlob = __webpack_require__(591); +const gitIgnore = __webpack_require__(660); +const slash = __webpack_require__(661); + +const DEFAULT_IGNORE = [ + '**/node_modules/**', + '**/flow-typed/**', + '**/coverage/**', + '**/.git' +]; + +const readFileP = promisify(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.startsWith('#')) + .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 ensureAbsolutePathForCwd = (cwd, p) => { + if (path.isAbsolute(p)) { + if (p.startsWith(cwd)) { + return p; + } + + throw new Error(`Path ${p} is not in cwd ${cwd}`); + } + + return path.join(cwd, p); +}; + +const getIsIgnoredPredecate = (ignores, cwd) => { + return p => ignores.ignores(slash(path.relative(cwd, ensureAbsolutePathForCwd(cwd, p)))); +}; + +const getFile = async (file, cwd) => { + const filePath = path.join(cwd, file); + const content = await readFileP(filePath, 'utf8'); + + return { + cwd, + filePath, + content + }; +}; + +const getFileSync = (file, cwd) => { + const filePath = path.join(cwd, file); + const content = fs.readFileSync(filePath, 'utf8'); + + return { + cwd, + filePath, + content + }; +}; + +const normalizeOptions = ({ + ignore = [], + cwd = process.cwd() +} = {}) => { + return {ignore, cwd}; +}; + +module.exports = async options => { + options = normalizeOptions(options); + + const paths = await fastGlob('**/.gitignore', { + ignore: DEFAULT_IGNORE.concat(options.ignore), + cwd: options.cwd + }); + + const files = await Promise.all(paths.map(file => getFile(file, options.cwd))); + const ignores = reduceIgnore(files); + + return getIsIgnoredPredecate(ignores, options.cwd); +}; + +module.exports.sync = options => { + options = normalizeOptions(options); + + 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); +}; /***/ }), -/* 642 */ -/***/ (function(module, exports, __webpack_require__) { +/* 660 */ +/***/ (function(module, exports) { -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const path = __webpack_require__(16); -const fsStat = __webpack_require__(627); -const fs = __webpack_require__(643); -class Settings { - constructor(_options = {}) { - this._options = _options; - this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); - this.fs = fs.createFileSystemAdapter(this._options.fs); - this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep); - this.stats = this._getValue(this._options.stats, false); - this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); - this.fsStatSettings = new fsStat.Settings({ - followSymbolicLink: this.followSymbolicLinks, - fs: this.fs, - throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink - }); - } - _getValue(option, value) { - return option === undefined ? value : option; - } -} -exports.default = Settings; +// A simple implementation of make-array +function makeArray (subject) { + return Array.isArray(subject) + ? subject + : [subject] +} +const REGEX_TEST_BLANK_LINE = /^\s+$/ +const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/ +const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/ +const REGEX_SPLITALL_CRLF = /\r?\n/g +// /foo, +// ./foo, +// ../foo, +// . +// .. +const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/ -/***/ }), -/* 643 */ -/***/ (function(module, exports, __webpack_require__) { +const SLASH = '/' +const KEY_IGNORE = typeof Symbol !== 'undefined' + ? Symbol.for('node-ignore') + /* istanbul ignore next */ + : 'node-ignore' -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const fs = __webpack_require__(23); -exports.FILE_SYSTEM_ADAPTER = { - lstat: fs.lstat, - stat: fs.stat, - lstatSync: fs.lstatSync, - statSync: fs.statSync, - readdir: fs.readdir, - readdirSync: fs.readdirSync -}; -function createFileSystemAdapter(fsMethods) { - if (!fsMethods) { - return exports.FILE_SYSTEM_ADAPTER; - } - return Object.assign({}, exports.FILE_SYSTEM_ADAPTER, fsMethods); -} -exports.createFileSystemAdapter = createFileSystemAdapter; +const define = (object, key, value) => + Object.defineProperty(object, key, {value}) +const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g -/***/ }), -/* 644 */ -/***/ (function(module, exports, __webpack_require__) { +// 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. + : '' +) -"use strict"; +// > 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` +// '`foo/`' should not continue with the '`..`' +const DEFAULT_REPLACER_PREFIX = [ -var reusify = __webpack_require__(645) + // > Trailing spaces are ignored unless they are quoted with backslash ("\") + [ + // (a\ ) -> (a ) + // (a ) -> (a) + // (a \ ) -> (a ) + /\\?\s+$/, + match => match.indexOf('\\') === 0 + ? ' ' + : '' + ], -function fastqueue (context, worker, concurrency) { - if (typeof context === 'function') { - concurrency = worker - worker = context - context = null - } + // replace (\ ) with ' ' + [ + /\\\s/g, + () => ' ' + ], - var cache = reusify(Task) - var queueHead = null - var queueTail = null - var _running = 0 + // Escape metacharacters + // which is written down by users but means special for regular expressions. - var self = { - push: push, - drain: noop, - saturated: noop, - pause: pause, - paused: false, - concurrency: concurrency, - running: running, - resume: resume, - idle: idle, - length: length, - unshift: unshift, - empty: noop, - kill: kill, - killAndDrain: killAndDrain - } + // > 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}` + ], - return self + [ + // > [abc] matches any character inside the brackets + // > (in this case a, b, or c); + /\[([^\]/]*)($|\])/g, + (match, p1, p2) => p2 === ']' + ? `[${sanitizeRange(p1)}]` + : `\\${match}` + ], - function running () { - return _running - } + [ + // > a question mark (?) matches a single character + /(?!\\)\?/g, + () => '[^/]' + ], - function pause () { - self.paused = true - } + // leading slash + [ - function length () { - var current = queueHead - var counter = 0 + // > 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 + /^\//, + () => '^' + ], - while (current) { - current = current.next - counter++ - } + // replace special metacharacter slash after the leading slash + [ + /\//g, + () => '\\/' + ], - return counter - } + [ + // > 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 '\\*' + /^\^*\\\*\\\*\\\//, - function resume () { - if (!self.paused) return - self.paused = false - for (var i = 0; i < self.concurrency; i++) { - _running++ - release() + // '**/foo' <-> 'foo' + () => '^(?:.*\\/)?' + ] +] + +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 + ? '(?:^|\\/)' + + // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^' } - } + ], - function idle () { - return _running === 0 && self.length() === 0 - } + // two globstars + [ + // Use lookahead assertions so that we could match more than one `'/**'` + /\\\/\\\*\\\*(?=\\\/|$)/g, - function push (value, done) { - var current = cache.get() + // Zero, one or several directories + // should not use '*', or it will be replaced by the next replacer - current.context = context - current.release = release - current.value = value - current.callback = done || noop + // Check if it is not the last `'/**'` + (_, index, str) => index + 6 < str.length - if (_running === self.concurrency || self.paused) { - if (queueTail) { - queueTail.next = current - queueTail = current - } else { - queueHead = current - queueTail = current - self.saturated() - } - } else { - _running++ - worker.call(context, current.value, current.worked) - } - } + // 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. + // '/**/' + ? '(?:\\/[^\\/]+)*' - function unshift (value, done) { - var current = cache.get() + // case: /** + // > A trailing `"/**"` matches everything inside. - current.context = context - current.release = release - current.value = value - current.callback = done || noop + // #21: everything inside but it should not include the current folder + : '\\/.+' + ], - if (_running === self.concurrency || self.paused) { - if (queueHead) { - current.next = queueHead - queueHead = current - } else { - queueHead = current - queueTail = current - self.saturated() - } - } else { - _running++ - worker.call(context, current.value, current.worked) - } - } + // intermediate wildcards + [ + // Never replace escaped '*' + // ignore rule '\*' will match the path '*' - function release (holder) { - if (holder) { - cache.release(holder) - } - var next = queueHead - if (next) { - if (!self.paused) { - if (queueTail === queueHead) { - queueTail = null - } - queueHead = next.next - next.next = null - worker.call(context, next.value, next.worked) - if (queueTail === null) { - self.empty() - } - } else { - _running-- - } - } else if (--_running === 0) { - self.drain() - } - } + // 'abc.*/' -> go + // 'abc.*' -> skip this rule + /(^|[^\\]+)\\\*(?=.+)/g, - function kill () { - queueHead = null - queueTail = null - self.drain = noop - } + // '*.js' matches '.js' + // '*.js' doesn't match 'abc' + (_, p1) => `${p1}[^\\/]*` + ], - function killAndDrain () { - queueHead = null - queueTail = null - self.drain() - self.drain = noop - } -} + // trailing wildcard + [ + /(\^|\\\/)?\\\*$/, + (_, p1) => { + const prefix = p1 + // '\^': + // '/*' does not match '' + // '/*' does not match everything -function noop () {} + // '\\\/': + // 'abc/*' does not match 'abc/' + ? `${p1}[^/]+` -function Task () { - this.value = null - this.callback = noop - this.next = null - this.release = noop - this.context = null + // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*' - var self = this + return `${prefix}(?=$|\\/$)` + } + ], - this.worked = function worked (err, result) { - var callback = self.callback - self.value = null - self.callback = noop - callback.call(self.context, err, result) - self.release(self) - } -} + [ + // unescape + /\\\\\\/g, + () => '\\' + ] +] -module.exports = fastqueue +const POSITIVE_REPLACERS = [ + ...DEFAULT_REPLACER_PREFIX, + // 'f' + // matches + // - /f(end) + // - /f/ + // - (start)f(end) + // - (start)f/ + // doesn't match + // - oof + // - foo + // pseudo: + // -> (^|/)f(/|$) -/***/ }), -/* 645 */ -/***/ (function(module, exports, __webpack_require__) { + // ending + [ + // 'js' will not match 'js.' + // 'ab' will not match 'abc' + /(?:[^*/])$/, -"use strict"; + // 'js*' will not match 'a.js' + // 'js/' will not match 'a.js' + // 'js' will match 'a.js' and 'a.js/' + match => `${match}(?=$|\\/)` + ], + ...DEFAULT_REPLACER_SUFFIX +] -function reusify (Constructor) { - var head = new Constructor() - var tail = head +const NEGATIVE_REPLACERS = [ + ...DEFAULT_REPLACER_PREFIX, - function get () { - var current = head + // #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 (current.next) { - head = current.next - } else { - head = new Constructor() - tail = head - } + // eg: + // ['node_modules/*', '!node_modules'] + // should ignore `node_modules/a.js` + [ + /(?:[^*])$/, + match => `${match}(?=$|\\/$)` + ], - current.next = null + ...DEFAULT_REPLACER_SUFFIX +] - return current - } +// A simple cache, because an ignore rule only has only one certain meaning +const regexCache = Object.create(null) - function release (obj) { - tail.next = obj - tail = obj +// @param {pattern} +const makeRegex = (pattern, negative, ignorecase) => { + const r = regexCache[pattern] + if (r) { + return r } - return { - get: get, - release: release + const replacers = negative + ? NEGATIVE_REPLACERS + : POSITIVE_REPLACERS + + const source = replacers.reduce( + (prev, current) => prev.replace(current[0], current[1].bind(pattern)), + pattern + ) + + return regexCache[pattern] = ignorecase + ? new RegExp(source, 'i') + : new RegExp(source) +} + +const isString = subject => typeof subject === 'string' + +// > A blank line matches no files, so it can serve as a separator for readability. +const checkPattern = pattern => pattern + && isString(pattern) + && !REGEX_TEST_BLANK_LINE.test(pattern) + + // > A line starting with # serves as a comment. + && pattern.indexOf('#') !== 0 + +const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF) + +class IgnoreRule { + constructor ( + origin, + pattern, + negative, + regex + ) { + this.origin = origin + this.pattern = pattern + this.negative = negative + this.regex = regex } } -module.exports = reusify +const createRule = (pattern, ignorecase) => { + const origin = pattern + let negative = false + + // > An optional prefix "!" which negates the pattern; + if (pattern.indexOf('!') === 0) { + negative = true + pattern = pattern.substr(1) + } + + pattern = pattern + // > Put a backslash ("\") in front of the first "!" for patterns that + // > begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') + // > Put a backslash ("\") in front of the first hash for patterns that + // > begin with a hash. + .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#') + const regex = makeRegex(pattern, negative, ignorecase) -/***/ }), -/* 646 */ -/***/ (function(module, exports, __webpack_require__) { + return new IgnoreRule( + origin, + pattern, + negative, + regex + ) +} -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -function isFatalError(settings, error) { - if (settings.errorFilter === null) { - return true; - } - return !settings.errorFilter(error); -} -exports.isFatalError = isFatalError; -function isAppliedFilter(filter, value) { - return filter === null || filter(value); -} -exports.isAppliedFilter = isAppliedFilter; -function replacePathSegmentSeparator(filepath, separator) { - return filepath.split(/[\\\/]/).join(separator); -} -exports.replacePathSegmentSeparator = replacePathSegmentSeparator; -function joinPathSegments(a, b, separator) { - if (a === '') { - return b; - } - return a + separator + b; -} -exports.joinPathSegments = joinPathSegments; +const throwError = (message, Ctor) => { + throw new Ctor(message) +} +const checkPath = (path, originalPath, doThrow) => { + if (!isString(path)) { + return doThrow( + `path must be a string, but got \`${originalPath}\``, + TypeError + ) + } -/***/ }), -/* 647 */ -/***/ (function(module, exports, __webpack_require__) { + // We don't know if we should ignore '', so throw + if (!path) { + return doThrow(`path must not be empty`, TypeError) + } -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const common = __webpack_require__(646); -class Reader { - constructor(_root, _settings) { - this._root = _root; - this._settings = _settings; - this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); - } -} -exports.default = Reader; + // Check if it is a relative path + if (checkPath.isNotRelative(path)) { + const r = '`path.relative()`d' + return doThrow( + `path should be a ${r} string, but got "${originalPath}"`, + RangeError + ) + } + return true +} -/***/ }), -/* 648 */ -/***/ (function(module, exports, __webpack_require__) { +const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path) -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const stream_1 = __webpack_require__(27); -const async_1 = __webpack_require__(634); -class StreamProvider { - constructor(_root, _settings) { - this._root = _root; - this._settings = _settings; - this._reader = new async_1.default(this._root, this._settings); - this._stream = new stream_1.Readable({ - objectMode: true, - read: () => { }, - destroy: this._reader.destroy.bind(this._reader) - }); - } - read() { - this._reader.onError((error) => { - this._stream.emit('error', error); - }); - this._reader.onEntry((entry) => { - this._stream.push(entry); - }); - this._reader.onEnd(() => { - this._stream.push(null); - }); - this._reader.read(); - return this._stream; - } -} -exports.default = StreamProvider; +checkPath.isNotRelative = isNotRelative +checkPath.convert = p => p +class Ignore { + constructor ({ + ignorecase = true + } = {}) { + this._rules = [] + this._ignorecase = ignorecase + define(this, KEY_IGNORE, true) + this._initCache() + } -/***/ }), -/* 649 */ -/***/ (function(module, exports, __webpack_require__) { + _initCache () { + this._ignoreCache = Object.create(null) + this._testCache = Object.create(null) + } -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const sync_1 = __webpack_require__(650); -class SyncProvider { - constructor(_root, _settings) { - this._root = _root; - this._settings = _settings; - this._reader = new sync_1.default(this._root, this._settings); - } - read() { - return this._reader.read(); - } -} -exports.default = SyncProvider; + _addPattern (pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules) + this._added = true + return + } + if (checkPattern(pattern)) { + const rule = createRule(pattern, this._ignorecase) + this._added = true + this._rules.push(rule) + } + } -/***/ }), -/* 650 */ -/***/ (function(module, exports, __webpack_require__) { + // @param {Array | string | Ignore} pattern + add (pattern) { + this._added = false -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const fsScandir = __webpack_require__(635); -const common = __webpack_require__(646); -const reader_1 = __webpack_require__(647); -class SyncReader extends reader_1.default { - constructor() { - super(...arguments); - this._scandir = fsScandir.scandirSync; - this._storage = new Set(); - this._queue = new Set(); - } - read() { - this._pushToQueue(this._root, this._settings.basePath); - this._handleQueue(); - return Array.from(this._storage); - } - _pushToQueue(dir, base) { - this._queue.add({ dir, base }); - } - _handleQueue() { - for (const item of this._queue.values()) { - this._handleDirectory(item.dir, item.base); - } - } - _handleDirectory(dir, base) { - try { - const entries = this._scandir(dir, this._settings.fsScandirSettings); - for (const entry of entries) { - this._handleEntry(entry, base); - } - } - catch (error) { - this._handleError(error); - } - } - _handleError(error) { - if (!common.isFatalError(this._settings, error)) { - return; - } - throw error; - } - _handleEntry(entry, base) { - const fullpath = entry.path; - if (base !== undefined) { - entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); - } - if (common.isAppliedFilter(this._settings.entryFilter, entry)) { - this._pushToStorage(entry); - } - if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { - this._pushToQueue(fullpath, entry.path); - } - } - _pushToStorage(entry) { - this._storage.add(entry); - } -} -exports.default = SyncReader; + makeArray( + isString(pattern) + ? splitPattern(pattern) + : pattern + ).forEach(this._addPattern, this) + // Some rules have just added to the ignore, + // making the behavior changed. + if (this._added) { + this._initCache() + } -/***/ }), -/* 651 */ -/***/ (function(module, exports, __webpack_require__) { + return this + } -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const path = __webpack_require__(16); -const fsScandir = __webpack_require__(635); -class Settings { - constructor(_options = {}) { - this._options = _options; - this.basePath = this._getValue(this._options.basePath, undefined); - this.concurrency = this._getValue(this._options.concurrency, Infinity); - this.deepFilter = this._getValue(this._options.deepFilter, null); - this.entryFilter = this._getValue(this._options.entryFilter, null); - this.errorFilter = this._getValue(this._options.errorFilter, null); - this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep); - this.fsScandirSettings = new fsScandir.Settings({ - followSymbolicLinks: this._options.followSymbolicLinks, - fs: this._options.fs, - pathSegmentSeparator: this._options.pathSegmentSeparator, - stats: this._options.stats, - throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink - }); - } - _getValue(option, value) { - return option === undefined ? value : option; - } -} -exports.default = Settings; + // legacy + addPattern (pattern) { + return this.add(pattern) + } + // | ignored : unignored + // negative | 0:0 | 0:1 | 1:0 | 1:1 + // -------- | ------- | ------- | ------- | -------- + // 0 | TEST | TEST | SKIP | X + // 1 | TESTIF | SKIP | TEST | X -/***/ }), -/* 652 */ -/***/ (function(module, exports, __webpack_require__) { + // - SKIP: always skip + // - TEST: always test + // - TESTIF: only test if checkUnignored + // - X: that never happen -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const path = __webpack_require__(16); -const fsStat = __webpack_require__(627); -const utils = __webpack_require__(598); -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; + // @param {boolean} whether should check if the path is unignored, + // setting `checkUnignored` to `false` could reduce additional + // path matching. + // @returns {TestResult} true if a file is ignored + _testOne (path, checkUnignored) { + let ignored = false + let unignored = false -/***/ }), -/* 653 */ -/***/ (function(module, exports, __webpack_require__) { + this._rules.forEach(rule => { + const {negative} = rule + if ( + unignored === negative && ignored !== unignored + || negative && !ignored && !unignored && !checkUnignored + ) { + return + } -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const path = __webpack_require__(16); -const deep_1 = __webpack_require__(654); -const entry_1 = __webpack_require__(655); -const error_1 = __webpack_require__(656); -const entry_2 = __webpack_require__(657); -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; + const matched = rule.regex.test(path) + if (matched) { + ignored = !negative + unignored = negative + } + }) -/***/ }), -/* 654 */ -/***/ (function(module, exports, __webpack_require__) { + return { + ignored, + unignored + } + } -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const utils = __webpack_require__(598); -class DeepFilter { - constructor(_settings, _micromatchOptions) { - this._settings = _settings; - this._micromatchOptions = _micromatchOptions; - } - getFilter(basePath, positive, negative) { - const maxPatternDepth = this._getMaxPatternDepth(positive); - const negativeRe = this._getNegativePatternsRe(negative); - return (entry) => this._filter(basePath, entry, negativeRe, maxPatternDepth); - } - _getMaxPatternDepth(patterns) { - const globstar = patterns.some(utils.pattern.hasGlobStar); - return globstar ? Infinity : utils.pattern.getMaxNaivePatternsDepth(patterns); - } - _getNegativePatternsRe(patterns) { - const affectDepthOfReadingPatterns = patterns.filter(utils.pattern.isAffectDepthOfReadingPattern); - return utils.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); - } - _filter(basePath, entry, negativeRe, maxPatternDepth) { - const depth = this._getEntryDepth(basePath, entry.path); - if (this._isSkippedByDeep(depth)) { - return false; - } - if (this._isSkippedByMaxPatternDepth(depth, maxPatternDepth)) { - return false; - } - if (this._isSkippedSymbolicLink(entry)) { - return false; - } - if (this._isSkippedDotDirectory(entry)) { - return false; - } - return this._isSkippedByNegativePatterns(entry, negativeRe); - } - _getEntryDepth(basePath, entryPath) { - const basePathDepth = basePath.split('/').length; - const entryPathDepth = entryPath.split('/').length; - return entryPathDepth - (basePath === '' ? 0 : basePathDepth); - } - _isSkippedByDeep(entryDepth) { - return entryDepth >= this._settings.deep; - } - _isSkippedByMaxPatternDepth(entryDepth, maxPatternDepth) { - return !this._settings.baseNameMatch && maxPatternDepth !== Infinity && entryDepth > maxPatternDepth; - } - _isSkippedSymbolicLink(entry) { - return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); - } - _isSkippedDotDirectory(entry) { - return !this._settings.dot && entry.name.startsWith('.'); - } - _isSkippedByNegativePatterns(entry, negativeRe) { - return !utils.pattern.matchAny(entry.path, negativeRe); - } -} -exports.default = DeepFilter; + // @returns {TestResult} + _test (originalPath, cache, checkUnignored, slices) { + const path = originalPath + // Supports nullable path + && checkPath.convert(originalPath) + checkPath(path, originalPath, throwError) -/***/ }), -/* 655 */ -/***/ (function(module, exports, __webpack_require__) { + return this._t(path, cache, checkUnignored, slices) + } -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const utils = __webpack_require__(598); -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) { - if (this._isDuplicateEntry(entry)) { - return false; - } - this._createIndexRecord(entry); - } - if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { - return false; - } - if (this._isSkippedByAbsoluteNegativePatterns(entry, negativeRe)) { - return false; - } - const filepath = this._settings.baseNameMatch ? entry.name : entry.path; - return this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe); - } - _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(entry, negativeRe) { - if (!this._settings.absolute) { - return false; - } - const fullpath = utils.path.makeAbsolute(this._settings.cwd, entry.path); - return this._isMatchToPatterns(fullpath, negativeRe); - } - _isMatchToPatterns(filepath, patternsRe) { - return utils.pattern.matchAny(filepath, patternsRe); - } -} -exports.default = EntryFilter; + _t (path, cache, checkUnignored, slices) { + if (path in cache) { + return cache[path] + } + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH) + } -/***/ }), -/* 656 */ -/***/ (function(module, exports, __webpack_require__) { + slices.pop() -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const utils = __webpack_require__(598); -class ErrorFilter { - constructor(_settings) { - this._settings = _settings; - } - getFilter() { - return (error) => this._isNonFatalError(error); - } - _isNonFatalError(error) { - return utils.errno.isEnoentCodeError(error) || this._settings.suppressErrors; - } -} -exports.default = ErrorFilter; + // If the path has no parent directory, just test it + if (!slices.length) { + return cache[path] = this._testOne(path, checkUnignored) + } + const parent = this._t( + slices.join(SLASH) + SLASH, + cache, + checkUnignored, + slices + ) -/***/ }), -/* 657 */ -/***/ (function(module, exports, __webpack_require__) { + // If the path contains a parent directory, check the parent first + return cache[path] = parent.ignored + // > It is not possible to re-include a file if a parent directory of + // > that file is excluded. + ? parent + : this._testOne(path, checkUnignored) + } -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const utils = __webpack_require__(598); -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({}, entry, { path: filepath }); - } -} -exports.default = EntryTransformer; + ignores (path) { + return this._test(path, this._ignoreCache, false).ignored + } + createFilter () { + return path => !this.ignores(path) + } -/***/ }), -/* 658 */ -/***/ (function(module, exports, __webpack_require__) { + filter (paths) { + return makeArray(paths).filter(this.createFilter()) + } -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const stream_1 = __webpack_require__(27); -const stream_2 = __webpack_require__(626); -const provider_1 = __webpack_require__(653); -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 dest = new stream_1.Readable({ objectMode: true, read: () => { } }); - source - .once('error', (error) => dest.emit('error', error)) - .on('data', (entry) => dest.emit('data', options.transform(entry))) - .once('end', () => dest.emit('end')); - return dest; - } - api(root, task, options) { - if (task.dynamic) { - return this._reader.dynamic(root, options); - } - return this._reader.static(task.patterns, options); - } -} -exports.default = ProviderStream; + // @returns {TestResult} + test (path) { + return this._test(path, this._testCache, true) + } +} +const factory = options => new Ignore(options) -/***/ }), -/* 659 */ -/***/ (function(module, exports, __webpack_require__) { +const returnFalse = () => false -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const sync_1 = __webpack_require__(660); -const provider_1 = __webpack_require__(653); -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 isPathValid = path => + checkPath(path && checkPath.convert(path), path, returnFalse) +factory.isPathValid = isPathValid -/***/ }), -/* 660 */ -/***/ (function(module, exports, __webpack_require__) { +// Fixes typescript +factory.default = factory -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const fsStat = __webpack_require__(627); -const fsWalk = __webpack_require__(632); -const reader_1 = __webpack_require__(652); -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); - } -} -exports.default = ReaderSync; +module.exports = factory + +// 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' + ) +) { + /* eslint no-control-regex: "off" */ + const makePosix = str => /^\\\\\?\\/.test(str) + || /["<>|\u0000-\u001F]+/u.test(str) + ? str + : str.replace(/\\/g, '/') + + checkPath.convert = makePosix + + // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' + // 'd:\\foo' + const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i + checkPath.isNotRelative = path => + REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) + || isNotRelative(path) +} /***/ }), @@ -75639,59 +75888,17 @@ exports.default = ReaderSync; /***/ (function(module, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const fs = __webpack_require__(23); -const os = __webpack_require__(11); -const CPU_COUNT = os.cpus().length; -exports.DEFAULT_FILE_SYSTEM_ADAPTER = { - lstat: fs.lstat, - lstatSync: fs.lstatSync, - stat: fs.stat, - statSync: fs.statSync, - readdir: fs.readdir, - readdirSync: fs.readdirSync -}; -// tslint:enable no-redundant-jsdoc -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({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER, methods); - } -} -exports.default = Settings; + +module.exports = path => { + const isExtendedLengthPath = /^\\\\\?\\/.test(path); + const hasNonAscii = /[^\u0000-\u0080]+/.test(path); // eslint-disable-line no-control-regex + + if (isExtendedLengthPath || hasNonAscii) { + return path; + } + + return path.replace(/\\/g, '/'); +}; /***/ }), @@ -75700,1739 +75907,1725 @@ exports.default = Settings; "use strict"; -const path = __webpack_require__(16); -const pathType = __webpack_require__(663); +const {Transform} = __webpack_require__(382); -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}`; +class ObjectTransform extends Transform { + constructor() { + super({ + objectMode: true + }); } +} - return `**/${file}.${getExtensions(extensions)}`; -}; - -const getGlob = (directory, options) => { - if (options.files && !Array.isArray(options.files)) { - throw new TypeError(`Expected \`files\` to be of type \`Array\` but received type \`${typeof options.files}\``); +class FilterStream extends ObjectTransform { + constructor(filter) { + super(); + this._filter = filter; } - if (options.extensions && !Array.isArray(options.extensions)) { - throw new TypeError(`Expected \`extensions\` to be of type \`Array\` but received type \`${typeof options.extensions}\``); - } + _transform(data, encoding, callback) { + if (this._filter(data)) { + this.push(data); + } - if (options.files && options.extensions) { - return options.files.map(x => path.posix.join(directory, addExtensions(x, options.extensions))); + callback(); } +} - if (options.files) { - return options.files.map(x => path.posix.join(directory, `**/${x}`)); +class UniqueStream extends ObjectTransform { + constructor() { + super(); + this._pushed = new Set(); } - if (options.extensions) { - return [path.posix.join(directory, `**/*.${getExtensions(options.extensions)}`)]; + _transform(data, encoding, callback) { + if (!this._pushed.has(data)) { + this.push(data); + this._pushed.add(data); + } + + callback(); } +} - return [path.posix.join(directory, '**')]; +module.exports = { + FilterStream, + UniqueStream }; -module.exports = async (input, options) => { - options = { - cwd: process.cwd(), - ...options - }; - if (typeof options.cwd !== 'string') { - throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``); - } +/***/ }), +/* 663 */ +/***/ (function(module, exports, __webpack_require__) { - const globs = await Promise.all([].concat(input).map(async x => { - const isDirectory = await pathType.isDirectory(getPath(x, options.cwd)); - return isDirectory ? getGlob(x, options) : x; - })); +"use strict"; - return [].concat.apply([], globs); // eslint-disable-line prefer-spread -}; +const path = __webpack_require__(4); -module.exports.sync = (input, options) => { - options = { - cwd: process.cwd(), - ...options - }; +module.exports = path_ => { + let cwd = process.cwd(); - if (typeof options.cwd !== 'string') { - throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``); - } + path_ = path.resolve(path_); - const globs = [].concat(input).map(x => pathType.isDirectorySync(getPath(x, options.cwd)) ? getGlob(x, options) : x); + if (process.platform === 'win32') { + cwd = cwd.toLowerCase(); + path_ = path_.toLowerCase(); + } - return [].concat.apply([], globs); // eslint-disable-line prefer-spread + return path_ === cwd; }; /***/ }), -/* 663 */ +/* 664 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const {promisify} = __webpack_require__(29); -const fs = __webpack_require__(23); +const path = __webpack_require__(4); -async function isType(fsStatType, statsMethodName, filePath) { - if (typeof filePath !== 'string') { - throw new TypeError(`Expected a string, got ${typeof filePath}`); - } +module.exports = (childPath, parentPath) => { + childPath = path.resolve(childPath); + parentPath = path.resolve(parentPath); - try { - const stats = await promisify(fs[fsStatType])(filePath); - return stats[statsMethodName](); - } catch (error) { - if (error.code === 'ENOENT') { - return false; - } + if (process.platform === 'win32') { + childPath = childPath.toLowerCase(); + parentPath = parentPath.toLowerCase(); + } - throw error; + if (childPath === parentPath) { + return false; } + + childPath += path.sep; + parentPath += path.sep; + + return childPath.startsWith(parentPath); +}; + + +/***/ }), +/* 665 */ +/***/ (function(module, exports, __webpack_require__) { + +const assert = __webpack_require__(371) +const path = __webpack_require__(4) +const fs = __webpack_require__(349) +let glob = undefined +try { + glob = __webpack_require__(586) +} catch (_err) { + // treat glob as optional. } -function isTypeSync(fsStatType, statsMethodName, filePath) { - if (typeof filePath !== 'string') { - throw new TypeError(`Expected a string, got ${typeof filePath}`); - } +const defaultGlobOpts = { + nosort: true, + silent: true +} - try { - return fs[fsStatType](filePath)[statsMethodName](); - } catch (error) { - if (error.code === 'ENOENT') { - return false; - } +// for EMFILE handling +let timeout = 0 - throw error; - } +const isWindows = (process.platform === "win32") + +const defaults = options => { + const methods = [ + 'unlink', + 'chmod', + 'stat', + 'lstat', + 'rmdir', + 'readdir' + ] + methods.forEach(m => { + options[m] = options[m] || fs[m] + m = m + 'Sync' + options[m] = options[m] || fs[m] + }) + + options.maxBusyTries = options.maxBusyTries || 3 + options.emfileWait = options.emfileWait || 1000 + if (options.glob === false) { + options.disableGlob = true + } + if (options.disableGlob !== true && glob === undefined) { + throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') + } + options.disableGlob = options.disableGlob || false + options.glob = options.glob || defaultGlobOpts } -exports.isFile = isType.bind(null, 'stat', 'isFile'); -exports.isDirectory = isType.bind(null, 'stat', 'isDirectory'); -exports.isSymlink = isType.bind(null, 'lstat', 'isSymbolicLink'); -exports.isFileSync = isTypeSync.bind(null, 'statSync', 'isFile'); -exports.isDirectorySync = isTypeSync.bind(null, 'statSync', 'isDirectory'); -exports.isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink'); +const rimraf = (p, options, cb) => { + if (typeof options === 'function') { + cb = options + options = {} + } + + assert(p, 'rimraf: missing path') + assert.equal(typeof p, 'string', 'rimraf: path should be a string') + assert.equal(typeof cb, 'function', 'rimraf: callback function required') + assert(options, 'rimraf: invalid options argument provided') + assert.equal(typeof options, 'object', 'rimraf: options should be object') + + defaults(options) + + let busyTries = 0 + let errState = null + let n = 0 + + const next = (er) => { + errState = errState || er + if (--n === 0) + cb(errState) + } + + const afterGlob = (er, results) => { + if (er) + return cb(er) + + n = results.length + if (n === 0) + return cb() + + results.forEach(p => { + const CB = (er) => { + if (er) { + if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && + busyTries < options.maxBusyTries) { + busyTries ++ + // try again, with the same exact callback as this one. + return setTimeout(() => rimraf_(p, options, CB), busyTries * 100) + } + + // this one won't happen if graceful-fs is used. + if (er.code === "EMFILE" && timeout < options.emfileWait) { + return setTimeout(() => rimraf_(p, options, CB), timeout ++) + } + + // already gone + if (er.code === "ENOENT") er = null + } + timeout = 0 + next(er) + } + rimraf_(p, options, CB) + }) + } -/***/ }), -/* 664 */ -/***/ (function(module, exports, __webpack_require__) { + if (options.disableGlob || !glob.hasMagic(p)) + return afterGlob(null, [p]) -"use strict"; + options.lstat(p, (er, stat) => { + if (!er) + return afterGlob(null, [p]) -const {promisify} = __webpack_require__(29); -const fs = __webpack_require__(23); -const path = __webpack_require__(16); -const fastGlob = __webpack_require__(596); -const gitIgnore = __webpack_require__(665); -const slash = __webpack_require__(666); + glob(p, options.glob, afterGlob) + }) -const DEFAULT_IGNORE = [ - '**/node_modules/**', - '**/flow-typed/**', - '**/coverage/**', - '**/.git' -]; +} -const readFileP = promisify(fs.readFile); +// Two possible strategies. +// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR +// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR +// +// Both result in an extra syscall when you guess wrong. However, there +// are likely far more normal files in the world than directories. This +// is based on the assumption that a the average number of files per +// directory is >= 1. +// +// If anyone ever complains about this, then I guess the strategy could +// be made configurable somehow. But until then, YAGNI. +const rimraf_ = (p, options, cb) => { + assert(p) + assert(options) + assert(typeof cb === 'function') -const mapGitIgnorePatternTo = base => ignore => { - if (ignore.startsWith('!')) { - return '!' + path.posix.join(base, ignore.slice(1)); - } + // sunos lets the root user unlink directories, which is... weird. + // so we have to lstat here and make sure it's not a dir. + options.lstat(p, (er, st) => { + if (er && er.code === "ENOENT") + return cb(null) - return path.posix.join(base, ignore); -}; + // Windows can EPERM on stat. Life is suffering. + if (er && er.code === "EPERM" && isWindows) + fixWinEPERM(p, options, er, cb) -const parseGitIgnore = (content, options) => { - const base = slash(path.relative(options.cwd, path.dirname(options.fileName))); + if (st && st.isDirectory()) + return rmdir(p, options, er, cb) - return content - .split(/\r?\n/) - .filter(Boolean) - .filter(line => !line.startsWith('#')) - .map(mapGitIgnorePatternTo(base)); -}; + options.unlink(p, er => { + if (er) { + if (er.code === "ENOENT") + return cb(null) + if (er.code === "EPERM") + return (isWindows) + ? fixWinEPERM(p, options, er, cb) + : rmdir(p, options, er, cb) + if (er.code === "EISDIR") + return rmdir(p, options, er, cb) + } + return cb(er) + }) + }) +} -const reduceIgnore = files => { - return files.reduce((ignores, file) => { - ignores.add(parseGitIgnore(file.content, { - cwd: file.cwd, - fileName: file.filePath - })); - return ignores; - }, gitIgnore()); -}; +const fixWinEPERM = (p, options, er, cb) => { + assert(p) + assert(options) + assert(typeof cb === 'function') + if (er) + assert(er instanceof Error) -const ensureAbsolutePathForCwd = (cwd, p) => { - if (path.isAbsolute(p)) { - if (p.startsWith(cwd)) { - return p; - } + options.chmod(p, 0o666, er2 => { + if (er2) + cb(er2.code === "ENOENT" ? null : er) + else + options.stat(p, (er3, stats) => { + if (er3) + cb(er3.code === "ENOENT" ? null : er) + else if (stats.isDirectory()) + rmdir(p, options, er, cb) + else + options.unlink(p, cb) + }) + }) +} - throw new Error(`Path ${p} is not in cwd ${cwd}`); - } +const fixWinEPERMSync = (p, options, er) => { + assert(p) + assert(options) + if (er) + assert(er instanceof Error) - return path.join(cwd, p); -}; + try { + options.chmodSync(p, 0o666) + } catch (er2) { + if (er2.code === "ENOENT") + return + else + throw er + } -const getIsIgnoredPredecate = (ignores, cwd) => { - return p => ignores.ignores(slash(path.relative(cwd, ensureAbsolutePathForCwd(cwd, p)))); -}; + let stats + try { + stats = options.statSync(p) + } catch (er3) { + if (er3.code === "ENOENT") + return + else + throw er + } -const getFile = async (file, cwd) => { - const filePath = path.join(cwd, file); - const content = await readFileP(filePath, 'utf8'); + if (stats.isDirectory()) + rmdirSync(p, options, er) + else + options.unlinkSync(p) +} - return { - cwd, - filePath, - content - }; -}; +const rmdir = (p, options, originalEr, cb) => { + assert(p) + assert(options) + if (originalEr) + assert(originalEr instanceof Error) + assert(typeof cb === 'function') -const getFileSync = (file, cwd) => { - const filePath = path.join(cwd, file); - const content = fs.readFileSync(filePath, 'utf8'); + // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) + // if we guessed wrong, and it's not a directory, then + // raise the original error. + options.rmdir(p, er => { + if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) + rmkids(p, options, cb) + else if (er && er.code === "ENOTDIR") + cb(originalEr) + else + cb(er) + }) +} - return { - cwd, - filePath, - content - }; -}; +const rmkids = (p, options, cb) => { + assert(p) + assert(options) + assert(typeof cb === 'function') -const normalizeOptions = ({ - ignore = [], - cwd = process.cwd() -} = {}) => { - return {ignore, cwd}; -}; + options.readdir(p, (er, files) => { + if (er) + return cb(er) + let n = files.length + if (n === 0) + return options.rmdir(p, cb) + let errState + files.forEach(f => { + rimraf(path.join(p, f), options, er => { + if (errState) + return + if (er) + return cb(errState = er) + if (--n === 0) + options.rmdir(p, cb) + }) + }) + }) +} -module.exports = async options => { - options = normalizeOptions(options); +// this looks simpler, and is strictly *faster*, but will +// tie up the JavaScript thread and fail on excessively +// deep directory trees. +const rimrafSync = (p, options) => { + options = options || {} + defaults(options) - const paths = await fastGlob('**/.gitignore', { - ignore: DEFAULT_IGNORE.concat(options.ignore), - cwd: options.cwd - }); + assert(p, 'rimraf: missing path') + assert.equal(typeof p, 'string', 'rimraf: path should be a string') + assert(options, 'rimraf: missing options') + assert.equal(typeof options, 'object', 'rimraf: options should be object') - const files = await Promise.all(paths.map(file => getFile(file, options.cwd))); - const ignores = reduceIgnore(files); + let results - return getIsIgnoredPredecate(ignores, options.cwd); -}; + if (options.disableGlob || !glob.hasMagic(p)) { + results = [p] + } else { + try { + options.lstatSync(p) + results = [p] + } catch (er) { + results = glob.sync(p, options.glob) + } + } -module.exports.sync = options => { - options = normalizeOptions(options); + if (!results.length) + return - const paths = fastGlob.sync('**/.gitignore', { - ignore: DEFAULT_IGNORE.concat(options.ignore), - cwd: options.cwd - }); + for (let i = 0; i < results.length; i++) { + const p = results[i] - const files = paths.map(file => getFileSync(file, options.cwd)); - const ignores = reduceIgnore(files); + let st + try { + st = options.lstatSync(p) + } catch (er) { + if (er.code === "ENOENT") + return - return getIsIgnoredPredecate(ignores, options.cwd); -}; + // Windows can EPERM on stat. Life is suffering. + if (er.code === "EPERM" && isWindows) + fixWinEPERMSync(p, options, er) + } + try { + // sunos lets the root user unlink directories, which is... weird. + if (st && st.isDirectory()) + rmdirSync(p, options, null) + else + options.unlinkSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + if (er.code === "EPERM") + return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) + if (er.code !== "EISDIR") + throw er -/***/ }), -/* 665 */ -/***/ (function(module, exports) { + rmdirSync(p, options, er) + } + } +} -// A simple implementation of make-array -function makeArray (subject) { - return Array.isArray(subject) - ? subject - : [subject] +const rmdirSync = (p, options, originalEr) => { + assert(p) + assert(options) + if (originalEr) + assert(originalEr instanceof Error) + + try { + options.rmdirSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + if (er.code === "ENOTDIR") + throw originalEr + if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") + rmkidsSync(p, options) + } } -const REGEX_TEST_BLANK_LINE = /^\s+$/ -const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/ -const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/ -const REGEX_SPLITALL_CRLF = /\r?\n/g -// /foo, -// ./foo, -// ../foo, -// . -// .. -const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/ +const rmkidsSync = (p, options) => { + assert(p) + assert(options) + options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) -const SLASH = '/' -const KEY_IGNORE = typeof Symbol !== 'undefined' - ? Symbol.for('node-ignore') - /* istanbul ignore next */ - : 'node-ignore' + // We only end up here once we got ENOTEMPTY at least once, and + // at this point, we are guaranteed to have removed all the kids. + // So, we know that it won't be ENOENT or ENOTDIR or anything else. + // try really hard to delete stuff on windows, because it has a + // PROFOUNDLY annoying habit of not closing handles promptly when + // files are deleted, resulting in spurious ENOTEMPTY errors. + const retries = isWindows ? 100 : 1 + let i = 0 + do { + let threw = true + try { + const ret = options.rmdirSync(p, options) + threw = false + return ret + } finally { + if (++i < retries && threw) + continue + } + } while (true) +} -const define = (object, key, value) => - Object.defineProperty(object, key, {value}) +module.exports = rimraf +rimraf.sync = rimrafSync -const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g -// 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. - : '' -) +/***/ }), +/* 666 */ +/***/ (function(module, exports, __webpack_require__) { -// > 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` +"use strict"; -// '`foo/`' should not continue with the '`..`' -const DEFAULT_REPLACER_PREFIX = [ +const AggregateError = __webpack_require__(667); - // > Trailing spaces are ignored unless they are quoted with backslash ("\") - [ - // (a\ ) -> (a ) - // (a ) -> (a) - // (a \ ) -> (a ) - /\\?\s+$/, - match => match.indexOf('\\') === 0 - ? ' ' - : '' - ], +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'); + } - // replace (\ ) with ' ' - [ - /\\\s/g, - () => ' ' - ], + if (!(typeof concurrency === 'number' && concurrency >= 1)) { + throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${concurrency}\` (${typeof concurrency})`); + } - // Escape metacharacters - // which is written down by users but means special for regular expressions. + const ret = []; + const errors = []; + const iterator = iterable[Symbol.iterator](); + let isRejected = false; + let isIterableDone = false; + let resolvingCount = 0; + let currentIndex = 0; - // > 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}` - ], + const next = () => { + if (isRejected) { + return; + } - [ - // > [abc] matches any character inside the brackets - // > (in this case a, b, or c); - /\[([^\]/]*)($|\])/g, - (match, p1, p2) => p2 === ']' - ? `[${sanitizeRange(p1)}]` - : `\\${match}` - ], + const nextItem = iterator.next(); + const i = currentIndex; + currentIndex++; - [ - // > a question mark (?) matches a single character - /(?!\\)\?/g, - () => '[^/]' - ], + if (nextItem.done) { + isIterableDone = true; - // leading slash - [ + if (resolvingCount === 0) { + if (!stopOnError && errors.length !== 0) { + reject(new AggregateError(errors)); + } else { + resolve(ret); + } + } - // > 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 - /^\//, - () => '^' - ], + return; + } - // replace special metacharacter slash after the leading slash - [ - /\//g, - () => '\\/' - ], + resolvingCount++; - [ - // > 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 '\\*' - /^\^*\\\*\\\*\\\//, + (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(); + } + } + })(); + }; - // '**/foo' <-> 'foo' - () => '^(?:.*\\/)?' - ] -] + for (let i = 0; i < concurrency; i++) { + next(); -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 - ? '(?:^|\\/)' + if (isIterableDone) { + break; + } + } + }); +}; - // > Otherwise, Git treats the pattern as a shell glob suitable for - // > consumption by fnmatch(3) - : '^' - } - ], - // two globstars - [ - // Use lookahead assertions so that we could match more than one `'/**'` - /\\\/\\\*\\\*(?=\\\/|$)/g, +/***/ }), +/* 667 */ +/***/ (function(module, exports, __webpack_require__) { - // Zero, one or several directories - // should not use '*', or it will be replaced by the next replacer +"use strict"; - // Check if it is not the last `'/**'` - (_, index, str) => index + 6 < str.length +const indentString = __webpack_require__(668); +const cleanStack = __webpack_require__(669); - // 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. - // '/**/' - ? '(?:\\/[^\\/]+)*' +const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); - // case: /** - // > A trailing `"/**"` matches everything inside. +class AggregateError extends Error { + constructor(errors) { + if (!Array.isArray(errors)) { + throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); + } - // #21: everything inside but it should not include the current folder - : '\\/.+' - ], + errors = [...errors].map(error => { + if (error instanceof Error) { + return error; + } - // intermediate wildcards - [ - // Never replace escaped '*' - // ignore rule '\*' will match the path '*' + 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); + } - // 'abc.*/' -> go - // 'abc.*' -> skip this rule - /(^|[^\\]+)\\\*(?=.+)/g, + return new Error(error); + }); - // '*.js' matches '.js' - // '*.js' doesn't match 'abc' - (_, p1) => `${p1}[^\\/]*` - ], + 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); - // trailing wildcard - [ - /(\^|\\\/)?\\\*$/, - (_, p1) => { - const prefix = p1 - // '\^': - // '/*' does not match '' - // '/*' does not match everything + this.name = 'AggregateError'; - // '\\\/': - // 'abc/*' does not match 'abc/' - ? `${p1}[^/]+` + Object.defineProperty(this, '_errors', {value: errors}); + } - // 'a*' matches 'a' - // 'a*' matches 'aa' - : '[^/]*' + * [Symbol.iterator]() { + for (const error of this._errors) { + yield error; + } + } +} - return `${prefix}(?=$|\\/$)` - } - ], +module.exports = AggregateError; - [ - // unescape - /\\\\\\/g, - () => '\\' - ] -] -const POSITIVE_REPLACERS = [ - ...DEFAULT_REPLACER_PREFIX, +/***/ }), +/* 668 */ +/***/ (function(module, exports, __webpack_require__) { - // 'f' - // matches - // - /f(end) - // - /f/ - // - (start)f(end) - // - (start)f/ - // doesn't match - // - oof - // - foo - // pseudo: - // -> (^|/)f(/|$) +"use strict"; - // 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}(?=$|\\/)` - ], +module.exports = (string, count = 1, options) => { + options = { + indent: ' ', + includeEmptyLines: false, + ...options + }; - ...DEFAULT_REPLACER_SUFFIX -] + if (typeof string !== 'string') { + throw new TypeError( + `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` + ); + } -const NEGATIVE_REPLACERS = [ - ...DEFAULT_REPLACER_PREFIX, + if (typeof count !== 'number') { + throw new TypeError( + `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` + ); + } - // #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 (typeof options.indent !== 'string') { + throw new TypeError( + `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` + ); + } - // eg: - // ['node_modules/*', '!node_modules'] - // should ignore `node_modules/a.js` - [ - /(?:[^*])$/, - match => `${match}(?=$|\\/$)` - ], + if (count === 0) { + return string; + } - ...DEFAULT_REPLACER_SUFFIX -] + const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; -// A simple cache, because an ignore rule only has only one certain meaning -const regexCache = Object.create(null) + return string.replace(regex, options.indent.repeat(count)); +}; -// @param {pattern} -const makeRegex = (pattern, negative, ignorecase) => { - const r = regexCache[pattern] - if (r) { - return r - } - const replacers = negative - ? NEGATIVE_REPLACERS - : POSITIVE_REPLACERS +/***/ }), +/* 669 */ +/***/ (function(module, exports, __webpack_require__) { - const source = replacers.reduce( - (prev, current) => prev.replace(current[0], current[1].bind(pattern)), - pattern - ) +"use strict"; - return regexCache[pattern] = ignorecase - ? new RegExp(source, 'i') - : new RegExp(source) -} +const os = __webpack_require__(364); -const isString = subject => typeof subject === 'string' +const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/; +const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; +const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir(); -// > A blank line matches no files, so it can serve as a separator for readability. -const checkPattern = pattern => pattern - && isString(pattern) - && !REGEX_TEST_BLANK_LINE.test(pattern) +module.exports = (stack, options) => { + options = Object.assign({pretty: false}, options); - // > A line starting with # serves as a comment. - && pattern.indexOf('#') !== 0 + return stack.replace(/\\/g, '/') + .split('\n') + .filter(line => { + const pathMatches = line.match(extractPathRegex); + if (pathMatches === null || !pathMatches[1]) { + return true; + } -const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF) + const match = pathMatches[1]; -class IgnoreRule { - constructor ( - origin, - pattern, - negative, - regex - ) { - this.origin = origin - this.pattern = pattern - this.negative = negative - this.regex = regex - } -} + // Electron + if ( + match.includes('.app/Contents/Resources/electron.asar') || + match.includes('.app/Contents/Resources/default_app.asar') + ) { + return false; + } -const createRule = (pattern, ignorecase) => { - const origin = pattern - let negative = false + return !pathRegex.test(match); + }) + .filter(line => line.trim() !== '') + .map(line => { + if (options.pretty) { + return line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~'))); + } - // > An optional prefix "!" which negates the pattern; - if (pattern.indexOf('!') === 0) { - negative = true - pattern = pattern.substr(1) - } + return line; + }) + .join('\n'); +}; - pattern = pattern - // > Put a backslash ("\") in front of the first "!" for patterns that - // > begin with a literal "!", for example, `"\!important!.txt"`. - .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') - // > Put a backslash ("\") in front of the first hash for patterns that - // > begin with a hash. - .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#') - const regex = makeRegex(pattern, negative, ignorecase) +/***/ }), +/* 670 */ +/***/ (function(module, exports, __webpack_require__) { - return new IgnoreRule( - origin, - pattern, - negative, - regex - ) -} +"use strict"; -const throwError = (message, Ctor) => { - throw new Ctor(message) -} +const chalk = __webpack_require__(671); +const cliCursor = __webpack_require__(675); +const cliSpinners = __webpack_require__(679); +const logSymbols = __webpack_require__(681); -const checkPath = (path, originalPath, doThrow) => { - if (!isString(path)) { - return doThrow( - `path must be a string, but got \`${originalPath}\``, - TypeError - ) - } +class Ora { + constructor(options) { + if (typeof options === 'string') { + options = { + text: options + }; + } - // We don't know if we should ignore '', so throw - if (!path) { - return doThrow(`path must not be empty`, TypeError) - } + this.options = Object.assign({ + text: '', + color: 'cyan', + stream: process.stderr + }, options); - // Check if it is a relative path - if (checkPath.isNotRelative(path)) { - const r = '`path.relative()`d' - return doThrow( - `path should be a ${r} string, but got "${originalPath}"`, - RangeError - ) - } + const sp = this.options.spinner; + this.spinner = typeof sp === 'object' ? sp : (process.platform === 'win32' ? cliSpinners.line : (cliSpinners[sp] || cliSpinners.dots)); // eslint-disable-line no-nested-ternary - return true -} + if (this.spinner.frames === undefined) { + throw new Error('Spinner must define `frames`'); + } -const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path) + this.text = this.options.text; + this.color = this.options.color; + this.interval = this.options.interval || this.spinner.interval || 100; + this.stream = this.options.stream; + this.id = null; + this.frameIndex = 0; + this.enabled = typeof this.options.enabled === 'boolean' ? this.options.enabled : ((this.stream && this.stream.isTTY) && !process.env.CI); + } + frame() { + const frames = this.spinner.frames; + let frame = frames[this.frameIndex]; -checkPath.isNotRelative = isNotRelative -checkPath.convert = p => p + if (this.color) { + frame = chalk[this.color](frame); + } -class Ignore { - constructor ({ - ignorecase = true - } = {}) { - this._rules = [] - this._ignorecase = ignorecase - define(this, KEY_IGNORE, true) - this._initCache() - } + this.frameIndex = ++this.frameIndex % frames.length; - _initCache () { - this._ignoreCache = Object.create(null) - this._testCache = Object.create(null) - } + return frame + ' ' + this.text; + } + clear() { + if (!this.enabled) { + return this; + } - _addPattern (pattern) { - // #32 - if (pattern && pattern[KEY_IGNORE]) { - this._rules = this._rules.concat(pattern._rules) - this._added = true - return - } + this.stream.clearLine(); + this.stream.cursorTo(0); - if (checkPattern(pattern)) { - const rule = createRule(pattern, this._ignorecase) - this._added = true - this._rules.push(rule) - } - } + return this; + } + render() { + this.clear(); + this.stream.write(this.frame()); - // @param {Array | string | Ignore} pattern - add (pattern) { - this._added = false + return this; + } + start(text) { + if (text) { + this.text = text; + } - makeArray( - isString(pattern) - ? splitPattern(pattern) - : pattern - ).forEach(this._addPattern, this) + if (!this.enabled || this.id) { + return this; + } - // Some rules have just added to the ignore, - // making the behavior changed. - if (this._added) { - this._initCache() - } + cliCursor.hide(this.stream); + this.render(); + this.id = setInterval(this.render.bind(this), this.interval); - return this - } + return this; + } + stop() { + if (!this.enabled) { + return this; + } - // legacy - addPattern (pattern) { - return this.add(pattern) - } + clearInterval(this.id); + this.id = null; + this.frameIndex = 0; + this.clear(); + cliCursor.show(this.stream); - // | ignored : unignored - // negative | 0:0 | 0:1 | 1:0 | 1:1 - // -------- | ------- | ------- | ------- | -------- - // 0 | TEST | TEST | SKIP | X - // 1 | TESTIF | SKIP | TEST | X + return this; + } + succeed(text) { + return this.stopAndPersist({symbol: logSymbols.success, text}); + } + fail(text) { + return this.stopAndPersist({symbol: logSymbols.error, text}); + } + warn(text) { + return this.stopAndPersist({symbol: logSymbols.warning, text}); + } + info(text) { + return this.stopAndPersist({symbol: logSymbols.info, text}); + } + stopAndPersist(options) { + if (!this.enabled) { + return this; + } - // - SKIP: always skip - // - TEST: always test - // - TESTIF: only test if checkUnignored - // - X: that never happen + // Legacy argument + // TODO: Deprecate sometime in the future + if (typeof options === 'string') { + options = { + symbol: options + }; + } - // @param {boolean} whether should check if the path is unignored, - // setting `checkUnignored` to `false` could reduce additional - // path matching. + options = options || {}; - // @returns {TestResult} true if a file is ignored - _testOne (path, checkUnignored) { - let ignored = false - let unignored = false + this.stop(); + this.stream.write(`${options.symbol || ' '} ${options.text || this.text}\n`); - this._rules.forEach(rule => { - const {negative} = rule - if ( - unignored === negative && ignored !== unignored - || negative && !ignored && !unignored && !checkUnignored - ) { - return - } + return this; + } +} - const matched = rule.regex.test(path) +module.exports = function (opts) { + return new Ora(opts); +}; - if (matched) { - ignored = !negative - unignored = negative - } - }) +module.exports.promise = (action, options) => { + if (typeof action.then !== 'function') { + throw new TypeError('Parameter `action` must be a Promise'); + } - return { - ignored, - unignored - } - } + const spinner = new Ora(options); + spinner.start(); - // @returns {TestResult} - _test (originalPath, cache, checkUnignored, slices) { - const path = originalPath - // Supports nullable path - && checkPath.convert(originalPath) + action.then( + () => { + spinner.succeed(); + }, + () => { + spinner.fail(); + } + ); - checkPath(path, originalPath, throwError) + return spinner; +}; - return this._t(path, cache, checkUnignored, slices) - } - _t (path, cache, checkUnignored, slices) { - if (path in cache) { - return cache[path] - } +/***/ }), +/* 671 */ +/***/ (function(module, exports, __webpack_require__) { - if (!slices) { - // path/to/a.js - // ['path', 'to', 'a.js'] - slices = path.split(SLASH) - } +"use strict"; - slices.pop() +const escapeStringRegexp = __webpack_require__(387); +const ansiStyles = __webpack_require__(672); +const stdoutColor = __webpack_require__(673).stdout; - // If the path has no parent directory, just test it - if (!slices.length) { - return cache[path] = this._testOne(path, checkUnignored) - } +const template = __webpack_require__(674); - const parent = this._t( - slices.join(SLASH) + SLASH, - cache, - checkUnignored, - slices - ) +const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); - // If the path contains a parent directory, check the parent first - return cache[path] = parent.ignored - // > It is not possible to re-include a file if a parent directory of - // > that file is excluded. - ? parent - : this._testOne(path, checkUnignored) - } +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; - ignores (path) { - return this._test(path, this._ignoreCache, false).ignored - } +// `color-convert` models to exclude from the Chalk API due to conflicts and such +const skipModels = new Set(['gray']); - createFilter () { - return path => !this.ignores(path) - } +const styles = Object.create(null); - filter (paths) { - return makeArray(paths).filter(this.createFilter()) - } +function applyOptions(obj, options) { + options = options || {}; - // @returns {TestResult} - test (path) { - return this._test(path, this._testCache, true) - } + // Detect level if not set manually + const scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; } -const factory = options => new Ignore(options) +function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + const chalk = {}; + applyOptions(chalk, options); -const returnFalse = () => false + chalk.template = function () { + const args = [].slice.call(arguments); + return chalkTag.apply(null, [chalk.template].concat(args)); + }; -const isPathValid = path => - checkPath(path && checkPath.convert(path), path, returnFalse) + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); -factory.isPathValid = isPathValid + chalk.template.constructor = Chalk; -// Fixes typescript -factory.default = factory + return chalk.template; + } -module.exports = factory + applyOptions(this, options); +} -// 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' - ) -) { - /* eslint no-control-regex: "off" */ - const makePosix = str => /^\\\\\?\\/.test(str) - || /["<>|\u0000-\u001F]+/u.test(str) - ? str - : str.replace(/\\/g, '/') +// Use bright blue on Windows as the normal blue color is illegible +if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001B[94m'; +} - checkPath.convert = makePosix +for (const key of Object.keys(ansiStyles)) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); - // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' - // 'd:\\foo' - const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i - checkPath.isNotRelative = path => - REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) - || isNotRelative(path) + styles[key] = { + get() { + const codes = ansiStyles[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + }; } +styles.visible = { + get() { + return build.call(this, this._styles || [], true, 'visible'); + } +}; -/***/ }), -/* 666 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); +for (const model of Object.keys(ansiStyles.color.ansi)) { + if (skipModels.has(model)) { + continue; + } -module.exports = path => { - const isExtendedLengthPath = /^\\\\\?\\/.test(path); - const hasNonAscii = /[^\u0000-\u0080]+/.test(path); // eslint-disable-line no-control-regex + styles[model] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.color.close, + closeRe: ansiStyles.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} - if (isExtendedLengthPath || hasNonAscii) { - return path; +ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); +for (const model of Object.keys(ansiStyles.bgColor.ansi)) { + if (skipModels.has(model)) { + continue; } - return path.replace(/\\/g, '/'); -}; - + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.bgColor.close, + closeRe: ansiStyles.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} -/***/ }), -/* 667 */ -/***/ (function(module, exports, __webpack_require__) { +const proto = Object.defineProperties(() => {}, styles); -"use strict"; +function build(_styles, _empty, key) { + const builder = function () { + return applyStyle.apply(builder, arguments); + }; -const {Transform} = __webpack_require__(27); + builder._styles = _styles; + builder._empty = _empty; -class ObjectTransform extends Transform { - constructor() { - super({ - objectMode: true - }); - } -} + const self = this; -class FilterStream extends ObjectTransform { - constructor(filter) { - super(); - this._filter = filter; - } + Object.defineProperty(builder, 'level', { + enumerable: true, + get() { + return self.level; + }, + set(level) { + self.level = level; + } + }); - _transform(data, encoding, callback) { - if (this._filter(data)) { - this.push(data); + Object.defineProperty(builder, 'enabled', { + enumerable: true, + get() { + return self.enabled; + }, + set(enabled) { + self.enabled = enabled; } + }); - callback(); - } + // See below for fix regarding invisible grey/dim combination on Windows + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; + + // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; } -class UniqueStream extends ObjectTransform { - constructor() { - super(); - this._pushed = new Set(); +function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + const args = arguments; + const argsLen = args.length; + let str = String(arguments[0]); + + if (argsLen === 0) { + return ''; } - _transform(data, encoding, callback) { - if (!this._pushed.has(data)) { - this.push(data); - this._pushed.add(data); + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (let a = 1; a < argsLen; a++) { + str += ' ' + args[a]; } + } - callback(); + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; } -} -module.exports = { - FilterStream, - UniqueStream -}; + // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + const originalDim = ansiStyles.dim.open; + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles.dim.open = ''; + } + for (const code of this._styles.slice().reverse()) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; -/***/ }), -/* 668 */ -/***/ (function(module, exports, __webpack_require__) { + // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); + } -"use strict"; + // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + ansiStyles.dim.open = originalDim; -const path = __webpack_require__(16); + return str; +} -module.exports = path_ => { - let cwd = process.cwd(); +function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } - path_ = path.resolve(path_); + const args = [].slice.call(arguments, 2); + const parts = [strings.raw[0]]; - if (process.platform === 'win32') { - cwd = cwd.toLowerCase(); - path_ = path_.toLowerCase(); + for (let i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); } - return path_ === cwd; -}; + return template(chalk, parts.join('')); +} + +Object.defineProperties(Chalk.prototype, styles); + +module.exports = Chalk(); // eslint-disable-line new-cap +module.exports.supportsColor = stdoutColor; +module.exports.default = module.exports; // For TypeScript /***/ }), -/* 669 */ +/* 672 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/* WEBPACK VAR INJECTION */(function(module) { +const colorConvert = __webpack_require__(389); -const path = __webpack_require__(16); - -module.exports = (childPath, parentPath) => { - childPath = path.resolve(childPath); - parentPath = path.resolve(parentPath); - - if (process.platform === 'win32') { - childPath = childPath.toLowerCase(); - parentPath = parentPath.toLowerCase(); - } - - if (childPath === parentPath) { - return false; - } - - childPath += path.sep; - parentPath += path.sep; +const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${code + offset}m`; +}; - return childPath.startsWith(parentPath); +const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};5;${code}m`; }; +const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; -/***/ }), -/* 670 */ -/***/ (function(module, exports, __webpack_require__) { +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], -const assert = __webpack_require__(30) -const path = __webpack_require__(16) -const fs = __webpack_require__(23) -let glob = undefined -try { - glob = __webpack_require__(591) -} catch (_err) { - // treat glob as optional. -} + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], -const defaultGlobOpts = { - nosort: true, - silent: true -} + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; -// for EMFILE handling -let timeout = 0 + // Fix humans + styles.color.grey = styles.color.gray; -const isWindows = (process.platform === "win32") + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; -const defaults = options => { - const methods = [ - 'unlink', - 'chmod', - 'stat', - 'lstat', - 'rmdir', - 'readdir' - ] - methods.forEach(m => { - options[m] = options[m] || fs[m] - m = m + 'Sync' - options[m] = options[m] || fs[m] - }) + for (const styleName of Object.keys(group)) { + const style = group[styleName]; - options.maxBusyTries = options.maxBusyTries || 3 - options.emfileWait = options.emfileWait || 1000 - if (options.glob === false) { - options.disableGlob = true - } - if (options.disableGlob !== true && glob === undefined) { - throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') - } - options.disableGlob = options.disableGlob || false - options.glob = options.glob || defaultGlobOpts -} + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; -const rimraf = (p, options, cb) => { - if (typeof options === 'function') { - cb = options - options = {} - } + group[styleName] = styles[styleName]; - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert.equal(typeof cb, 'function', 'rimraf: callback function required') - assert(options, 'rimraf: invalid options argument provided') - assert.equal(typeof options, 'object', 'rimraf: options should be object') + codes.set(style[0], style[1]); + } - defaults(options) + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); - let busyTries = 0 - let errState = null - let n = 0 + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } - const next = (er) => { - errState = errState || er - if (--n === 0) - cb(errState) - } + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; - const afterGlob = (er, results) => { - if (er) - return cb(er) + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; - n = results.length - if (n === 0) - return cb() + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; - results.forEach(p => { - const CB = (er) => { - if (er) { - if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && - busyTries < options.maxBusyTries) { - busyTries ++ - // try again, with the same exact callback as this one. - return setTimeout(() => rimraf_(p, options, CB), busyTries * 100) - } + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; - // this one won't happen if graceful-fs is used. - if (er.code === "EMFILE" && timeout < options.emfileWait) { - return setTimeout(() => rimraf_(p, options, CB), timeout ++) - } + for (let key of Object.keys(colorConvert)) { + if (typeof colorConvert[key] !== 'object') { + continue; + } - // already gone - if (er.code === "ENOENT") er = null - } + const suite = colorConvert[key]; - timeout = 0 - next(er) - } - rimraf_(p, options, CB) - }) - } + if (key === 'ansi16') { + key = 'ansi'; + } - if (options.disableGlob || !glob.hasMagic(p)) - return afterGlob(null, [p]) + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } - options.lstat(p, (er, stat) => { - if (!er) - return afterGlob(null, [p]) + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } - glob(p, options.glob, afterGlob) - }) + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + return styles; } -// Two possible strategies. -// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR -// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR -// -// Both result in an extra syscall when you guess wrong. However, there -// are likely far more normal files in the world than directories. This -// is based on the assumption that a the average number of files per -// directory is >= 1. -// -// If anyone ever complains about this, then I guess the strategy could -// be made configurable somehow. But until then, YAGNI. -const rimraf_ = (p, options, cb) => { - assert(p) - assert(options) - assert(typeof cb === 'function') +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); - // sunos lets the root user unlink directories, which is... weird. - // so we have to lstat here and make sure it's not a dir. - options.lstat(p, (er, st) => { - if (er && er.code === "ENOENT") - return cb(null) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(11)(module))) - // Windows can EPERM on stat. Life is suffering. - if (er && er.code === "EPERM" && isWindows) - fixWinEPERM(p, options, er, cb) +/***/ }), +/* 673 */ +/***/ (function(module, exports, __webpack_require__) { - if (st && st.isDirectory()) - return rmdir(p, options, er, cb) +"use strict"; - options.unlink(p, er => { - if (er) { - if (er.code === "ENOENT") - return cb(null) - if (er.code === "EPERM") - return (isWindows) - ? fixWinEPERM(p, options, er, cb) - : rmdir(p, options, er, cb) - if (er.code === "EISDIR") - return rmdir(p, options, er, cb) - } - return cb(er) - }) - }) -} +const os = __webpack_require__(364); +const hasFlag = __webpack_require__(394); -const fixWinEPERM = (p, options, er, cb) => { - assert(p) - assert(options) - assert(typeof cb === 'function') - if (er) - assert(er instanceof Error) +const env = process.env; - options.chmod(p, 0o666, er2 => { - if (er2) - cb(er2.code === "ENOENT" ? null : er) - else - options.stat(p, (er3, stats) => { - if (er3) - cb(er3.code === "ENOENT" ? null : er) - else if (stats.isDirectory()) - rmdir(p, options, er, cb) - else - options.unlink(p, cb) - }) - }) +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; } -const fixWinEPERMSync = (p, options, er) => { - assert(p) - assert(options) - if (er) - assert(er instanceof Error) +function translateLevel(level) { + if (level === 0) { + return false; + } - try { - options.chmodSync(p, 0o666) - } catch (er2) { - if (er2.code === "ENOENT") - return - else - throw er - } + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} - let stats - try { - stats = options.statSync(p) - } catch (er3) { - if (er3.code === "ENOENT") - return - else - throw er - } +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } - if (stats.isDirectory()) - rmdirSync(p, options, er) - else - options.unlinkSync(p) -} + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } -const rmdir = (p, options, originalEr, cb) => { - assert(p) - assert(options) - if (originalEr) - assert(originalEr instanceof Error) - assert(typeof cb === 'function') + if (hasFlag('color=256')) { + return 2; + } - // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) - // if we guessed wrong, and it's not a directory, then - // raise the original error. - options.rmdir(p, er => { - if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) - rmkids(p, options, cb) - else if (er && er.code === "ENOTDIR") - cb(originalEr) - else - cb(er) - }) -} + if (stream && !stream.isTTY && forceColor !== true) { + // VS code debugger doesn't have isTTY set + if (env.VSCODE_PID) { + return 1; + } + return 0; + } -const rmkids = (p, options, cb) => { - assert(p) - assert(options) - assert(typeof cb === 'function') + const min = forceColor ? 1 : 0; - options.readdir(p, (er, files) => { - if (er) - return cb(er) - let n = files.length - if (n === 0) - return options.rmdir(p, cb) - let errState - files.forEach(f => { - rimraf(path.join(p, f), options, er => { - if (errState) - return - if (er) - return cb(errState = er) - if (--n === 0) - options.rmdir(p, cb) - }) - }) - }) -} + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(process.versions.node.split('.')[0]) >= 8 && + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } -// this looks simpler, and is strictly *faster*, but will -// tie up the JavaScript thread and fail on excessively -// deep directory trees. -const rimrafSync = (p, options) => { - options = options || {} - defaults(options) + return 1; + } - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert(options, 'rimraf: missing options') - assert.equal(typeof options, 'object', 'rimraf: options should be object') + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } - let results + return min; + } - if (options.disableGlob || !glob.hasMagic(p)) { - results = [p] - } else { - try { - options.lstatSync(p) - results = [p] - } catch (er) { - results = glob.sync(p, options.glob) - } - } + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } - if (!results.length) - return + if (env.COLORTERM === 'truecolor') { + return 3; + } - for (let i = 0; i < results.length; i++) { - const p = results[i] + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - let st - try { - st = options.lstatSync(p) - } catch (er) { - if (er.code === "ENOENT") - return + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } - // Windows can EPERM on stat. Life is suffering. - if (er.code === "EPERM" && isWindows) - fixWinEPERMSync(p, options, er) - } + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } - try { - // sunos lets the root user unlink directories, which is... weird. - if (st && st.isDirectory()) - rmdirSync(p, options, null) - else - options.unlinkSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "EPERM") - return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) - if (er.code !== "EISDIR") - throw er + if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } - rmdirSync(p, options, er) - } - } -} + if ('COLORTERM' in env) { + return 1; + } -const rmdirSync = (p, options, originalEr) => { - assert(p) - assert(options) - if (originalEr) - assert(originalEr instanceof Error) + if (env.TERM === 'dumb') { + return min; + } - try { - options.rmdirSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "ENOTDIR") - throw originalEr - if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") - rmkidsSync(p, options) - } + return min; } -const rmkidsSync = (p, options) => { - assert(p) - assert(options) - options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) - - // We only end up here once we got ENOTEMPTY at least once, and - // at this point, we are guaranteed to have removed all the kids. - // So, we know that it won't be ENOENT or ENOTDIR or anything else. - // try really hard to delete stuff on windows, because it has a - // PROFOUNDLY annoying habit of not closing handles promptly when - // files are deleted, resulting in spurious ENOTEMPTY errors. - const retries = isWindows ? 100 : 1 - let i = 0 - do { - let threw = true - try { - const ret = options.rmdirSync(p, options) - threw = false - return ret - } finally { - if (++i < retries && threw) - continue - } - } while (true) +function getSupportLevel(stream) { + const level = supportsColor(stream); + return translateLevel(level); } -module.exports = rimraf -rimraf.sync = rimrafSync +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) +}; /***/ }), -/* 671 */ +/* 674 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const AggregateError = __webpack_require__(672); - -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 TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; +const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; +const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; +const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; - const ret = []; - const errors = []; - const iterator = iterable[Symbol.iterator](); - let isRejected = false; - let isIterableDone = false; - let resolvingCount = 0; - let currentIndex = 0; +const ESCAPES = new Map([ + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['b', '\b'], + ['f', '\f'], + ['v', '\v'], + ['0', '\0'], + ['\\', '\\'], + ['e', '\u001B'], + ['a', '\u0007'] +]); - const next = () => { - if (isRejected) { - return; - } +function unescape(c) { + if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } - const nextItem = iterator.next(); - const i = currentIndex; - currentIndex++; + return ESCAPES.get(c) || c; +} - if (nextItem.done) { - isIterableDone = true; +function parseArguments(name, args) { + const results = []; + const chunks = args.trim().split(/\s*,\s*/g); + let matches; - if (resolvingCount === 0) { - if (!stopOnError && errors.length !== 0) { - reject(new AggregateError(errors)); - } else { - resolve(ret); - } - } + for (const chunk of chunks) { + if (!isNaN(chunk)) { + results.push(Number(chunk)); + } else if ((matches = chunk.match(STRING_REGEX))) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } - return; - } + return results; +} - resolvingCount++; +function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; - (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(); - } - } - })(); - }; + const results = []; + let matches; - for (let i = 0; i < concurrency; i++) { - next(); + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; - if (isIterableDone) { - break; - } + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); } - }); -}; - - -/***/ }), -/* 672 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; + } -const indentString = __webpack_require__(673); -const cleanStack = __webpack_require__(674); + return results; +} -const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); +function buildStyle(chalk, styles) { + const enabled = {}; -class AggregateError extends Error { - constructor(errors) { - if (!Array.isArray(errors)) { - throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); } + } - errors = [...errors].map(error => { - if (error instanceof Error) { - return error; + let current = chalk; + for (const styleName of Object.keys(enabled)) { + if (Array.isArray(enabled[styleName])) { + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); } - 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); + if (enabled[styleName].length > 0) { + current = current[styleName].apply(current, enabled[styleName]); + } else { + current = current[styleName]; } + } + } - return new Error(error); - }); - - 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); + return current; +} - this.name = 'AggregateError'; +module.exports = (chalk, tmp) => { + const styles = []; + const chunks = []; + let chunk = []; - Object.defineProperty(this, '_errors', {value: errors}); - } + // eslint-disable-next-line max-params + tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { + if (escapeChar) { + chunk.push(unescape(escapeChar)); + } else if (style) { + const str = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); + styles.push({inverse, styles: parseStyle(style)}); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } - * [Symbol.iterator]() { - for (const error of this._errors) { - yield error; + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(chr); } + }); + + chunks.push(chunk.join('')); + + if (styles.length > 0) { + const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMsg); } -} -module.exports = AggregateError; + return chunks.join(''); +}; /***/ }), -/* 673 */ +/* 675 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +const restoreCursor = __webpack_require__(676); -module.exports = (string, count = 1, options) => { - options = { - indent: ' ', - includeEmptyLines: false, - ...options - }; +let hidden = false; - if (typeof string !== 'string') { - throw new TypeError( - `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` - ); - } +exports.show = stream => { + const s = stream || process.stderr; - if (typeof count !== 'number') { - throw new TypeError( - `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` - ); + if (!s.isTTY) { + return; } - if (typeof options.indent !== 'string') { - throw new TypeError( - `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` - ); - } + hidden = false; + s.write('\u001b[?25h'); +}; - if (count === 0) { - return string; +exports.hide = stream => { + const s = stream || process.stderr; + + if (!s.isTTY) { + return; } - const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; + restoreCursor(); + hidden = true; + s.write('\u001b[?25l'); +}; - return string.replace(regex, options.indent.repeat(count)); +exports.toggle = (force, stream) => { + if (force !== undefined) { + hidden = force; + } + + if (hidden) { + exports.show(stream); + } else { + exports.hide(stream); + } }; /***/ }), -/* 674 */ +/* 676 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const os = __webpack_require__(11); - -const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/; -const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; -const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir(); - -module.exports = (stack, options) => { - options = Object.assign({pretty: false}, options); - - return stack.replace(/\\/g, '/') - .split('\n') - .filter(line => { - const pathMatches = line.match(extractPathRegex); - if (pathMatches === null || !pathMatches[1]) { - return true; - } - - const match = pathMatches[1]; - - // Electron - if ( - match.includes('.app/Contents/Resources/electron.asar') || - match.includes('.app/Contents/Resources/default_app.asar') - ) { - return false; - } - - return !pathRegex.test(match); - }) - .filter(line => line.trim() !== '') - .map(line => { - if (options.pretty) { - return line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~'))); - } +const onetime = __webpack_require__(677); +const signalExit = __webpack_require__(370); - return line; - }) - .join('\n'); -}; +module.exports = onetime(() => { + signalExit(() => { + process.stderr.write('\u001b[?25h'); + }, {alwaysLast: true}); +}); /***/ }), -/* 675 */ +/* 677 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const chalk = __webpack_require__(676); -const cliCursor = __webpack_require__(680); -const cliSpinners = __webpack_require__(684); -const logSymbols = __webpack_require__(565); +const mimicFn = __webpack_require__(678); -class Ora { - constructor(options) { - if (typeof options === 'string') { - options = { - text: options - }; - } +module.exports = (fn, opts) => { + // TODO: Remove this in v3 + if (opts === true) { + throw new TypeError('The second argument is now an options object'); + } - this.options = Object.assign({ - text: '', - color: 'cyan', - stream: process.stderr - }, options); + if (typeof fn !== 'function') { + throw new TypeError('Expected a function'); + } - const sp = this.options.spinner; - this.spinner = typeof sp === 'object' ? sp : (process.platform === 'win32' ? cliSpinners.line : (cliSpinners[sp] || cliSpinners.dots)); // eslint-disable-line no-nested-ternary + opts = opts || {}; - if (this.spinner.frames === undefined) { - throw new Error('Spinner must define `frames`'); - } + let ret; + let called = false; + const fnName = fn.displayName || fn.name || ''; - this.text = this.options.text; - this.color = this.options.color; - this.interval = this.options.interval || this.spinner.interval || 100; - this.stream = this.options.stream; - this.id = null; - this.frameIndex = 0; - this.enabled = typeof this.options.enabled === 'boolean' ? this.options.enabled : ((this.stream && this.stream.isTTY) && !process.env.CI); - } - frame() { - const frames = this.spinner.frames; - let frame = frames[this.frameIndex]; + const onetime = function () { + if (called) { + if (opts.throw === true) { + throw new Error(`Function \`${fnName}\` can only be called once`); + } - if (this.color) { - frame = chalk[this.color](frame); + return ret; } - this.frameIndex = ++this.frameIndex % frames.length; + called = true; + ret = fn.apply(this, arguments); + fn = null; - return frame + ' ' + this.text; - } - clear() { - if (!this.enabled) { - return this; - } + return ret; + }; - this.stream.clearLine(); - this.stream.cursorTo(0); + mimicFn(onetime, fn); - return this; - } - render() { - this.clear(); - this.stream.write(this.frame()); + return onetime; +}; - return this; - } - start(text) { - if (text) { - this.text = text; - } - if (!this.enabled || this.id) { - return this; - } +/***/ }), +/* 678 */ +/***/ (function(module, exports, __webpack_require__) { - cliCursor.hide(this.stream); - this.render(); - this.id = setInterval(this.render.bind(this), this.interval); +"use strict"; - return this; +module.exports = (to, from) => { + // TODO: use `Reflect.ownKeys()` when targeting Node.js 6 + for (const prop of Object.getOwnPropertyNames(from).concat(Object.getOwnPropertySymbols(from))) { + Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); } - stop() { - if (!this.enabled) { - return this; - } - clearInterval(this.id); - this.id = null; - this.frameIndex = 0; - this.clear(); - cliCursor.show(this.stream); + return to; +}; - return this; - } - succeed(text) { - return this.stopAndPersist({symbol: logSymbols.success, text}); - } - fail(text) { - return this.stopAndPersist({symbol: logSymbols.error, text}); - } - warn(text) { - return this.stopAndPersist({symbol: logSymbols.warning, text}); - } - info(text) { - return this.stopAndPersist({symbol: logSymbols.info, text}); - } - stopAndPersist(options) { - if (!this.enabled) { - return this; - } - // Legacy argument - // TODO: Deprecate sometime in the future - if (typeof options === 'string') { - options = { - symbol: options - }; - } +/***/ }), +/* 679 */ +/***/ (function(module, exports, __webpack_require__) { - options = options || {}; +"use strict"; - this.stop(); - this.stream.write(`${options.symbol || ' '} ${options.text || this.text}\n`); +module.exports = __webpack_require__(680); - return this; - } -} -module.exports = function (opts) { - return new Ora(opts); -}; +/***/ }), +/* 680 */ +/***/ (function(module) { -module.exports.promise = (action, options) => { - if (typeof action.then !== 'function') { - throw new TypeError('Parameter `action` must be a Promise'); - } +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\":[\"⢀⠀\",\"⡀⠀\",\"⠄⠀\",\"⢂⠀\",\"⡂⠀\",\"⠅⠀\",\"⢃⠀\",\"⡃⠀\",\"⠍⠀\",\"⢋⠀\",\"⡋⠀\",\"⠍⠁\",\"⢋⠁\",\"⡋⠁\",\"⠍⠉\",\"⠋⠉\",\"⠋⠉\",\"⠉⠙\",\"⠉⠙\",\"⠉⠩\",\"⠈⢙\",\"⠈⡙\",\"⢈⠩\",\"⡀⢙\",\"⠄⡙\",\"⢂⠩\",\"⡂⢘\",\"⠅⡘\",\"⢃⠨\",\"⡃⢐\",\"⠍⡐\",\"⢋⠠\",\"⡋⢀\",\"⠍⡁\",\"⢋⠁\",\"⡋⠁\",\"⠍⠉\",\"⠋⠉\",\"⠋⠉\",\"⠉⠙\",\"⠉⠙\",\"⠉⠩\",\"⠈⢙\",\"⠈⡙\",\"⠈⠩\",\"⠀⢙\",\"⠀⡙\",\"⠀⠩\",\"⠀⢘\",\"⠀⡘\",\"⠀⠨\",\"⠀⢐\",\"⠀⡐\",\"⠀⠠\",\"⠀⢀\",\"⠀⡀\"]},\"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\":[\"🌍 \",\"🌎 \",\"🌏 \"]},\"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\":[\"🌲\",\"🎄\"]}}"); - const spinner = new Ora(options); - spinner.start(); +/***/ }), +/* 681 */ +/***/ (function(module, exports, __webpack_require__) { - action.then( - () => { - spinner.succeed(); - }, - () => { - spinner.fail(); - } - ); +"use strict"; - return spinner; +const chalk = __webpack_require__(682); + +const isSupported = process.platform !== 'win32' || process.env.CI || process.env.TERM === 'xterm-256color'; + +const main = { + info: chalk.blue('ℹ'), + success: chalk.green('✔'), + warning: chalk.yellow('⚠'), + error: chalk.red('✖') +}; + +const fallbacks = { + info: chalk.blue('i'), + success: chalk.green('√'), + warning: chalk.yellow('‼'), + error: chalk.red('×') }; +module.exports = isSupported ? main : fallbacks; + /***/ }), -/* 676 */ +/* 682 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const escapeStringRegexp = __webpack_require__(3); -const ansiStyles = __webpack_require__(677); -const stdoutColor = __webpack_require__(678).stdout; +const escapeStringRegexp = __webpack_require__(387); +const ansiStyles = __webpack_require__(683); +const stdoutColor = __webpack_require__(684).stdout; -const template = __webpack_require__(679); +const template = __webpack_require__(685); const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); @@ -77658,12 +77851,12 @@ module.exports.default = module.exports; // For TypeScript /***/ }), -/* 677 */ +/* 683 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(module) { -const colorConvert = __webpack_require__(6); +const colorConvert = __webpack_require__(389); const wrapAnsi16 = (fn, offset) => function () { const code = fn.apply(colorConvert, arguments); @@ -77828,16 +78021,16 @@ Object.defineProperty(module, 'exports', { get: assembleStyles }); -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(5)(module))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(11)(module))) /***/ }), -/* 678 */ +/* 684 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const os = __webpack_require__(11); -const hasFlag = __webpack_require__(12); +const os = __webpack_require__(364); +const hasFlag = __webpack_require__(394); const env = process.env; @@ -77973,7 +78166,7 @@ module.exports = { /***/ }), -/* 679 */ +/* 685 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -78107,145 +78300,6 @@ module.exports = (chalk, tmp) => { }; -/***/ }), -/* 680 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const restoreCursor = __webpack_require__(681); - -let hidden = false; - -exports.show = stream => { - const s = stream || process.stderr; - - if (!s.isTTY) { - return; - } - - hidden = false; - s.write('\u001b[?25h'); -}; - -exports.hide = stream => { - const s = stream || process.stderr; - - if (!s.isTTY) { - return; - } - - restoreCursor(); - hidden = true; - s.write('\u001b[?25l'); -}; - -exports.toggle = (force, stream) => { - if (force !== undefined) { - hidden = force; - } - - if (hidden) { - exports.show(stream); - } else { - exports.hide(stream); - } -}; - - -/***/ }), -/* 681 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const onetime = __webpack_require__(682); -const signalExit = __webpack_require__(397); - -module.exports = onetime(() => { - signalExit(() => { - process.stderr.write('\u001b[?25h'); - }, {alwaysLast: true}); -}); - - -/***/ }), -/* 682 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const mimicFn = __webpack_require__(683); - -module.exports = (fn, opts) => { - // TODO: Remove this in v3 - if (opts === true) { - throw new TypeError('The second argument is now an options object'); - } - - if (typeof fn !== 'function') { - throw new TypeError('Expected a function'); - } - - opts = opts || {}; - - let ret; - let called = false; - const fnName = fn.displayName || fn.name || ''; - - const onetime = function () { - if (called) { - if (opts.throw === true) { - throw new Error(`Function \`${fnName}\` can only be called once`); - } - - return ret; - } - - called = true; - ret = fn.apply(this, arguments); - fn = null; - - return ret; - }; - - mimicFn(onetime, fn); - - return onetime; -}; - - -/***/ }), -/* 683 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -module.exports = (to, from) => { - // TODO: use `Reflect.ownKeys()` when targeting Node.js 6 - for (const prop of Object.getOwnPropertyNames(from).concat(Object.getOwnPropertySymbols(from))) { - Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); - } - - return to; -}; - - -/***/ }), -/* 684 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -module.exports = __webpack_require__(685); - - -/***/ }), -/* 685 */ -/***/ (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\":[\"⢀⠀\",\"⡀⠀\",\"⠄⠀\",\"⢂⠀\",\"⡂⠀\",\"⠅⠀\",\"⢃⠀\",\"⡃⠀\",\"⠍⠀\",\"⢋⠀\",\"⡋⠀\",\"⠍⠁\",\"⢋⠁\",\"⡋⠁\",\"⠍⠉\",\"⠋⠉\",\"⠋⠉\",\"⠉⠙\",\"⠉⠙\",\"⠉⠩\",\"⠈⢙\",\"⠈⡙\",\"⢈⠩\",\"⡀⢙\",\"⠄⡙\",\"⢂⠩\",\"⡂⢘\",\"⠅⡘\",\"⢃⠨\",\"⡃⢐\",\"⠍⡐\",\"⢋⠠\",\"⡋⢀\",\"⠍⡁\",\"⢋⠁\",\"⡋⠁\",\"⠍⠉\",\"⠋⠉\",\"⠋⠉\",\"⠉⠙\",\"⠉⠙\",\"⠉⠩\",\"⠈⢙\",\"⠈⡙\",\"⠈⠩\",\"⠀⢙\",\"⠀⡙\",\"⠀⠩\",\"⠀⢘\",\"⠀⡘\",\"⠀⠨\",\"⠀⢐\",\"⠀⡐\",\"⠀⠠\",\"⠀⢀\",\"⠀⡀\"]},\"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\":[\"🌍 \",\"🌎 \",\"🌏 \"]},\"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\":[\"🌲\",\"🎄\"]}}"); - /***/ }), /* 686 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { @@ -78253,9 +78307,8 @@ module.exports = JSON.parse("{\"dots\":{\"interval\":80,\"frames\":[\"⠋\",\" "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RunCommand", function() { return RunCommand; }); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(chalk__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(34); +/* harmony import */ var _utils_errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(516); +/* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(500); /* harmony import */ var _utils_parallelize__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(501); /* harmony import */ var _utils_projects__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(502); /* @@ -78290,16 +78343,18 @@ const RunCommand = { const batchedProjects = Object(_utils_projects__WEBPACK_IMPORTED_MODULE_3__["topologicallyBatchProjects"])(projects, projectGraph); if (extraArgs.length === 0) { - _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.red.bold('\nNo script specified')); - process.exit(1); + throw new _utils_errors__WEBPACK_IMPORTED_MODULE_0__["CliError"]('No script specified'); } const scriptName = extraArgs[0]; const scriptArgs = extraArgs.slice(1); - _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.bold(`\nRunning script [${chalk__WEBPACK_IMPORTED_MODULE_0___default.a.green(scriptName)}] in batched topological order\n`)); - await Object(_utils_parallelize__WEBPACK_IMPORTED_MODULE_2__["parallelizeBatches"])(batchedProjects, async pkg => { - if (pkg.hasScript(scriptName)) { - await pkg.runScriptStreaming(scriptName, scriptArgs); + await Object(_utils_parallelize__WEBPACK_IMPORTED_MODULE_2__["parallelizeBatches"])(batchedProjects, async project => { + if (project.hasScript(scriptName)) { + _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].info(`[${project.name}] running "${scriptName}" script`); + await project.runScriptStreaming(scriptName, { + args: scriptArgs + }); + _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].success(`[${project.name}] complete`); } }); } @@ -78313,9 +78368,8 @@ const RunCommand = { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WatchCommand", function() { return WatchCommand; }); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(chalk__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(34); +/* harmony import */ var _utils_errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(516); +/* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(500); /* harmony import */ var _utils_parallelize__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(501); /* harmony import */ var _utils_projects__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(502); /* harmony import */ var _utils_watch__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(688); @@ -78378,12 +78432,11 @@ const WatchCommand = { } if (projectsToWatch.size === 0) { - _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.red(`\nThere are no projects to watch found. Make sure that projects define 'kbn:watch' script in 'package.json'.\n`)); - return; + throw new _utils_errors__WEBPACK_IMPORTED_MODULE_0__["CliError"](`There are no projects to watch found. Make sure that projects define 'kbn:watch' script in 'package.json'.`); } const projectNames = Array.from(projectsToWatch.keys()); - _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.bold(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.green(`Running ${watchScriptName} scripts for [${projectNames.join(', ')}].`))); // Kibana should always be run the last, so we don't rely on automatic + _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].info(`Running ${watchScriptName} scripts for [${projectNames.join(', ')}].`); // Kibana should always be run the last, so we don't rely on automatic // topological batching and push it to the last one-entry batch manually. const shouldWatchKibanaProject = projectsToWatch.delete(kibanaProjectName); @@ -78394,8 +78447,10 @@ const WatchCommand = { } await Object(_utils_parallelize__WEBPACK_IMPORTED_MODULE_2__["parallelizeBatches"])(batchedProjects, async pkg => { - const completionHint = await Object(_utils_watch__WEBPACK_IMPORTED_MODULE_4__["waitUntilWatchIsReady"])(pkg.runScriptStreaming(watchScriptName).stdout); - _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.bold(`[${chalk__WEBPACK_IMPORTED_MODULE_0___default.a.green(pkg.name)}] Initial build completed (${completionHint}).`)); + const completionHint = await Object(_utils_watch__WEBPACK_IMPORTED_MODULE_4__["waitUntilWatchIsReady"])(pkg.runScriptStreaming(watchScriptName, { + debug: false + }).stdout); + _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].success(`[${pkg.name}] Initial build completed (${completionHint}).`); }); } @@ -78408,8 +78463,8 @@ const WatchCommand = { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "waitUntilWatchIsReady", function() { return waitUntilWatchIsReady; }); -/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(169); -/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(270); +/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(140); +/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(241); /* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with @@ -78482,17 +78537,11 @@ function waitUntilWatchIsReady(stream, opts = {}) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runCommand", function() { return runCommand; }); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(chalk__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var indent_string__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(690); -/* harmony import */ var indent_string__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(indent_string__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var wrap_ansi__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(691); -/* harmony import */ var wrap_ansi__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(wrap_ansi__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _utils_errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(516); -/* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(34); -/* harmony import */ var _utils_projects__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(502); -/* harmony import */ var _utils_projects_tree__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(698); -/* harmony import */ var _utils_kibana__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(699); +/* harmony import */ var _utils_errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(516); +/* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(500); +/* harmony import */ var _utils_projects__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(502); +/* harmony import */ var _utils_projects_tree__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(690); +/* harmony import */ var _utils_kibana__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(691); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } @@ -78522,13 +78571,10 @@ function _defineProperty(obj, key, value) { if (key in obj) { Object.definePrope - - - async function runCommand(command, config) { try { - _utils_log__WEBPACK_IMPORTED_MODULE_4__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.bold(`Running [${chalk__WEBPACK_IMPORTED_MODULE_0___default.a.green(command.name)}] command from [${chalk__WEBPACK_IMPORTED_MODULE_0___default.a.yellow(config.rootPath)}]:\n`)); - const kbn = await _utils_kibana__WEBPACK_IMPORTED_MODULE_7__["Kibana"].loadFrom(config.rootPath); + _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].debug(`Running [${command.name}] command from [${config.rootPath}]`); + const kbn = await _utils_kibana__WEBPACK_IMPORTED_MODULE_4__["Kibana"].loadFrom(config.rootPath); const projects = kbn.getFilteredProjects({ skipKibanaPlugins: Boolean(config.options['skip-kibana-plugins']), ossOnly: Boolean(config.options.oss), @@ -78537,34 +78583,31 @@ async function runCommand(command, config) { }); if (projects.size === 0) { - _utils_log__WEBPACK_IMPORTED_MODULE_4__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.red(`There are no projects found. Double check project name(s) in '-i/--include' and '-e/--exclude' filters.\n`)); + _utils_log__WEBPACK_IMPORTED_MODULE_1__["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_5__["buildProjectGraph"])(projects); - _utils_log__WEBPACK_IMPORTED_MODULE_4__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.bold(`Found [${chalk__WEBPACK_IMPORTED_MODULE_0___default.a.green(projects.size.toString())}] projects:\n`)); - _utils_log__WEBPACK_IMPORTED_MODULE_4__["log"].write(Object(_utils_projects_tree__WEBPACK_IMPORTED_MODULE_6__["renderProjectsTree"])(config.rootPath, projects)); + const projectGraph = Object(_utils_projects__WEBPACK_IMPORTED_MODULE_2__["buildProjectGraph"])(projects); + _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].debug(`Found ${projects.size.toString()} projects`); + _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].debug(Object(_utils_projects_tree__WEBPACK_IMPORTED_MODULE_3__["renderProjectsTree"])(config.rootPath, projects)); await command.run(projects, projectGraph, _objectSpread({}, config, { kbn })); - } catch (e) { - _utils_log__WEBPACK_IMPORTED_MODULE_4__["log"].write(chalk__WEBPACK_IMPORTED_MODULE_0___default.a.bold.red(`\n[${command.name}] failed:\n`)); + } catch (error) { + _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].error(`[${command.name}] failed:`); - if (e instanceof _utils_errors__WEBPACK_IMPORTED_MODULE_3__["CliError"]) { - const msg = chalk__WEBPACK_IMPORTED_MODULE_0___default.a.red(`CliError: ${e.message}\n`); - _utils_log__WEBPACK_IMPORTED_MODULE_4__["log"].write(wrap_ansi__WEBPACK_IMPORTED_MODULE_2___default()(msg, 80)); - const keys = Object.keys(e.meta); + if (error instanceof _utils_errors__WEBPACK_IMPORTED_MODULE_0__["CliError"]) { + _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].error(error.message); + const metaOutput = Object.entries(error.meta).map(([key, value]) => `${key}: ${value}`).join('\n'); - if (keys.length > 0) { - const metaOutput = keys.map(key => { - const value = e.meta[key]; - return `${key}: ${value}`; - }); - _utils_log__WEBPACK_IMPORTED_MODULE_4__["log"].write('Additional debugging info:\n'); - _utils_log__WEBPACK_IMPORTED_MODULE_4__["log"].write(indent_string__WEBPACK_IMPORTED_MODULE_1___default()(metaOutput.join('\n'), 3)); + if (metaOutput) { + _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].info('Additional debugging info:\n'); + _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].indent(2); + _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].info(metaOutput); + _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].indent(-2); } } else { - _utils_log__WEBPACK_IMPORTED_MODULE_4__["log"].write(e.stack); + _utils_log__WEBPACK_IMPORTED_MODULE_1__["log"].error(error); } process.exit(1); @@ -78581,400 +78624,14 @@ function toArray(value) { /***/ }), /* 690 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -module.exports = (str, count, opts) => { - // Support older versions: use the third parameter as options.indent - // TODO: Remove the workaround in the next major version - const options = typeof opts === 'object' ? Object.assign({indent: ' '}, opts) : {indent: opts || ' '}; - count = count === undefined ? 1 : count; - - if (typeof str !== 'string') { - throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof str}\``); - } - - 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 str; - } - - const regex = options.includeEmptyLines ? /^/mg : /^(?!\s*$)/mg; - return str.replace(regex, options.indent.repeat(count)); -} -; - - -/***/ }), -/* 691 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const stringWidth = __webpack_require__(692); -const stripAnsi = __webpack_require__(696); - -const ESCAPES = new Set([ - '\u001B', - '\u009B' -]); - -const END_CODE = 39; - -const ESCAPE_CODES = new Map([ - [0, 0], - [1, 22], - [2, 22], - [3, 23], - [4, 24], - [7, 27], - [8, 28], - [9, 29], - [30, 39], - [31, 39], - [32, 39], - [33, 39], - [34, 39], - [35, 39], - [36, 39], - [37, 39], - [90, 39], - [40, 49], - [41, 49], - [42, 49], - [43, 49], - [44, 49], - [45, 49], - [46, 49], - [47, 49] -]); - -const wrapAnsi = code => `${ESCAPES.values().next().value}[${code}m`; - -// Calculate the length of words split on ' ', ignoring -// the extra characters added by ansi escape codes -const wordLengths = str => str.split(' ').map(s => stringWidth(s)); - -// Wrap a long word across multiple rows -// Ansi escape codes do not count towards length -const wrapWord = (rows, word, cols) => { - const arr = Array.from(word); - - let insideEscape = false; - let visible = stringWidth(stripAnsi(rows[rows.length - 1])); - - for (const item of arr.entries()) { - const i = item[0]; - const char = item[1]; - const charLength = stringWidth(char); - - if (visible + charLength <= cols) { - rows[rows.length - 1] += char; - } else { - rows.push(char); - visible = 0; - } - - if (ESCAPES.has(char)) { - insideEscape = true; - } else if (insideEscape && char === 'm') { - insideEscape = false; - continue; - } - - if (insideEscape) { - continue; - } - - visible += charLength; - - if (visible === cols && i < arr.length - 1) { - rows.push(''); - visible = 0; - } - } - - // It's possible that the last row we copy over is only - // ansi escape characters, handle this edge-case - if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { - rows[rows.length - 2] += rows.pop(); - } -}; - -// The wrap-ansi module can be invoked -// in either 'hard' or 'soft' wrap mode -// -// 'hard' will never allow a string to take up more -// than cols characters -// -// 'soft' allows long words to expand past the column length -const exec = (str, cols, opts) => { - const options = opts || {}; - - if (str.trim() === '') { - return options.trim === false ? str : str.trim(); - } - - let pre = ''; - let ret = ''; - let escapeCode; - - const lengths = wordLengths(str); - const words = str.split(' '); - const rows = ['']; - - for (const item of Array.from(words).entries()) { - const i = item[0]; - const word = item[1]; - - rows[rows.length - 1] = options.trim === false ? rows[rows.length - 1] : rows[rows.length - 1].trim(); - let rowLength = stringWidth(rows[rows.length - 1]); - - if (rowLength || word === '') { - if (rowLength === cols && options.wordWrap === false) { - // If we start with a new word but the current row length equals the length of the columns, add a new row - rows.push(''); - rowLength = 0; - } - - rows[rows.length - 1] += ' '; - rowLength++; - } - - // In 'hard' wrap mode, the length of a line is - // never allowed to extend past 'cols' - if (lengths[i] > cols && options.hard) { - if (rowLength) { - rows.push(''); - } - wrapWord(rows, word, cols); - continue; - } - - if (rowLength + lengths[i] > cols && rowLength > 0) { - if (options.wordWrap === false && rowLength < cols) { - wrapWord(rows, word, cols); - continue; - } - - rows.push(''); - } - - if (rowLength + lengths[i] > cols && options.wordWrap === false) { - wrapWord(rows, word, cols); - continue; - } - - rows[rows.length - 1] += word; - } - - pre = rows.map(r => options.trim === false ? r : r.trim()).join('\n'); - - for (const item of Array.from(pre).entries()) { - const i = item[0]; - const char = item[1]; - - ret += char; - - if (ESCAPES.has(char)) { - const code = parseFloat(/\d[^m]*/.exec(pre.slice(i, i + 4))); - escapeCode = code === END_CODE ? null : code; - } - - const code = ESCAPE_CODES.get(Number(escapeCode)); - - if (escapeCode && code) { - if (pre[i + 1] === '\n') { - ret += wrapAnsi(code); - } else if (char === '\n') { - ret += wrapAnsi(escapeCode); - } - } - } - - return ret; -}; - -// For each newline, invoke the method separately -module.exports = (str, cols, opts) => { - return String(str) - .normalize() - .split('\n') - .map(line => exec(line, cols, opts)) - .join('\n'); -}; - - -/***/ }), -/* 692 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const stripAnsi = __webpack_require__(693); -const isFullwidthCodePoint = __webpack_require__(695); - -module.exports = str => { - if (typeof str !== 'string' || str.length === 0) { - return 0; - } - - str = stripAnsi(str); - - let width = 0; - - for (let i = 0; i < str.length; i++) { - const code = str.codePointAt(i); - - // Ignore control characters - if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { - continue; - } - - // Ignore combining characters - if (code >= 0x300 && code <= 0x36F) { - continue; - } - - // Surrogates - if (code > 0xFFFF) { - i++; - } - - width += isFullwidthCodePoint(code) ? 2 : 1; - } - - return width; -}; - - -/***/ }), -/* 693 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const ansiRegex = __webpack_require__(694); - -module.exports = input => typeof input === 'string' ? input.replace(ansiRegex(), '') : input; - - -/***/ }), -/* 694 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -module.exports = () => { - const pattern = [ - '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)', - '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))' - ].join('|'); - - return new RegExp(pattern, 'g'); -}; - - -/***/ }), -/* 695 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -/* eslint-disable yoda */ -module.exports = x => { - if (Number.isNaN(x)) { - return false; - } - - // code points are derived from: - // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt - if ( - x >= 0x1100 && ( - x <= 0x115f || // Hangul Jamo - x === 0x2329 || // LEFT-POINTING ANGLE BRACKET - x === 0x232a || // RIGHT-POINTING ANGLE BRACKET - // CJK Radicals Supplement .. Enclosed CJK Letters and Months - (0x2e80 <= x && x <= 0x3247 && x !== 0x303f) || - // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A - (0x3250 <= x && x <= 0x4dbf) || - // CJK Unified Ideographs .. Yi Radicals - (0x4e00 <= x && x <= 0xa4c6) || - // Hangul Jamo Extended-A - (0xa960 <= x && x <= 0xa97c) || - // Hangul Syllables - (0xac00 <= x && x <= 0xd7a3) || - // CJK Compatibility Ideographs - (0xf900 <= x && x <= 0xfaff) || - // Vertical Forms - (0xfe10 <= x && x <= 0xfe19) || - // CJK Compatibility Forms .. Small Form Variants - (0xfe30 <= x && x <= 0xfe6b) || - // Halfwidth and Fullwidth Forms - (0xff01 <= x && x <= 0xff60) || - (0xffe0 <= x && x <= 0xffe6) || - // Kana Supplement - (0x1b000 <= x && x <= 0x1b001) || - // Enclosed Ideographic Supplement - (0x1f200 <= x && x <= 0x1f251) || - // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane - (0x20000 <= x && x <= 0x3fffd) - ) - ) { - return true; - } - - return false; -}; - - -/***/ }), -/* 696 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const ansiRegex = __webpack_require__(697); - -module.exports = input => typeof input === 'string' ? input.replace(ansiRegex(), '') : input; - - -/***/ }), -/* 697 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -module.exports = () => { - const pattern = [ - '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)', - '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))' - ].join('|'); - - return new RegExp(pattern, 'g'); -}; - - -/***/ }), -/* 698 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "renderProjectsTree", function() { return renderProjectsTree; }); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); +/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(386); /* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(chalk__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16); +/* 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__); /* * Licensed to Elasticsearch B.V. under one or more contributor @@ -79119,20 +78776,20 @@ function addProjectToTree(tree, pathParts, project) { } /***/ }), -/* 699 */ +/* 691 */ /***/ (function(module, __webpack_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__(16); +/* 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 multimatch__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(700); +/* harmony import */ var multimatch__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(692); /* harmony import */ var multimatch__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(multimatch__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var is_path_inside__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(704); +/* harmony import */ var is_path_inside__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(696); /* harmony import */ var is_path_inside__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(is_path_inside__WEBPACK_IMPORTED_MODULE_2__); /* harmony import */ var _projects__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(502); -/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(579); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(574); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } @@ -79273,15 +78930,15 @@ class Kibana { } /***/ }), -/* 700 */ +/* 692 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; const minimatch = __webpack_require__(506); -const arrayUnion = __webpack_require__(701); -const arrayDiffer = __webpack_require__(702); -const arrify = __webpack_require__(703); +const arrayUnion = __webpack_require__(693); +const arrayDiffer = __webpack_require__(694); +const arrify = __webpack_require__(695); module.exports = (list, patterns, options = {}) => { list = arrify(list); @@ -79305,7 +78962,7 @@ module.exports = (list, patterns, options = {}) => { /***/ }), -/* 701 */ +/* 693 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -79317,7 +78974,7 @@ module.exports = (...arguments_) => { /***/ }), -/* 702 */ +/* 694 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -79332,7 +78989,7 @@ module.exports = arrayDiffer; /***/ }), -/* 703 */ +/* 695 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -79362,12 +79019,12 @@ module.exports = arrify; /***/ }), -/* 704 */ +/* 696 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const path = __webpack_require__(16); +const path = __webpack_require__(4); module.exports = (childPath, parentPath) => { childPath = path.resolve(childPath); @@ -79390,15 +79047,15 @@ module.exports = (childPath, parentPath) => { /***/ }), -/* 705 */ +/* 697 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony import */ var _build_production_projects__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(706); +/* harmony import */ var _build_production_projects__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(698); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "buildProductionProjects", function() { return _build_production_projects__WEBPACK_IMPORTED_MODULE_0__["buildProductionProjects"]; }); -/* harmony import */ var _prepare_project_dependencies__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(941); +/* harmony import */ var _prepare_project_dependencies__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(933); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "prepareExternalProjectDependencies", function() { return _prepare_project_dependencies__WEBPACK_IMPORTED_MODULE_1__["prepareExternalProjectDependencies"]; }); /* @@ -79423,21 +79080,21 @@ __webpack_require__.r(__webpack_exports__); /***/ }), -/* 706 */ +/* 698 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buildProductionProjects", function() { return buildProductionProjects; }); -/* harmony import */ var cpy__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(707); +/* harmony import */ var cpy__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(699); /* 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__(587); +/* harmony import */ var del__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(582); /* 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__(16); +/* 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__(579); -/* harmony import */ var _utils_fs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(20); -/* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(34); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(574); +/* harmony import */ var _utils_fs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(491); +/* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(500); /* harmony import */ var _utils_package_json__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(518); /* harmony import */ var _utils_projects__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(502); /* @@ -79475,7 +79132,7 @@ async function buildProductionProjects({ const projectGraph = Object(_utils_projects__WEBPACK_IMPORTED_MODULE_7__["buildProjectGraph"])(projects); const batchedProjects = Object(_utils_projects__WEBPACK_IMPORTED_MODULE_7__["topologicallyBatchProjects"])(projects, projectGraph); const projectNames = [...projects.values()].map(project => project.name); - _utils_log__WEBPACK_IMPORTED_MODULE_5__["log"].write(`Preparing production build for [${projectNames.join(', ')}]`); + _utils_log__WEBPACK_IMPORTED_MODULE_5__["log"].info(`Preparing production build for [${projectNames.join(', ')}]`); for (const batch of batchedProjects) { for (const project of batch) { @@ -79571,21 +79228,21 @@ async function copyToBuild(project, kibanaRoot, buildRoot) { } /***/ }), -/* 707 */ +/* 699 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const EventEmitter = __webpack_require__(399); -const path = __webpack_require__(16); -const os = __webpack_require__(11); -const pAll = __webpack_require__(708); -const arrify = __webpack_require__(710); -const globby = __webpack_require__(711); -const isGlob = __webpack_require__(605); -const cpFile = __webpack_require__(926); -const junk = __webpack_require__(938); -const CpyError = __webpack_require__(939); +const EventEmitter = __webpack_require__(373); +const path = __webpack_require__(4); +const os = __webpack_require__(364); +const pAll = __webpack_require__(700); +const arrify = __webpack_require__(702); +const globby = __webpack_require__(703); +const isGlob = __webpack_require__(600); +const cpFile = __webpack_require__(918); +const junk = __webpack_require__(930); +const CpyError = __webpack_require__(931); const defaultOptions = { ignoreJunk: true @@ -79704,12 +79361,12 @@ module.exports = (source, destination, { /***/ }), -/* 708 */ +/* 700 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const pMap = __webpack_require__(709); +const pMap = __webpack_require__(701); module.exports = (iterable, options) => pMap(iterable, element => element(), options); // TODO: Remove this for the next major release @@ -79717,7 +79374,7 @@ module.exports.default = module.exports; /***/ }), -/* 709 */ +/* 701 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -79796,7 +79453,7 @@ module.exports.default = pMap; /***/ }), -/* 710 */ +/* 702 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -79826,17 +79483,17 @@ module.exports = arrify; /***/ }), -/* 711 */ +/* 703 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const fs = __webpack_require__(23); -const arrayUnion = __webpack_require__(712); -const glob = __webpack_require__(714); -const fastGlob = __webpack_require__(719); -const dirGlob = __webpack_require__(919); -const gitignore = __webpack_require__(922); +const fs = __webpack_require__(349); +const arrayUnion = __webpack_require__(704); +const glob = __webpack_require__(706); +const fastGlob = __webpack_require__(711); +const dirGlob = __webpack_require__(911); +const gitignore = __webpack_require__(914); const DEFAULT_FILTER = () => false; @@ -79981,12 +79638,12 @@ module.exports.gitignore = gitignore; /***/ }), -/* 712 */ +/* 704 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var arrayUniq = __webpack_require__(713); +var arrayUniq = __webpack_require__(705); module.exports = function () { return arrayUniq([].concat.apply([], arguments)); @@ -79994,7 +79651,7 @@ module.exports = function () { /***/ }), -/* 713 */ +/* 705 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -80063,7 +79720,7 @@ if ('Set' in global) { /***/ }), -/* 714 */ +/* 706 */ /***/ (function(module, exports, __webpack_require__) { // Approach: @@ -80108,27 +79765,27 @@ if ('Set' in global) { module.exports = glob -var fs = __webpack_require__(23) +var fs = __webpack_require__(349) var rp = __webpack_require__(504) var minimatch = __webpack_require__(506) var Minimatch = minimatch.Minimatch -var inherits = __webpack_require__(715) -var EE = __webpack_require__(399).EventEmitter -var path = __webpack_require__(16) -var assert = __webpack_require__(30) +var inherits = __webpack_require__(707) +var EE = __webpack_require__(373).EventEmitter +var path = __webpack_require__(4) +var assert = __webpack_require__(371) var isAbsolute = __webpack_require__(512) -var globSync = __webpack_require__(717) -var common = __webpack_require__(718) +var globSync = __webpack_require__(709) +var common = __webpack_require__(710) var alphasort = common.alphasort var alphasorti = common.alphasorti var setopts = common.setopts var ownProp = common.ownProp var inflight = __webpack_require__(515) -var util = __webpack_require__(29) +var util = __webpack_require__(397) var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored -var once = __webpack_require__(404) +var once = __webpack_require__(378) function glob (pattern, options, cb) { if (typeof options === 'function') cb = options, options = {} @@ -80859,22 +80516,22 @@ Glob.prototype._stat2 = function (f, abs, er, stat, cb) { /***/ }), -/* 715 */ +/* 707 */ /***/ (function(module, exports, __webpack_require__) { try { - var util = __webpack_require__(29); + var util = __webpack_require__(397); /* istanbul ignore next */ if (typeof util.inherits !== 'function') throw ''; module.exports = util.inherits; } catch (e) { /* istanbul ignore next */ - module.exports = __webpack_require__(716); + module.exports = __webpack_require__(708); } /***/ }), -/* 716 */ +/* 708 */ /***/ (function(module, exports) { if (typeof Object.create === 'function') { @@ -80907,22 +80564,22 @@ if (typeof Object.create === 'function') { /***/ }), -/* 717 */ +/* 709 */ /***/ (function(module, exports, __webpack_require__) { module.exports = globSync globSync.GlobSync = GlobSync -var fs = __webpack_require__(23) +var fs = __webpack_require__(349) var rp = __webpack_require__(504) var minimatch = __webpack_require__(506) var Minimatch = minimatch.Minimatch -var Glob = __webpack_require__(714).Glob -var util = __webpack_require__(29) -var path = __webpack_require__(16) -var assert = __webpack_require__(30) +var Glob = __webpack_require__(706).Glob +var util = __webpack_require__(397) +var path = __webpack_require__(4) +var assert = __webpack_require__(371) var isAbsolute = __webpack_require__(512) -var common = __webpack_require__(718) +var common = __webpack_require__(710) var alphasort = common.alphasort var alphasorti = common.alphasorti var setopts = common.setopts @@ -81399,7 +81056,7 @@ GlobSync.prototype._makeAbs = function (f) { /***/ }), -/* 718 */ +/* 710 */ /***/ (function(module, exports, __webpack_require__) { exports.alphasort = alphasort @@ -81416,7 +81073,7 @@ function ownProp (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } -var path = __webpack_require__(16) +var path = __webpack_require__(4) var minimatch = __webpack_require__(506) var isAbsolute = __webpack_require__(512) var Minimatch = minimatch.Minimatch @@ -81645,10 +81302,10 @@ function childrenIgnored (self, path) { /***/ }), -/* 719 */ +/* 711 */ /***/ (function(module, exports, __webpack_require__) { -const pkg = __webpack_require__(720); +const pkg = __webpack_require__(712); module.exports = pkg.async; module.exports.default = pkg.async; @@ -81661,19 +81318,19 @@ module.exports.generateTasks = pkg.generateTasks; /***/ }), -/* 720 */ +/* 712 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -var optionsManager = __webpack_require__(721); -var taskManager = __webpack_require__(722); -var reader_async_1 = __webpack_require__(890); -var reader_stream_1 = __webpack_require__(914); -var reader_sync_1 = __webpack_require__(915); -var arrayUtils = __webpack_require__(917); -var streamUtils = __webpack_require__(918); +var optionsManager = __webpack_require__(713); +var taskManager = __webpack_require__(714); +var reader_async_1 = __webpack_require__(882); +var reader_stream_1 = __webpack_require__(906); +var reader_sync_1 = __webpack_require__(907); +var arrayUtils = __webpack_require__(909); +var streamUtils = __webpack_require__(910); /** * Synchronous API. */ @@ -81739,7 +81396,7 @@ function isString(source) { /***/ }), -/* 721 */ +/* 713 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -81777,13 +81434,13 @@ exports.prepare = prepare; /***/ }), -/* 722 */ +/* 714 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -var patternUtils = __webpack_require__(723); +var patternUtils = __webpack_require__(715); /** * Generate tasks based on parent directory of each pattern. */ @@ -81874,16 +81531,16 @@ exports.convertPatternGroupToTask = convertPatternGroupToTask; /***/ }), -/* 723 */ +/* 715 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -var path = __webpack_require__(16); -var globParent = __webpack_require__(724); -var isGlob = __webpack_require__(727); -var micromatch = __webpack_require__(728); +var path = __webpack_require__(4); +var globParent = __webpack_require__(716); +var isGlob = __webpack_require__(719); +var micromatch = __webpack_require__(720); var GLOBSTAR = '**'; /** * Return true for static pattern. @@ -82029,16 +81686,16 @@ exports.matchAny = matchAny; /***/ }), -/* 724 */ +/* 716 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var path = __webpack_require__(16); -var isglob = __webpack_require__(725); -var pathDirname = __webpack_require__(726); -var isWin32 = __webpack_require__(11).platform() === 'win32'; +var path = __webpack_require__(4); +var isglob = __webpack_require__(717); +var pathDirname = __webpack_require__(718); +var isWin32 = __webpack_require__(364).platform() === 'win32'; module.exports = function globParent(str) { // flip windows path separators @@ -82060,7 +81717,7 @@ module.exports = function globParent(str) { /***/ }), -/* 725 */ +/* 717 */ /***/ (function(module, exports, __webpack_require__) { /*! @@ -82070,7 +81727,7 @@ module.exports = function globParent(str) { * Licensed under the MIT License. */ -var isExtglob = __webpack_require__(606); +var isExtglob = __webpack_require__(601); module.exports = function isGlob(str) { if (typeof str !== 'string' || str === '') { @@ -82091,14 +81748,14 @@ module.exports = function isGlob(str) { /***/ }), -/* 726 */ +/* 718 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var path = __webpack_require__(16); -var inspect = __webpack_require__(29).inspect; +var path = __webpack_require__(4); +var inspect = __webpack_require__(397).inspect; function assertPath(path) { if (typeof path !== 'string') { @@ -82241,7 +81898,7 @@ module.exports.win32 = win32; /***/ }), -/* 727 */ +/* 719 */ /***/ (function(module, exports, __webpack_require__) { /*! @@ -82251,7 +81908,7 @@ module.exports.win32 = win32; * Released under the MIT License. */ -var isExtglob = __webpack_require__(606); +var isExtglob = __webpack_require__(601); var chars = { '{': '}', '(': ')', '[': ']'}; module.exports = function isGlob(str, options) { @@ -82293,7 +81950,7 @@ module.exports = function isGlob(str, options) { /***/ }), -/* 728 */ +/* 720 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -82303,19 +81960,19 @@ module.exports = function isGlob(str, options) { * Module dependencies */ -var util = __webpack_require__(29); -var braces = __webpack_require__(729); -var toRegex = __webpack_require__(842); -var extend = __webpack_require__(850); +var util = __webpack_require__(397); +var braces = __webpack_require__(721); +var toRegex = __webpack_require__(834); +var extend = __webpack_require__(842); /** * Local dependencies */ -var compilers = __webpack_require__(853); -var parsers = __webpack_require__(886); -var cache = __webpack_require__(887); -var utils = __webpack_require__(888); +var compilers = __webpack_require__(845); +var parsers = __webpack_require__(878); +var cache = __webpack_require__(879); +var utils = __webpack_require__(880); var MAX_LENGTH = 1024 * 64; /** @@ -83177,7 +82834,7 @@ module.exports = micromatch; /***/ }), -/* 729 */ +/* 721 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -83187,18 +82844,18 @@ module.exports = micromatch; * Module dependencies */ -var toRegex = __webpack_require__(730); -var unique = __webpack_require__(744); -var extend = __webpack_require__(739); +var toRegex = __webpack_require__(722); +var unique = __webpack_require__(736); +var extend = __webpack_require__(731); /** * Local dependencies */ -var compilers = __webpack_require__(745); -var parsers = __webpack_require__(762); -var Braces = __webpack_require__(772); -var utils = __webpack_require__(746); +var compilers = __webpack_require__(737); +var parsers = __webpack_require__(754); +var Braces = __webpack_require__(764); +var utils = __webpack_require__(738); var MAX_LENGTH = 1024 * 64; var cache = {}; @@ -83502,15 +83159,15 @@ module.exports = braces; /***/ }), -/* 730 */ +/* 722 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var define = __webpack_require__(731); -var extend = __webpack_require__(739); -var not = __webpack_require__(741); +var define = __webpack_require__(723); +var extend = __webpack_require__(731); +var not = __webpack_require__(733); var MAX_LENGTH = 1024 * 64; /** @@ -83657,7 +83314,7 @@ module.exports.makeRe = makeRe; /***/ }), -/* 731 */ +/* 723 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -83670,7 +83327,7 @@ module.exports.makeRe = makeRe; -var isDescriptor = __webpack_require__(732); +var isDescriptor = __webpack_require__(724); module.exports = function defineProperty(obj, prop, val) { if (typeof obj !== 'object' && typeof obj !== 'function') { @@ -83695,7 +83352,7 @@ module.exports = function defineProperty(obj, prop, val) { /***/ }), -/* 732 */ +/* 724 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -83708,9 +83365,9 @@ module.exports = function defineProperty(obj, prop, val) { -var typeOf = __webpack_require__(733); -var isAccessor = __webpack_require__(734); -var isData = __webpack_require__(737); +var typeOf = __webpack_require__(725); +var isAccessor = __webpack_require__(726); +var isData = __webpack_require__(729); module.exports = function isDescriptor(obj, key) { if (typeOf(obj) !== 'object') { @@ -83724,7 +83381,7 @@ module.exports = function isDescriptor(obj, key) { /***/ }), -/* 733 */ +/* 725 */ /***/ (function(module, exports) { var toString = Object.prototype.toString; @@ -83877,7 +83534,7 @@ function isBuffer(val) { /***/ }), -/* 734 */ +/* 726 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -83890,7 +83547,7 @@ function isBuffer(val) { -var typeOf = __webpack_require__(735); +var typeOf = __webpack_require__(727); // accessor descriptor properties var accessor = { @@ -83953,10 +83610,10 @@ module.exports = isAccessorDescriptor; /***/ }), -/* 735 */ +/* 727 */ /***/ (function(module, exports, __webpack_require__) { -var isBuffer = __webpack_require__(736); +var isBuffer = __webpack_require__(728); var toString = Object.prototype.toString; /** @@ -84075,7 +83732,7 @@ module.exports = function kindOf(val) { /***/ }), -/* 736 */ +/* 728 */ /***/ (function(module, exports) { /*! @@ -84102,7 +83759,7 @@ function isSlowBuffer (obj) { /***/ }), -/* 737 */ +/* 729 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -84115,7 +83772,7 @@ function isSlowBuffer (obj) { -var typeOf = __webpack_require__(738); +var typeOf = __webpack_require__(730); // data descriptor properties var data = { @@ -84164,10 +83821,10 @@ module.exports = isDataDescriptor; /***/ }), -/* 738 */ +/* 730 */ /***/ (function(module, exports, __webpack_require__) { -var isBuffer = __webpack_require__(736); +var isBuffer = __webpack_require__(728); var toString = Object.prototype.toString; /** @@ -84286,13 +83943,13 @@ module.exports = function kindOf(val) { /***/ }), -/* 739 */ +/* 731 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isObject = __webpack_require__(740); +var isObject = __webpack_require__(732); module.exports = function extend(o/*, objects*/) { if (!isObject(o)) { o = {}; } @@ -84326,7 +83983,7 @@ function hasOwn(obj, key) { /***/ }), -/* 740 */ +/* 732 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -84346,13 +84003,13 @@ module.exports = function isExtendable(val) { /***/ }), -/* 741 */ +/* 733 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var extend = __webpack_require__(742); +var extend = __webpack_require__(734); /** * The main export is a function that takes a `pattern` string and an `options` object. @@ -84419,13 +84076,13 @@ module.exports = toRegex; /***/ }), -/* 742 */ +/* 734 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isObject = __webpack_require__(743); +var isObject = __webpack_require__(735); module.exports = function extend(o/*, objects*/) { if (!isObject(o)) { o = {}; } @@ -84459,7 +84116,7 @@ function hasOwn(obj, key) { /***/ }), -/* 743 */ +/* 735 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -84479,7 +84136,7 @@ module.exports = function isExtendable(val) { /***/ }), -/* 744 */ +/* 736 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -84529,13 +84186,13 @@ module.exports.immutable = function uniqueImmutable(arr) { /***/ }), -/* 745 */ +/* 737 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var utils = __webpack_require__(746); +var utils = __webpack_require__(738); module.exports = function(braces, options) { braces.compiler @@ -84818,25 +84475,25 @@ function hasQueue(node) { /***/ }), -/* 746 */ +/* 738 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var splitString = __webpack_require__(747); +var splitString = __webpack_require__(739); var utils = module.exports; /** * Module dependencies */ -utils.extend = __webpack_require__(739); -utils.flatten = __webpack_require__(753); -utils.isObject = __webpack_require__(751); -utils.fillRange = __webpack_require__(754); -utils.repeat = __webpack_require__(761); -utils.unique = __webpack_require__(744); +utils.extend = __webpack_require__(731); +utils.flatten = __webpack_require__(745); +utils.isObject = __webpack_require__(743); +utils.fillRange = __webpack_require__(746); +utils.repeat = __webpack_require__(753); +utils.unique = __webpack_require__(736); utils.define = function(obj, key, val) { Object.defineProperty(obj, key, { @@ -85168,7 +84825,7 @@ utils.escapeRegex = function(str) { /***/ }), -/* 747 */ +/* 739 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -85181,7 +84838,7 @@ utils.escapeRegex = function(str) { -var extend = __webpack_require__(748); +var extend = __webpack_require__(740); module.exports = function(str, options, fn) { if (typeof str !== 'string') { @@ -85346,14 +85003,14 @@ function keepEscaping(opts, str, idx) { /***/ }), -/* 748 */ +/* 740 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isExtendable = __webpack_require__(749); -var assignSymbols = __webpack_require__(752); +var isExtendable = __webpack_require__(741); +var assignSymbols = __webpack_require__(744); module.exports = Object.assign || function(obj/*, objects*/) { if (obj === null || typeof obj === 'undefined') { @@ -85413,7 +85070,7 @@ function isEnum(obj, key) { /***/ }), -/* 749 */ +/* 741 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -85426,7 +85083,7 @@ function isEnum(obj, key) { -var isPlainObject = __webpack_require__(750); +var isPlainObject = __webpack_require__(742); module.exports = function isExtendable(val) { return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); @@ -85434,7 +85091,7 @@ module.exports = function isExtendable(val) { /***/ }), -/* 750 */ +/* 742 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -85447,7 +85104,7 @@ module.exports = function isExtendable(val) { -var isObject = __webpack_require__(751); +var isObject = __webpack_require__(743); function isObjectObject(o) { return isObject(o) === true @@ -85478,7 +85135,7 @@ module.exports = function isPlainObject(o) { /***/ }), -/* 751 */ +/* 743 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -85497,7 +85154,7 @@ module.exports = function isObject(val) { /***/ }), -/* 752 */ +/* 744 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -85544,7 +85201,7 @@ module.exports = function(receiver, objects) { /***/ }), -/* 753 */ +/* 745 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -85573,7 +85230,7 @@ function flat(arr, res) { /***/ }), -/* 754 */ +/* 746 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -85586,11 +85243,11 @@ function flat(arr, res) { -var util = __webpack_require__(29); -var isNumber = __webpack_require__(755); -var extend = __webpack_require__(757); -var repeat = __webpack_require__(759); -var toRegex = __webpack_require__(760); +var util = __webpack_require__(397); +var isNumber = __webpack_require__(747); +var extend = __webpack_require__(749); +var repeat = __webpack_require__(751); +var toRegex = __webpack_require__(752); /** * Return a range of numbers or letters. @@ -85788,7 +85445,7 @@ module.exports = fillRange; /***/ }), -/* 755 */ +/* 747 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -85801,7 +85458,7 @@ module.exports = fillRange; -var typeOf = __webpack_require__(756); +var typeOf = __webpack_require__(748); module.exports = function isNumber(num) { var type = typeOf(num); @@ -85817,10 +85474,10 @@ module.exports = function isNumber(num) { /***/ }), -/* 756 */ +/* 748 */ /***/ (function(module, exports, __webpack_require__) { -var isBuffer = __webpack_require__(736); +var isBuffer = __webpack_require__(728); var toString = Object.prototype.toString; /** @@ -85939,13 +85596,13 @@ module.exports = function kindOf(val) { /***/ }), -/* 757 */ +/* 749 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isObject = __webpack_require__(758); +var isObject = __webpack_require__(750); module.exports = function extend(o/*, objects*/) { if (!isObject(o)) { o = {}; } @@ -85979,7 +85636,7 @@ function hasOwn(obj, key) { /***/ }), -/* 758 */ +/* 750 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -85999,7 +85656,7 @@ module.exports = function isExtendable(val) { /***/ }), -/* 759 */ +/* 751 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -86076,7 +85733,7 @@ function repeat(str, num) { /***/ }), -/* 760 */ +/* 752 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -86089,8 +85746,8 @@ function repeat(str, num) { -var repeat = __webpack_require__(759); -var isNumber = __webpack_require__(755); +var repeat = __webpack_require__(751); +var isNumber = __webpack_require__(747); var cache = {}; function toRegexRange(min, max, options) { @@ -86377,7 +86034,7 @@ module.exports = toRegexRange; /***/ }), -/* 761 */ +/* 753 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -86402,14 +86059,14 @@ module.exports = function repeat(ele, num) { /***/ }), -/* 762 */ +/* 754 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var Node = __webpack_require__(763); -var utils = __webpack_require__(746); +var Node = __webpack_require__(755); +var utils = __webpack_require__(738); /** * Braces parsers @@ -86769,15 +86426,15 @@ function concatNodes(pos, node, parent, options) { /***/ }), -/* 763 */ +/* 755 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isObject = __webpack_require__(751); -var define = __webpack_require__(764); -var utils = __webpack_require__(771); +var isObject = __webpack_require__(743); +var define = __webpack_require__(756); +var utils = __webpack_require__(763); var ownNames; /** @@ -87268,7 +86925,7 @@ exports = module.exports = Node; /***/ }), -/* 764 */ +/* 756 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -87281,7 +86938,7 @@ exports = module.exports = Node; -var isDescriptor = __webpack_require__(765); +var isDescriptor = __webpack_require__(757); module.exports = function defineProperty(obj, prop, val) { if (typeof obj !== 'object' && typeof obj !== 'function') { @@ -87306,7 +86963,7 @@ module.exports = function defineProperty(obj, prop, val) { /***/ }), -/* 765 */ +/* 757 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -87319,9 +86976,9 @@ module.exports = function defineProperty(obj, prop, val) { -var typeOf = __webpack_require__(766); -var isAccessor = __webpack_require__(767); -var isData = __webpack_require__(769); +var typeOf = __webpack_require__(758); +var isAccessor = __webpack_require__(759); +var isData = __webpack_require__(761); module.exports = function isDescriptor(obj, key) { if (typeOf(obj) !== 'object') { @@ -87335,7 +86992,7 @@ module.exports = function isDescriptor(obj, key) { /***/ }), -/* 766 */ +/* 758 */ /***/ (function(module, exports) { var toString = Object.prototype.toString; @@ -87470,7 +87127,7 @@ function isBuffer(val) { /***/ }), -/* 767 */ +/* 759 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -87483,7 +87140,7 @@ function isBuffer(val) { -var typeOf = __webpack_require__(768); +var typeOf = __webpack_require__(760); // accessor descriptor properties var accessor = { @@ -87546,7 +87203,7 @@ module.exports = isAccessorDescriptor; /***/ }), -/* 768 */ +/* 760 */ /***/ (function(module, exports) { var toString = Object.prototype.toString; @@ -87681,7 +87338,7 @@ function isBuffer(val) { /***/ }), -/* 769 */ +/* 761 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -87694,7 +87351,7 @@ function isBuffer(val) { -var typeOf = __webpack_require__(770); +var typeOf = __webpack_require__(762); module.exports = function isDataDescriptor(obj, prop) { // data descriptor properties @@ -87737,7 +87394,7 @@ module.exports = function isDataDescriptor(obj, prop) { /***/ }), -/* 770 */ +/* 762 */ /***/ (function(module, exports) { var toString = Object.prototype.toString; @@ -87872,13 +87529,13 @@ function isBuffer(val) { /***/ }), -/* 771 */ +/* 763 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var typeOf = __webpack_require__(756); +var typeOf = __webpack_require__(748); var utils = module.exports; /** @@ -88898,17 +88555,17 @@ function assert(val, message) { /***/ }), -/* 772 */ +/* 764 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var extend = __webpack_require__(739); -var Snapdragon = __webpack_require__(773); -var compilers = __webpack_require__(745); -var parsers = __webpack_require__(762); -var utils = __webpack_require__(746); +var extend = __webpack_require__(731); +var Snapdragon = __webpack_require__(765); +var compilers = __webpack_require__(737); +var parsers = __webpack_require__(754); +var utils = __webpack_require__(738); /** * Customize Snapdragon parser and renderer @@ -89009,17 +88666,17 @@ module.exports = Braces; /***/ }), -/* 773 */ +/* 765 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var Base = __webpack_require__(774); -var define = __webpack_require__(800); -var Compiler = __webpack_require__(810); -var Parser = __webpack_require__(839); -var utils = __webpack_require__(819); +var Base = __webpack_require__(766); +var define = __webpack_require__(792); +var Compiler = __webpack_require__(802); +var Parser = __webpack_require__(831); +var utils = __webpack_require__(811); var regexCache = {}; var cache = {}; @@ -89190,20 +88847,20 @@ module.exports.Parser = Parser; /***/ }), -/* 774 */ +/* 766 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var util = __webpack_require__(29); -var define = __webpack_require__(775); -var CacheBase = __webpack_require__(776); -var Emitter = __webpack_require__(777); -var isObject = __webpack_require__(751); -var merge = __webpack_require__(794); -var pascal = __webpack_require__(797); -var cu = __webpack_require__(798); +var util = __webpack_require__(397); +var define = __webpack_require__(767); +var CacheBase = __webpack_require__(768); +var Emitter = __webpack_require__(769); +var isObject = __webpack_require__(743); +var merge = __webpack_require__(786); +var pascal = __webpack_require__(789); +var cu = __webpack_require__(790); /** * Optionally define a custom `cache` namespace to use. @@ -89632,7 +89289,7 @@ module.exports.namespace = namespace; /***/ }), -/* 775 */ +/* 767 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -89645,7 +89302,7 @@ module.exports.namespace = namespace; -var isDescriptor = __webpack_require__(765); +var isDescriptor = __webpack_require__(757); module.exports = function defineProperty(obj, prop, val) { if (typeof obj !== 'object' && typeof obj !== 'function') { @@ -89670,21 +89327,21 @@ module.exports = function defineProperty(obj, prop, val) { /***/ }), -/* 776 */ +/* 768 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isObject = __webpack_require__(751); -var Emitter = __webpack_require__(777); -var visit = __webpack_require__(778); -var toPath = __webpack_require__(781); -var union = __webpack_require__(782); -var del = __webpack_require__(786); -var get = __webpack_require__(784); -var has = __webpack_require__(791); -var set = __webpack_require__(785); +var isObject = __webpack_require__(743); +var Emitter = __webpack_require__(769); +var visit = __webpack_require__(770); +var toPath = __webpack_require__(773); +var union = __webpack_require__(774); +var del = __webpack_require__(778); +var get = __webpack_require__(776); +var has = __webpack_require__(783); +var set = __webpack_require__(777); /** * Create a `Cache` constructor that when instantiated will @@ -89938,7 +89595,7 @@ module.exports.namespace = namespace; /***/ }), -/* 777 */ +/* 769 */ /***/ (function(module, exports, __webpack_require__) { @@ -90107,7 +89764,7 @@ Emitter.prototype.hasListeners = function(event){ /***/ }), -/* 778 */ +/* 770 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -90120,8 +89777,8 @@ Emitter.prototype.hasListeners = function(event){ -var visit = __webpack_require__(779); -var mapVisit = __webpack_require__(780); +var visit = __webpack_require__(771); +var mapVisit = __webpack_require__(772); module.exports = function(collection, method, val) { var result; @@ -90144,7 +89801,7 @@ module.exports = function(collection, method, val) { /***/ }), -/* 779 */ +/* 771 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -90157,7 +89814,7 @@ module.exports = function(collection, method, val) { -var isObject = __webpack_require__(751); +var isObject = __webpack_require__(743); module.exports = function visit(thisArg, method, target, val) { if (!isObject(thisArg) && typeof thisArg !== 'function') { @@ -90184,14 +89841,14 @@ module.exports = function visit(thisArg, method, target, val) { /***/ }), -/* 780 */ +/* 772 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var util = __webpack_require__(29); -var visit = __webpack_require__(779); +var util = __webpack_require__(397); +var visit = __webpack_require__(771); /** * Map `visit` over an array of objects. @@ -90228,7 +89885,7 @@ function isObject(val) { /***/ }), -/* 781 */ +/* 773 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -90241,7 +89898,7 @@ function isObject(val) { -var typeOf = __webpack_require__(756); +var typeOf = __webpack_require__(748); module.exports = function toPath(args) { if (typeOf(args) !== 'arguments') { @@ -90268,16 +89925,16 @@ function filter(arr) { /***/ }), -/* 782 */ +/* 774 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isObject = __webpack_require__(743); -var union = __webpack_require__(783); -var get = __webpack_require__(784); -var set = __webpack_require__(785); +var isObject = __webpack_require__(735); +var union = __webpack_require__(775); +var get = __webpack_require__(776); +var set = __webpack_require__(777); module.exports = function unionValue(obj, prop, value) { if (!isObject(obj)) { @@ -90305,7 +89962,7 @@ function arrayify(val) { /***/ }), -/* 783 */ +/* 775 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -90341,7 +89998,7 @@ module.exports = function union(init) { /***/ }), -/* 784 */ +/* 776 */ /***/ (function(module, exports) { /*! @@ -90397,7 +90054,7 @@ function toString(val) { /***/ }), -/* 785 */ +/* 777 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -90410,10 +90067,10 @@ function toString(val) { -var split = __webpack_require__(747); -var extend = __webpack_require__(742); -var isPlainObject = __webpack_require__(750); -var isObject = __webpack_require__(743); +var split = __webpack_require__(739); +var extend = __webpack_require__(734); +var isPlainObject = __webpack_require__(742); +var isObject = __webpack_require__(735); module.exports = function(obj, prop, val) { if (!isObject(obj)) { @@ -90459,7 +90116,7 @@ function isValidKey(key) { /***/ }), -/* 786 */ +/* 778 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -90472,8 +90129,8 @@ function isValidKey(key) { -var isObject = __webpack_require__(751); -var has = __webpack_require__(787); +var isObject = __webpack_require__(743); +var has = __webpack_require__(779); module.exports = function unset(obj, prop) { if (!isObject(obj)) { @@ -90498,7 +90155,7 @@ module.exports = function unset(obj, prop) { /***/ }), -/* 787 */ +/* 779 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -90511,9 +90168,9 @@ module.exports = function unset(obj, prop) { -var isObject = __webpack_require__(788); -var hasValues = __webpack_require__(790); -var get = __webpack_require__(784); +var isObject = __webpack_require__(780); +var hasValues = __webpack_require__(782); +var get = __webpack_require__(776); module.exports = function(obj, prop, noZero) { if (isObject(obj)) { @@ -90524,7 +90181,7 @@ module.exports = function(obj, prop, noZero) { /***/ }), -/* 788 */ +/* 780 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -90537,7 +90194,7 @@ module.exports = function(obj, prop, noZero) { -var isArray = __webpack_require__(789); +var isArray = __webpack_require__(781); module.exports = function isObject(val) { return val != null && typeof val === 'object' && isArray(val) === false; @@ -90545,7 +90202,7 @@ module.exports = function isObject(val) { /***/ }), -/* 789 */ +/* 781 */ /***/ (function(module, exports) { var toString = {}.toString; @@ -90556,7 +90213,7 @@ module.exports = Array.isArray || function (arr) { /***/ }), -/* 790 */ +/* 782 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -90599,7 +90256,7 @@ module.exports = function hasValue(o, noZero) { /***/ }), -/* 791 */ +/* 783 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -90612,9 +90269,9 @@ module.exports = function hasValue(o, noZero) { -var isObject = __webpack_require__(751); -var hasValues = __webpack_require__(792); -var get = __webpack_require__(784); +var isObject = __webpack_require__(743); +var hasValues = __webpack_require__(784); +var get = __webpack_require__(776); module.exports = function(val, prop) { return hasValues(isObject(val) && prop ? get(val, prop) : val); @@ -90622,7 +90279,7 @@ module.exports = function(val, prop) { /***/ }), -/* 792 */ +/* 784 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -90635,8 +90292,8 @@ module.exports = function(val, prop) { -var typeOf = __webpack_require__(793); -var isNumber = __webpack_require__(755); +var typeOf = __webpack_require__(785); +var isNumber = __webpack_require__(747); module.exports = function hasValue(val) { // is-number checks for NaN and other edge cases @@ -90689,10 +90346,10 @@ module.exports = function hasValue(val) { /***/ }), -/* 793 */ +/* 785 */ /***/ (function(module, exports, __webpack_require__) { -var isBuffer = __webpack_require__(736); +var isBuffer = __webpack_require__(728); var toString = Object.prototype.toString; /** @@ -90814,14 +90471,14 @@ module.exports = function kindOf(val) { /***/ }), -/* 794 */ +/* 786 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isExtendable = __webpack_require__(795); -var forIn = __webpack_require__(796); +var isExtendable = __webpack_require__(787); +var forIn = __webpack_require__(788); function mixinDeep(target, objects) { var len = arguments.length, i = 0; @@ -90885,7 +90542,7 @@ module.exports = mixinDeep; /***/ }), -/* 795 */ +/* 787 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -90898,7 +90555,7 @@ module.exports = mixinDeep; -var isPlainObject = __webpack_require__(750); +var isPlainObject = __webpack_require__(742); module.exports = function isExtendable(val) { return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); @@ -90906,7 +90563,7 @@ module.exports = function isExtendable(val) { /***/ }), -/* 796 */ +/* 788 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -90929,7 +90586,7 @@ module.exports = function forIn(obj, fn, thisArg) { /***/ }), -/* 797 */ +/* 789 */ /***/ (function(module, exports) { /*! @@ -90956,14 +90613,14 @@ module.exports = pascalcase; /***/ }), -/* 798 */ +/* 790 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var util = __webpack_require__(29); -var utils = __webpack_require__(799); +var util = __webpack_require__(397); +var utils = __webpack_require__(791); /** * Expose class utils @@ -91328,7 +90985,7 @@ cu.bubble = function(Parent, events) { /***/ }), -/* 799 */ +/* 791 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -91342,10 +90999,10 @@ var utils = {}; * Lazily required module dependencies */ -utils.union = __webpack_require__(783); -utils.define = __webpack_require__(800); -utils.isObj = __webpack_require__(751); -utils.staticExtend = __webpack_require__(807); +utils.union = __webpack_require__(775); +utils.define = __webpack_require__(792); +utils.isObj = __webpack_require__(743); +utils.staticExtend = __webpack_require__(799); /** @@ -91356,7 +91013,7 @@ module.exports = utils; /***/ }), -/* 800 */ +/* 792 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -91369,7 +91026,7 @@ module.exports = utils; -var isDescriptor = __webpack_require__(801); +var isDescriptor = __webpack_require__(793); module.exports = function defineProperty(obj, prop, val) { if (typeof obj !== 'object' && typeof obj !== 'function') { @@ -91394,7 +91051,7 @@ module.exports = function defineProperty(obj, prop, val) { /***/ }), -/* 801 */ +/* 793 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -91407,9 +91064,9 @@ module.exports = function defineProperty(obj, prop, val) { -var typeOf = __webpack_require__(802); -var isAccessor = __webpack_require__(803); -var isData = __webpack_require__(805); +var typeOf = __webpack_require__(794); +var isAccessor = __webpack_require__(795); +var isData = __webpack_require__(797); module.exports = function isDescriptor(obj, key) { if (typeOf(obj) !== 'object') { @@ -91423,7 +91080,7 @@ module.exports = function isDescriptor(obj, key) { /***/ }), -/* 802 */ +/* 794 */ /***/ (function(module, exports) { var toString = Object.prototype.toString; @@ -91576,7 +91233,7 @@ function isBuffer(val) { /***/ }), -/* 803 */ +/* 795 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -91589,7 +91246,7 @@ function isBuffer(val) { -var typeOf = __webpack_require__(804); +var typeOf = __webpack_require__(796); // accessor descriptor properties var accessor = { @@ -91652,10 +91309,10 @@ module.exports = isAccessorDescriptor; /***/ }), -/* 804 */ +/* 796 */ /***/ (function(module, exports, __webpack_require__) { -var isBuffer = __webpack_require__(736); +var isBuffer = __webpack_require__(728); var toString = Object.prototype.toString; /** @@ -91774,7 +91431,7 @@ module.exports = function kindOf(val) { /***/ }), -/* 805 */ +/* 797 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -91787,7 +91444,7 @@ module.exports = function kindOf(val) { -var typeOf = __webpack_require__(806); +var typeOf = __webpack_require__(798); // data descriptor properties var data = { @@ -91836,10 +91493,10 @@ module.exports = isDataDescriptor; /***/ }), -/* 806 */ +/* 798 */ /***/ (function(module, exports, __webpack_require__) { -var isBuffer = __webpack_require__(736); +var isBuffer = __webpack_require__(728); var toString = Object.prototype.toString; /** @@ -91958,7 +91615,7 @@ module.exports = function kindOf(val) { /***/ }), -/* 807 */ +/* 799 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -91971,9 +91628,9 @@ module.exports = function kindOf(val) { -var copy = __webpack_require__(808); -var define = __webpack_require__(800); -var util = __webpack_require__(29); +var copy = __webpack_require__(800); +var define = __webpack_require__(792); +var util = __webpack_require__(397); /** * Returns a function for extending the static properties, @@ -92055,15 +91712,15 @@ module.exports = extend; /***/ }), -/* 808 */ +/* 800 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var typeOf = __webpack_require__(756); -var copyDescriptor = __webpack_require__(809); -var define = __webpack_require__(800); +var typeOf = __webpack_require__(748); +var copyDescriptor = __webpack_require__(801); +var define = __webpack_require__(792); /** * Copy static properties, prototype properties, and descriptors from one object to another. @@ -92236,7 +91893,7 @@ module.exports.has = has; /***/ }), -/* 809 */ +/* 801 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -92324,16 +91981,16 @@ function isObject(val) { /***/ }), -/* 810 */ +/* 802 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var use = __webpack_require__(811); -var define = __webpack_require__(800); -var debug = __webpack_require__(813)('snapdragon:compiler'); -var utils = __webpack_require__(819); +var use = __webpack_require__(803); +var define = __webpack_require__(792); +var debug = __webpack_require__(805)('snapdragon:compiler'); +var utils = __webpack_require__(811); /** * Create a new `Compiler` with the given `options`. @@ -92487,7 +92144,7 @@ Compiler.prototype = { // source map support if (opts.sourcemap) { - var sourcemaps = __webpack_require__(838); + var sourcemaps = __webpack_require__(830); sourcemaps(this); this.mapVisit(this.ast.nodes); this.applySourceMaps(); @@ -92508,7 +92165,7 @@ module.exports = Compiler; /***/ }), -/* 811 */ +/* 803 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -92521,7 +92178,7 @@ module.exports = Compiler; -var utils = __webpack_require__(812); +var utils = __webpack_require__(804); module.exports = function base(app, opts) { if (!utils.isObject(app) && typeof app !== 'function') { @@ -92636,7 +92293,7 @@ module.exports = function base(app, opts) { /***/ }), -/* 812 */ +/* 804 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -92650,8 +92307,8 @@ var utils = {}; * Lazily required module dependencies */ -utils.define = __webpack_require__(800); -utils.isObject = __webpack_require__(751); +utils.define = __webpack_require__(792); +utils.isObject = __webpack_require__(743); utils.isString = function(val) { @@ -92666,7 +92323,7 @@ module.exports = utils; /***/ }), -/* 813 */ +/* 805 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -92675,14 +92332,14 @@ module.exports = utils; */ if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __webpack_require__(814); + module.exports = __webpack_require__(806); } else { - module.exports = __webpack_require__(817); + module.exports = __webpack_require__(809); } /***/ }), -/* 814 */ +/* 806 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -92691,7 +92348,7 @@ if (typeof process !== 'undefined' && process.type === 'renderer') { * Expose `debug()` as the module. */ -exports = module.exports = __webpack_require__(815); +exports = module.exports = __webpack_require__(807); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; @@ -92873,7 +92530,7 @@ function localstorage() { /***/ }), -/* 815 */ +/* 807 */ /***/ (function(module, exports, __webpack_require__) { @@ -92889,7 +92546,7 @@ exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; -exports.humanize = __webpack_require__(816); +exports.humanize = __webpack_require__(808); /** * The currently active debug mode names, and names to skip. @@ -93081,7 +92738,7 @@ function coerce(val) { /***/ }), -/* 816 */ +/* 808 */ /***/ (function(module, exports) { /** @@ -93239,15 +92896,15 @@ function plural(ms, n, name) { /***/ }), -/* 817 */ +/* 809 */ /***/ (function(module, exports, __webpack_require__) { /** * Module dependencies. */ -var tty = __webpack_require__(484); -var util = __webpack_require__(29); +var tty = __webpack_require__(471); +var util = __webpack_require__(397); /** * This is the Node.js implementation of `debug()`. @@ -93255,7 +92912,7 @@ var util = __webpack_require__(29); * Expose `debug()` as the module. */ -exports = module.exports = __webpack_require__(815); +exports = module.exports = __webpack_require__(807); exports.init = init; exports.log = log; exports.formatArgs = formatArgs; @@ -93427,14 +93084,14 @@ function createWritableStdioStream (fd) { break; case 'FILE': - var fs = __webpack_require__(23); + var fs = __webpack_require__(349); stream = new fs.SyncWriteStream(fd, { autoClose: false }); stream._type = 'fs'; break; case 'PIPE': case 'TCP': - var net = __webpack_require__(818); + var net = __webpack_require__(810); stream = new net.Socket({ fd: fd, readable: false, @@ -93493,13 +93150,13 @@ exports.enable(load()); /***/ }), -/* 818 */ +/* 810 */ /***/ (function(module, exports) { module.exports = require("net"); /***/ }), -/* 819 */ +/* 811 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -93509,9 +93166,9 @@ module.exports = require("net"); * Module dependencies */ -exports.extend = __webpack_require__(742); -exports.SourceMap = __webpack_require__(820); -exports.sourceMapResolve = __webpack_require__(831); +exports.extend = __webpack_require__(734); +exports.SourceMap = __webpack_require__(812); +exports.sourceMapResolve = __webpack_require__(823); /** * Convert backslash in the given string to forward slashes @@ -93554,7 +93211,7 @@ exports.last = function(arr, n) { /***/ }), -/* 820 */ +/* 812 */ /***/ (function(module, exports, __webpack_require__) { /* @@ -93562,13 +93219,13 @@ exports.last = function(arr, n) { * Licensed under the New BSD license. See LICENSE.txt or: * http://opensource.org/licenses/BSD-3-Clause */ -exports.SourceMapGenerator = __webpack_require__(821).SourceMapGenerator; -exports.SourceMapConsumer = __webpack_require__(827).SourceMapConsumer; -exports.SourceNode = __webpack_require__(830).SourceNode; +exports.SourceMapGenerator = __webpack_require__(813).SourceMapGenerator; +exports.SourceMapConsumer = __webpack_require__(819).SourceMapConsumer; +exports.SourceNode = __webpack_require__(822).SourceNode; /***/ }), -/* 821 */ +/* 813 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -93578,10 +93235,10 @@ exports.SourceNode = __webpack_require__(830).SourceNode; * http://opensource.org/licenses/BSD-3-Clause */ -var base64VLQ = __webpack_require__(822); -var util = __webpack_require__(824); -var ArraySet = __webpack_require__(825).ArraySet; -var MappingList = __webpack_require__(826).MappingList; +var base64VLQ = __webpack_require__(814); +var util = __webpack_require__(816); +var ArraySet = __webpack_require__(817).ArraySet; +var MappingList = __webpack_require__(818).MappingList; /** * An instance of the SourceMapGenerator represents a source map which is @@ -93990,7 +93647,7 @@ exports.SourceMapGenerator = SourceMapGenerator; /***/ }), -/* 822 */ +/* 814 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -94030,7 +93687,7 @@ exports.SourceMapGenerator = SourceMapGenerator; * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -var base64 = __webpack_require__(823); +var base64 = __webpack_require__(815); // 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, @@ -94136,7 +93793,7 @@ exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { /***/ }), -/* 823 */ +/* 815 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -94209,7 +93866,7 @@ exports.decode = function (charCode) { /***/ }), -/* 824 */ +/* 816 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -94632,7 +94289,7 @@ exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflate /***/ }), -/* 825 */ +/* 817 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -94642,7 +94299,7 @@ exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflate * http://opensource.org/licenses/BSD-3-Clause */ -var util = __webpack_require__(824); +var util = __webpack_require__(816); var has = Object.prototype.hasOwnProperty; var hasNativeMap = typeof Map !== "undefined"; @@ -94759,7 +94416,7 @@ exports.ArraySet = ArraySet; /***/ }), -/* 826 */ +/* 818 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -94769,7 +94426,7 @@ exports.ArraySet = ArraySet; * http://opensource.org/licenses/BSD-3-Clause */ -var util = __webpack_require__(824); +var util = __webpack_require__(816); /** * Determine whether mappingB is after mappingA with respect to generated @@ -94844,7 +94501,7 @@ exports.MappingList = MappingList; /***/ }), -/* 827 */ +/* 819 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -94854,11 +94511,11 @@ exports.MappingList = MappingList; * http://opensource.org/licenses/BSD-3-Clause */ -var util = __webpack_require__(824); -var binarySearch = __webpack_require__(828); -var ArraySet = __webpack_require__(825).ArraySet; -var base64VLQ = __webpack_require__(822); -var quickSort = __webpack_require__(829).quickSort; +var util = __webpack_require__(816); +var binarySearch = __webpack_require__(820); +var ArraySet = __webpack_require__(817).ArraySet; +var base64VLQ = __webpack_require__(814); +var quickSort = __webpack_require__(821).quickSort; function SourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; @@ -95932,7 +95589,7 @@ exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; /***/ }), -/* 828 */ +/* 820 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -96049,7 +95706,7 @@ exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { /***/ }), -/* 829 */ +/* 821 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -96169,7 +95826,7 @@ exports.quickSort = function (ary, comparator) { /***/ }), -/* 830 */ +/* 822 */ /***/ (function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ @@ -96179,8 +95836,8 @@ exports.quickSort = function (ary, comparator) { * http://opensource.org/licenses/BSD-3-Clause */ -var SourceMapGenerator = __webpack_require__(821).SourceMapGenerator; -var util = __webpack_require__(824); +var SourceMapGenerator = __webpack_require__(813).SourceMapGenerator; +var util = __webpack_require__(816); // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other // operating systems these days (capturing the result). @@ -96588,17 +96245,17 @@ exports.SourceNode = SourceNode; /***/ }), -/* 831 */ +/* 823 */ /***/ (function(module, exports, __webpack_require__) { // Copyright 2014, 2015, 2016, 2017 Simon Lydell // X11 (“MIT”) Licensed. (See LICENSE.) -var sourceMappingURL = __webpack_require__(832) -var resolveUrl = __webpack_require__(833) -var decodeUriComponent = __webpack_require__(834) -var urix = __webpack_require__(836) -var atob = __webpack_require__(837) +var sourceMappingURL = __webpack_require__(824) +var resolveUrl = __webpack_require__(825) +var decodeUriComponent = __webpack_require__(826) +var urix = __webpack_require__(828) +var atob = __webpack_require__(829) @@ -96896,7 +96553,7 @@ module.exports = { /***/ }), -/* 832 */ +/* 824 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;// Copyright 2014 Simon Lydell @@ -96959,13 +96616,13 @@ void (function(root, factory) { /***/ }), -/* 833 */ +/* 825 */ /***/ (function(module, exports, __webpack_require__) { // Copyright 2014 Simon Lydell // X11 (“MIT”) Licensed. (See LICENSE.) -var url = __webpack_require__(452) +var url = __webpack_require__(439) function resolveUrl(/* ...urls */) { return Array.prototype.reduce.call(arguments, function(resolved, nextUrl) { @@ -96977,13 +96634,13 @@ module.exports = resolveUrl /***/ }), -/* 834 */ +/* 826 */ /***/ (function(module, exports, __webpack_require__) { // Copyright 2017 Simon Lydell // X11 (“MIT”) Licensed. (See LICENSE.) -var decodeUriComponent = __webpack_require__(835) +var decodeUriComponent = __webpack_require__(827) function customDecodeUriComponent(string) { // `decodeUriComponent` turns `+` into ` `, but that's not wanted. @@ -96994,7 +96651,7 @@ module.exports = customDecodeUriComponent /***/ }), -/* 835 */ +/* 827 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -97095,13 +96752,13 @@ module.exports = function (encodedURI) { /***/ }), -/* 836 */ +/* 828 */ /***/ (function(module, exports, __webpack_require__) { // Copyright 2014 Simon Lydell // X11 (“MIT”) Licensed. (See LICENSE.) -var path = __webpack_require__(16) +var path = __webpack_require__(4) "use strict" @@ -97118,7 +96775,7 @@ module.exports = urix /***/ }), -/* 837 */ +/* 829 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -97132,16 +96789,16 @@ module.exports = atob.atob = atob; /***/ }), -/* 838 */ +/* 830 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var fs = __webpack_require__(23); -var path = __webpack_require__(16); -var define = __webpack_require__(800); -var utils = __webpack_require__(819); +var fs = __webpack_require__(349); +var path = __webpack_require__(4); +var define = __webpack_require__(792); +var utils = __webpack_require__(811); /** * Expose `mixin()`. @@ -97284,19 +96941,19 @@ exports.comment = function(node) { /***/ }), -/* 839 */ +/* 831 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var use = __webpack_require__(811); -var util = __webpack_require__(29); -var Cache = __webpack_require__(840); -var define = __webpack_require__(800); -var debug = __webpack_require__(813)('snapdragon:parser'); -var Position = __webpack_require__(841); -var utils = __webpack_require__(819); +var use = __webpack_require__(803); +var util = __webpack_require__(397); +var Cache = __webpack_require__(832); +var define = __webpack_require__(792); +var debug = __webpack_require__(805)('snapdragon:parser'); +var Position = __webpack_require__(833); +var utils = __webpack_require__(811); /** * Create a new `Parser` with the given `input` and `options`. @@ -97824,7 +97481,7 @@ module.exports = Parser; /***/ }), -/* 840 */ +/* 832 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -97931,13 +97588,13 @@ MapCache.prototype.del = function mapDelete(key) { /***/ }), -/* 841 */ +/* 833 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var define = __webpack_require__(800); +var define = __webpack_require__(792); /** * Store position for a node @@ -97952,16 +97609,16 @@ module.exports = function Position(start, parser) { /***/ }), -/* 842 */ +/* 834 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var safe = __webpack_require__(843); -var define = __webpack_require__(849); -var extend = __webpack_require__(850); -var not = __webpack_require__(852); +var safe = __webpack_require__(835); +var define = __webpack_require__(841); +var extend = __webpack_require__(842); +var not = __webpack_require__(844); var MAX_LENGTH = 1024 * 64; /** @@ -98114,10 +97771,10 @@ module.exports.makeRe = makeRe; /***/ }), -/* 843 */ +/* 835 */ /***/ (function(module, exports, __webpack_require__) { -var parse = __webpack_require__(844); +var parse = __webpack_require__(836); var types = parse.types; module.exports = function (re, opts) { @@ -98163,13 +97820,13 @@ function isRegExp (x) { /***/ }), -/* 844 */ +/* 836 */ /***/ (function(module, exports, __webpack_require__) { -var util = __webpack_require__(845); -var types = __webpack_require__(846); -var sets = __webpack_require__(847); -var positions = __webpack_require__(848); +var util = __webpack_require__(837); +var types = __webpack_require__(838); +var sets = __webpack_require__(839); +var positions = __webpack_require__(840); module.exports = function(regexpStr) { @@ -98451,11 +98108,11 @@ module.exports.types = types; /***/ }), -/* 845 */ +/* 837 */ /***/ (function(module, exports, __webpack_require__) { -var types = __webpack_require__(846); -var sets = __webpack_require__(847); +var types = __webpack_require__(838); +var sets = __webpack_require__(839); // All of these are private and only used by randexp. @@ -98568,7 +98225,7 @@ exports.error = function(regexp, msg) { /***/ }), -/* 846 */ +/* 838 */ /***/ (function(module, exports) { module.exports = { @@ -98584,10 +98241,10 @@ module.exports = { /***/ }), -/* 847 */ +/* 839 */ /***/ (function(module, exports, __webpack_require__) { -var types = __webpack_require__(846); +var types = __webpack_require__(838); var INTS = function() { return [{ type: types.RANGE , from: 48, to: 57 }]; @@ -98672,10 +98329,10 @@ exports.anyChar = function() { /***/ }), -/* 848 */ +/* 840 */ /***/ (function(module, exports, __webpack_require__) { -var types = __webpack_require__(846); +var types = __webpack_require__(838); exports.wordBoundary = function() { return { type: types.POSITION, value: 'b' }; @@ -98695,7 +98352,7 @@ exports.end = function() { /***/ }), -/* 849 */ +/* 841 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -98708,8 +98365,8 @@ exports.end = function() { -var isobject = __webpack_require__(751); -var isDescriptor = __webpack_require__(765); +var isobject = __webpack_require__(743); +var isDescriptor = __webpack_require__(757); var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) ? Reflect.defineProperty : Object.defineProperty; @@ -98740,14 +98397,14 @@ module.exports = function defineProperty(obj, key, val) { /***/ }), -/* 850 */ +/* 842 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isExtendable = __webpack_require__(851); -var assignSymbols = __webpack_require__(752); +var isExtendable = __webpack_require__(843); +var assignSymbols = __webpack_require__(744); module.exports = Object.assign || function(obj/*, objects*/) { if (obj === null || typeof obj === 'undefined') { @@ -98807,7 +98464,7 @@ function isEnum(obj, key) { /***/ }), -/* 851 */ +/* 843 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -98820,7 +98477,7 @@ function isEnum(obj, key) { -var isPlainObject = __webpack_require__(750); +var isPlainObject = __webpack_require__(742); module.exports = function isExtendable(val) { return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); @@ -98828,14 +98485,14 @@ module.exports = function isExtendable(val) { /***/ }), -/* 852 */ +/* 844 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var extend = __webpack_require__(850); -var safe = __webpack_require__(843); +var extend = __webpack_require__(842); +var safe = __webpack_require__(835); /** * The main export is a function that takes a `pattern` string and an `options` object. @@ -98907,14 +98564,14 @@ module.exports = toRegex; /***/ }), -/* 853 */ +/* 845 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var nanomatch = __webpack_require__(854); -var extglob = __webpack_require__(870); +var nanomatch = __webpack_require__(846); +var extglob = __webpack_require__(862); module.exports = function(snapdragon) { var compilers = snapdragon.compiler.compilers; @@ -98991,7 +98648,7 @@ function escapeExtglobs(compiler) { /***/ }), -/* 854 */ +/* 846 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -99001,18 +98658,18 @@ function escapeExtglobs(compiler) { * Module dependencies */ -var util = __webpack_require__(29); -var toRegex = __webpack_require__(855); -var extend = __webpack_require__(856); +var util = __webpack_require__(397); +var toRegex = __webpack_require__(847); +var extend = __webpack_require__(848); /** * Local dependencies */ -var compilers = __webpack_require__(858); -var parsers = __webpack_require__(859); -var cache = __webpack_require__(862); -var utils = __webpack_require__(864); +var compilers = __webpack_require__(850); +var parsers = __webpack_require__(851); +var cache = __webpack_require__(854); +var utils = __webpack_require__(856); var MAX_LENGTH = 1024 * 64; /** @@ -99836,15 +99493,15 @@ module.exports = nanomatch; /***/ }), -/* 855 */ +/* 847 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var define = __webpack_require__(800); -var extend = __webpack_require__(742); -var not = __webpack_require__(741); +var define = __webpack_require__(792); +var extend = __webpack_require__(734); +var not = __webpack_require__(733); var MAX_LENGTH = 1024 * 64; /** @@ -99991,14 +99648,14 @@ module.exports.makeRe = makeRe; /***/ }), -/* 856 */ +/* 848 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isExtendable = __webpack_require__(857); -var assignSymbols = __webpack_require__(752); +var isExtendable = __webpack_require__(849); +var assignSymbols = __webpack_require__(744); module.exports = Object.assign || function(obj/*, objects*/) { if (obj === null || typeof obj === 'undefined') { @@ -100058,7 +99715,7 @@ function isEnum(obj, key) { /***/ }), -/* 857 */ +/* 849 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -100071,7 +99728,7 @@ function isEnum(obj, key) { -var isPlainObject = __webpack_require__(750); +var isPlainObject = __webpack_require__(742); module.exports = function isExtendable(val) { return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); @@ -100079,7 +99736,7 @@ module.exports = function isExtendable(val) { /***/ }), -/* 858 */ +/* 850 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -100425,15 +100082,15 @@ module.exports = function(nanomatch, options) { /***/ }), -/* 859 */ +/* 851 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var regexNot = __webpack_require__(741); -var toRegex = __webpack_require__(855); -var isOdd = __webpack_require__(860); +var regexNot = __webpack_require__(733); +var toRegex = __webpack_require__(847); +var isOdd = __webpack_require__(852); /** * Characters to use in negation regex (we want to "not" match @@ -100819,7 +100476,7 @@ module.exports.not = NOT_REGEX; /***/ }), -/* 860 */ +/* 852 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -100832,7 +100489,7 @@ module.exports.not = NOT_REGEX; -var isNumber = __webpack_require__(861); +var isNumber = __webpack_require__(853); module.exports = function isOdd(i) { if (!isNumber(i)) { @@ -100846,7 +100503,7 @@ module.exports = function isOdd(i) { /***/ }), -/* 861 */ +/* 853 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -100874,14 +100531,14 @@ module.exports = function isNumber(num) { /***/ }), -/* 862 */ +/* 854 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = new (__webpack_require__(863))(); +module.exports = new (__webpack_require__(855))(); /***/ }), -/* 863 */ +/* 855 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -100894,7 +100551,7 @@ module.exports = new (__webpack_require__(863))(); -var MapCache = __webpack_require__(840); +var MapCache = __webpack_require__(832); /** * Create a new `FragmentCache` with an optional object to use for `caches`. @@ -101016,27 +100673,27 @@ exports = module.exports = FragmentCache; /***/ }), -/* 864 */ +/* 856 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = module.exports; -var path = __webpack_require__(16); +var path = __webpack_require__(4); /** * Module dependencies */ -var isWindows = __webpack_require__(865)(); -var Snapdragon = __webpack_require__(773); -utils.define = __webpack_require__(866); -utils.diff = __webpack_require__(867); -utils.extend = __webpack_require__(856); -utils.pick = __webpack_require__(868); -utils.typeOf = __webpack_require__(869); -utils.unique = __webpack_require__(744); +var isWindows = __webpack_require__(857)(); +var Snapdragon = __webpack_require__(765); +utils.define = __webpack_require__(858); +utils.diff = __webpack_require__(859); +utils.extend = __webpack_require__(848); +utils.pick = __webpack_require__(860); +utils.typeOf = __webpack_require__(861); +utils.unique = __webpack_require__(736); /** * Returns true if the given value is effectively an empty string @@ -101402,7 +101059,7 @@ utils.unixify = function(options) { /***/ }), -/* 865 */ +/* 857 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! @@ -101430,7 +101087,7 @@ var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_ /***/ }), -/* 866 */ +/* 858 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -101443,8 +101100,8 @@ var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_ -var isobject = __webpack_require__(751); -var isDescriptor = __webpack_require__(765); +var isobject = __webpack_require__(743); +var isDescriptor = __webpack_require__(757); var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) ? Reflect.defineProperty : Object.defineProperty; @@ -101475,7 +101132,7 @@ module.exports = function defineProperty(obj, key, val) { /***/ }), -/* 867 */ +/* 859 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -101529,7 +101186,7 @@ function diffArray(one, two) { /***/ }), -/* 868 */ +/* 860 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -101542,7 +101199,7 @@ function diffArray(one, two) { -var isObject = __webpack_require__(751); +var isObject = __webpack_require__(743); module.exports = function pick(obj, keys) { if (!isObject(obj) && typeof obj !== 'function') { @@ -101571,7 +101228,7 @@ module.exports = function pick(obj, keys) { /***/ }), -/* 869 */ +/* 861 */ /***/ (function(module, exports) { var toString = Object.prototype.toString; @@ -101706,7 +101363,7 @@ function isBuffer(val) { /***/ }), -/* 870 */ +/* 862 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -101716,18 +101373,18 @@ function isBuffer(val) { * Module dependencies */ -var extend = __webpack_require__(742); -var unique = __webpack_require__(744); -var toRegex = __webpack_require__(855); +var extend = __webpack_require__(734); +var unique = __webpack_require__(736); +var toRegex = __webpack_require__(847); /** * Local dependencies */ -var compilers = __webpack_require__(871); -var parsers = __webpack_require__(882); -var Extglob = __webpack_require__(885); -var utils = __webpack_require__(884); +var compilers = __webpack_require__(863); +var parsers = __webpack_require__(874); +var Extglob = __webpack_require__(877); +var utils = __webpack_require__(876); var MAX_LENGTH = 1024 * 64; /** @@ -102044,13 +101701,13 @@ module.exports = extglob; /***/ }), -/* 871 */ +/* 863 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var brackets = __webpack_require__(872); +var brackets = __webpack_require__(864); /** * Extglob compilers @@ -102220,7 +101877,7 @@ module.exports = function(extglob) { /***/ }), -/* 872 */ +/* 864 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -102230,17 +101887,17 @@ module.exports = function(extglob) { * Local dependencies */ -var compilers = __webpack_require__(873); -var parsers = __webpack_require__(875); +var compilers = __webpack_require__(865); +var parsers = __webpack_require__(867); /** * Module dependencies */ -var debug = __webpack_require__(877)('expand-brackets'); -var extend = __webpack_require__(742); -var Snapdragon = __webpack_require__(773); -var toRegex = __webpack_require__(855); +var debug = __webpack_require__(869)('expand-brackets'); +var extend = __webpack_require__(734); +var Snapdragon = __webpack_require__(765); +var toRegex = __webpack_require__(847); /** * Parses the given POSIX character class `pattern` and returns a @@ -102438,13 +102095,13 @@ module.exports = brackets; /***/ }), -/* 873 */ +/* 865 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var posix = __webpack_require__(874); +var posix = __webpack_require__(866); module.exports = function(brackets) { brackets.compiler @@ -102532,7 +102189,7 @@ module.exports = function(brackets) { /***/ }), -/* 874 */ +/* 866 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -102561,14 +102218,14 @@ module.exports = { /***/ }), -/* 875 */ +/* 867 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var utils = __webpack_require__(876); -var define = __webpack_require__(800); +var utils = __webpack_require__(868); +var define = __webpack_require__(792); /** * Text regex @@ -102787,14 +102444,14 @@ module.exports.TEXT_REGEX = TEXT_REGEX; /***/ }), -/* 876 */ +/* 868 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var toRegex = __webpack_require__(855); -var regexNot = __webpack_require__(741); +var toRegex = __webpack_require__(847); +var regexNot = __webpack_require__(733); var cached; /** @@ -102828,7 +102485,7 @@ exports.createRegex = function(pattern, include) { /***/ }), -/* 877 */ +/* 869 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -102837,14 +102494,14 @@ exports.createRegex = function(pattern, include) { */ if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __webpack_require__(878); + module.exports = __webpack_require__(870); } else { - module.exports = __webpack_require__(881); + module.exports = __webpack_require__(873); } /***/ }), -/* 878 */ +/* 870 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -102853,7 +102510,7 @@ if (typeof process !== 'undefined' && process.type === 'renderer') { * Expose `debug()` as the module. */ -exports = module.exports = __webpack_require__(879); +exports = module.exports = __webpack_require__(871); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; @@ -103035,7 +102692,7 @@ function localstorage() { /***/ }), -/* 879 */ +/* 871 */ /***/ (function(module, exports, __webpack_require__) { @@ -103051,7 +102708,7 @@ exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; -exports.humanize = __webpack_require__(880); +exports.humanize = __webpack_require__(872); /** * The currently active debug mode names, and names to skip. @@ -103243,7 +102900,7 @@ function coerce(val) { /***/ }), -/* 880 */ +/* 872 */ /***/ (function(module, exports) { /** @@ -103401,15 +103058,15 @@ function plural(ms, n, name) { /***/ }), -/* 881 */ +/* 873 */ /***/ (function(module, exports, __webpack_require__) { /** * Module dependencies. */ -var tty = __webpack_require__(484); -var util = __webpack_require__(29); +var tty = __webpack_require__(471); +var util = __webpack_require__(397); /** * This is the Node.js implementation of `debug()`. @@ -103417,7 +103074,7 @@ var util = __webpack_require__(29); * Expose `debug()` as the module. */ -exports = module.exports = __webpack_require__(879); +exports = module.exports = __webpack_require__(871); exports.init = init; exports.log = log; exports.formatArgs = formatArgs; @@ -103589,14 +103246,14 @@ function createWritableStdioStream (fd) { break; case 'FILE': - var fs = __webpack_require__(23); + var fs = __webpack_require__(349); stream = new fs.SyncWriteStream(fd, { autoClose: false }); stream._type = 'fs'; break; case 'PIPE': case 'TCP': - var net = __webpack_require__(818); + var net = __webpack_require__(810); stream = new net.Socket({ fd: fd, readable: false, @@ -103655,15 +103312,15 @@ exports.enable(load()); /***/ }), -/* 882 */ +/* 874 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var brackets = __webpack_require__(872); -var define = __webpack_require__(883); -var utils = __webpack_require__(884); +var brackets = __webpack_require__(864); +var define = __webpack_require__(875); +var utils = __webpack_require__(876); /** * Characters to use in text regex (we want to "not" match @@ -103818,7 +103475,7 @@ module.exports = parsers; /***/ }), -/* 883 */ +/* 875 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -103831,7 +103488,7 @@ module.exports = parsers; -var isDescriptor = __webpack_require__(765); +var isDescriptor = __webpack_require__(757); module.exports = function defineProperty(obj, prop, val) { if (typeof obj !== 'object' && typeof obj !== 'function') { @@ -103856,14 +103513,14 @@ module.exports = function defineProperty(obj, prop, val) { /***/ }), -/* 884 */ +/* 876 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var regex = __webpack_require__(741); -var Cache = __webpack_require__(863); +var regex = __webpack_require__(733); +var Cache = __webpack_require__(855); /** * Utils @@ -103932,7 +103589,7 @@ utils.createRegex = function(str) { /***/ }), -/* 885 */ +/* 877 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -103942,16 +103599,16 @@ utils.createRegex = function(str) { * Module dependencies */ -var Snapdragon = __webpack_require__(773); -var define = __webpack_require__(883); -var extend = __webpack_require__(742); +var Snapdragon = __webpack_require__(765); +var define = __webpack_require__(875); +var extend = __webpack_require__(734); /** * Local dependencies */ -var compilers = __webpack_require__(871); -var parsers = __webpack_require__(882); +var compilers = __webpack_require__(863); +var parsers = __webpack_require__(874); /** * Customize Snapdragon parser and renderer @@ -104017,16 +103674,16 @@ module.exports = Extglob; /***/ }), -/* 886 */ +/* 878 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var extglob = __webpack_require__(870); -var nanomatch = __webpack_require__(854); -var regexNot = __webpack_require__(741); -var toRegex = __webpack_require__(842); +var extglob = __webpack_require__(862); +var nanomatch = __webpack_require__(846); +var regexNot = __webpack_require__(733); +var toRegex = __webpack_require__(834); var not; /** @@ -104107,33 +103764,33 @@ function textRegex(pattern) { /***/ }), -/* 887 */ +/* 879 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = new (__webpack_require__(863))(); +module.exports = new (__webpack_require__(855))(); /***/ }), -/* 888 */ +/* 880 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = module.exports; -var path = __webpack_require__(16); +var path = __webpack_require__(4); /** * Module dependencies */ -var Snapdragon = __webpack_require__(773); -utils.define = __webpack_require__(849); -utils.diff = __webpack_require__(867); -utils.extend = __webpack_require__(850); -utils.pick = __webpack_require__(868); -utils.typeOf = __webpack_require__(889); -utils.unique = __webpack_require__(744); +var Snapdragon = __webpack_require__(765); +utils.define = __webpack_require__(841); +utils.diff = __webpack_require__(859); +utils.extend = __webpack_require__(842); +utils.pick = __webpack_require__(860); +utils.typeOf = __webpack_require__(881); +utils.unique = __webpack_require__(736); /** * Returns true if the platform is windows, or `path.sep` is `\\`. @@ -104430,7 +104087,7 @@ utils.unixify = function(options) { /***/ }), -/* 889 */ +/* 881 */ /***/ (function(module, exports) { var toString = Object.prototype.toString; @@ -104565,7 +104222,7 @@ function isBuffer(val) { /***/ }), -/* 890 */ +/* 882 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -104584,9 +104241,9 @@ var __extends = (this && this.__extends) || (function () { }; })(); Object.defineProperty(exports, "__esModule", { value: true }); -var readdir = __webpack_require__(891); -var reader_1 = __webpack_require__(904); -var fs_stream_1 = __webpack_require__(908); +var readdir = __webpack_require__(883); +var reader_1 = __webpack_require__(896); +var fs_stream_1 = __webpack_require__(900); var ReaderAsync = /** @class */ (function (_super) { __extends(ReaderAsync, _super); function ReaderAsync() { @@ -104647,15 +104304,15 @@ exports.default = ReaderAsync; /***/ }), -/* 891 */ +/* 883 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const readdirSync = __webpack_require__(892); -const readdirAsync = __webpack_require__(900); -const readdirStream = __webpack_require__(903); +const readdirSync = __webpack_require__(884); +const readdirAsync = __webpack_require__(892); +const readdirStream = __webpack_require__(895); module.exports = exports = readdirAsyncPath; exports.readdir = exports.readdirAsync = exports.async = readdirAsyncPath; @@ -104739,7 +104396,7 @@ function readdirStreamStat (dir, options) { /***/ }), -/* 892 */ +/* 884 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -104747,11 +104404,11 @@ function readdirStreamStat (dir, options) { module.exports = readdirSync; -const DirectoryReader = __webpack_require__(893); +const DirectoryReader = __webpack_require__(885); let syncFacade = { - fs: __webpack_require__(898), - forEach: __webpack_require__(899), + fs: __webpack_require__(890), + forEach: __webpack_require__(891), sync: true }; @@ -104780,18 +104437,18 @@ function readdirSync (dir, options, internalOptions) { /***/ }), -/* 893 */ +/* 885 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const Readable = __webpack_require__(27).Readable; -const EventEmitter = __webpack_require__(399).EventEmitter; -const path = __webpack_require__(16); -const normalizeOptions = __webpack_require__(894); -const stat = __webpack_require__(896); -const call = __webpack_require__(897); +const Readable = __webpack_require__(382).Readable; +const EventEmitter = __webpack_require__(373).EventEmitter; +const path = __webpack_require__(4); +const normalizeOptions = __webpack_require__(886); +const stat = __webpack_require__(888); +const call = __webpack_require__(889); /** * Asynchronously reads the contents of a directory and streams the results @@ -105167,14 +104824,14 @@ module.exports = DirectoryReader; /***/ }), -/* 894 */ +/* 886 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const path = __webpack_require__(16); -const globToRegExp = __webpack_require__(895); +const path = __webpack_require__(4); +const globToRegExp = __webpack_require__(887); module.exports = normalizeOptions; @@ -105351,7 +105008,7 @@ function normalizeOptions (options, internalOptions) { /***/ }), -/* 895 */ +/* 887 */ /***/ (function(module, exports) { module.exports = function (glob, opts) { @@ -105488,13 +105145,13 @@ module.exports = function (glob, opts) { /***/ }), -/* 896 */ +/* 888 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const call = __webpack_require__(897); +const call = __webpack_require__(889); module.exports = stat; @@ -105569,7 +105226,7 @@ function symlinkStat (fs, path, lstats, callback) { /***/ }), -/* 897 */ +/* 889 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -105630,14 +105287,14 @@ function callOnce (fn) { /***/ }), -/* 898 */ +/* 890 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const fs = __webpack_require__(23); -const call = __webpack_require__(897); +const fs = __webpack_require__(349); +const call = __webpack_require__(889); /** * A facade around {@link fs.readdirSync} that allows it to be called @@ -105701,7 +105358,7 @@ exports.lstat = function (path, callback) { /***/ }), -/* 899 */ +/* 891 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -105730,7 +105387,7 @@ function syncForEach (array, iterator, done) { /***/ }), -/* 900 */ +/* 892 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -105738,12 +105395,12 @@ function syncForEach (array, iterator, done) { module.exports = readdirAsync; -const maybe = __webpack_require__(901); -const DirectoryReader = __webpack_require__(893); +const maybe = __webpack_require__(893); +const DirectoryReader = __webpack_require__(885); let asyncFacade = { - fs: __webpack_require__(23), - forEach: __webpack_require__(902), + fs: __webpack_require__(349), + forEach: __webpack_require__(894), async: true }; @@ -105785,7 +105442,7 @@ function readdirAsync (dir, options, callback, internalOptions) { /***/ }), -/* 901 */ +/* 893 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -105812,7 +105469,7 @@ module.exports = function maybe (cb, promise) { /***/ }), -/* 902 */ +/* 894 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -105848,7 +105505,7 @@ function asyncForEach (array, iterator, done) { /***/ }), -/* 903 */ +/* 895 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -105856,11 +105513,11 @@ function asyncForEach (array, iterator, done) { module.exports = readdirStream; -const DirectoryReader = __webpack_require__(893); +const DirectoryReader = __webpack_require__(885); let streamFacade = { - fs: __webpack_require__(23), - forEach: __webpack_require__(902), + fs: __webpack_require__(349), + forEach: __webpack_require__(894), async: true }; @@ -105880,16 +105537,16 @@ function readdirStream (dir, options, internalOptions) { /***/ }), -/* 904 */ +/* 896 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -var path = __webpack_require__(16); -var deep_1 = __webpack_require__(905); -var entry_1 = __webpack_require__(907); -var pathUtil = __webpack_require__(906); +var path = __webpack_require__(4); +var deep_1 = __webpack_require__(897); +var entry_1 = __webpack_require__(899); +var pathUtil = __webpack_require__(898); var Reader = /** @class */ (function () { function Reader(options) { this.options = options; @@ -105955,14 +105612,14 @@ exports.default = Reader; /***/ }), -/* 905 */ +/* 897 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -var pathUtils = __webpack_require__(906); -var patternUtils = __webpack_require__(723); +var pathUtils = __webpack_require__(898); +var patternUtils = __webpack_require__(715); var DeepFilter = /** @class */ (function () { function DeepFilter(options, micromatchOptions) { this.options = options; @@ -106045,13 +105702,13 @@ exports.default = DeepFilter; /***/ }), -/* 906 */ +/* 898 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -var path = __webpack_require__(16); +var path = __webpack_require__(4); /** * Returns «true» if the last partial of the path starting with a period. */ @@ -106076,14 +105733,14 @@ exports.makeAbsolute = makeAbsolute; /***/ }), -/* 907 */ +/* 899 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -var pathUtils = __webpack_require__(906); -var patternUtils = __webpack_require__(723); +var pathUtils = __webpack_require__(898); +var patternUtils = __webpack_require__(715); var EntryFilter = /** @class */ (function () { function EntryFilter(options, micromatchOptions) { this.options = options; @@ -106168,7 +105825,7 @@ exports.default = EntryFilter; /***/ }), -/* 908 */ +/* 900 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -106187,9 +105844,9 @@ var __extends = (this && this.__extends) || (function () { }; })(); Object.defineProperty(exports, "__esModule", { value: true }); -var stream = __webpack_require__(27); -var fsStat = __webpack_require__(909); -var fs_1 = __webpack_require__(913); +var stream = __webpack_require__(382); +var fsStat = __webpack_require__(901); +var fs_1 = __webpack_require__(905); var FileSystemStream = /** @class */ (function (_super) { __extends(FileSystemStream, _super); function FileSystemStream() { @@ -106239,14 +105896,14 @@ exports.default = FileSystemStream; /***/ }), -/* 909 */ +/* 901 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const optionsManager = __webpack_require__(910); -const statProvider = __webpack_require__(912); +const optionsManager = __webpack_require__(902); +const statProvider = __webpack_require__(904); /** * Asynchronous API. */ @@ -106277,13 +105934,13 @@ exports.statSync = statSync; /***/ }), -/* 910 */ +/* 902 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const fsAdapter = __webpack_require__(911); +const fsAdapter = __webpack_require__(903); function prepare(opts) { const options = Object.assign({ fs: fsAdapter.getFileSystemAdapter(opts ? opts.fs : undefined), @@ -106296,13 +105953,13 @@ exports.prepare = prepare; /***/ }), -/* 911 */ +/* 903 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const fs = __webpack_require__(23); +const fs = __webpack_require__(349); exports.FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, stat: fs.stat, @@ -106319,7 +105976,7 @@ exports.getFileSystemAdapter = getFileSystemAdapter; /***/ }), -/* 912 */ +/* 904 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -106371,13 +106028,13 @@ exports.isFollowedSymlink = isFollowedSymlink; /***/ }), -/* 913 */ +/* 905 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -var path = __webpack_require__(16); +var path = __webpack_require__(4); var FileSystem = /** @class */ (function () { function FileSystem(options) { this.options = options; @@ -106402,7 +106059,7 @@ exports.default = FileSystem; /***/ }), -/* 914 */ +/* 906 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -106421,10 +106078,10 @@ var __extends = (this && this.__extends) || (function () { }; })(); Object.defineProperty(exports, "__esModule", { value: true }); -var stream = __webpack_require__(27); -var readdir = __webpack_require__(891); -var reader_1 = __webpack_require__(904); -var fs_stream_1 = __webpack_require__(908); +var stream = __webpack_require__(382); +var readdir = __webpack_require__(883); +var reader_1 = __webpack_require__(896); +var fs_stream_1 = __webpack_require__(900); var TransformStream = /** @class */ (function (_super) { __extends(TransformStream, _super); function TransformStream(reader) { @@ -106492,7 +106149,7 @@ exports.default = ReaderStream; /***/ }), -/* 915 */ +/* 907 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -106511,9 +106168,9 @@ var __extends = (this && this.__extends) || (function () { }; })(); Object.defineProperty(exports, "__esModule", { value: true }); -var readdir = __webpack_require__(891); -var reader_1 = __webpack_require__(904); -var fs_sync_1 = __webpack_require__(916); +var readdir = __webpack_require__(883); +var reader_1 = __webpack_require__(896); +var fs_sync_1 = __webpack_require__(908); var ReaderSync = /** @class */ (function (_super) { __extends(ReaderSync, _super); function ReaderSync() { @@ -106573,7 +106230,7 @@ exports.default = ReaderSync; /***/ }), -/* 916 */ +/* 908 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -106592,8 +106249,8 @@ var __extends = (this && this.__extends) || (function () { }; })(); Object.defineProperty(exports, "__esModule", { value: true }); -var fsStat = __webpack_require__(909); -var fs_1 = __webpack_require__(913); +var fsStat = __webpack_require__(901); +var fs_1 = __webpack_require__(905); var FileSystemSync = /** @class */ (function (_super) { __extends(FileSystemSync, _super); function FileSystemSync() { @@ -106639,7 +106296,7 @@ exports.default = FileSystemSync; /***/ }), -/* 917 */ +/* 909 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -106655,13 +106312,13 @@ exports.flatten = flatten; /***/ }), -/* 918 */ +/* 910 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -var merge2 = __webpack_require__(590); +var merge2 = __webpack_require__(585); /** * Merge multiple streams and propagate their errors into one stream in parallel. */ @@ -106676,13 +106333,13 @@ exports.merge = merge; /***/ }), -/* 919 */ +/* 911 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const path = __webpack_require__(16); -const pathType = __webpack_require__(920); +const path = __webpack_require__(4); +const pathType = __webpack_require__(912); const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0]; @@ -106748,13 +106405,13 @@ module.exports.sync = (input, opts) => { /***/ }), -/* 920 */ +/* 912 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const fs = __webpack_require__(23); -const pify = __webpack_require__(921); +const fs = __webpack_require__(349); +const pify = __webpack_require__(913); function type(fn, fn2, fp) { if (typeof fp !== 'string') { @@ -106797,7 +106454,7 @@ exports.symlinkSync = typeSync.bind(null, 'lstatSync', 'isSymbolicLink'); /***/ }), -/* 921 */ +/* 913 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -106888,17 +106545,17 @@ module.exports = (obj, opts) => { /***/ }), -/* 922 */ +/* 914 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const fs = __webpack_require__(23); -const path = __webpack_require__(16); -const fastGlob = __webpack_require__(719); -const gitIgnore = __webpack_require__(923); -const pify = __webpack_require__(924); -const slash = __webpack_require__(925); +const fs = __webpack_require__(349); +const path = __webpack_require__(4); +const fastGlob = __webpack_require__(711); +const gitIgnore = __webpack_require__(915); +const pify = __webpack_require__(916); +const slash = __webpack_require__(917); const DEFAULT_IGNORE = [ '**/node_modules/**', @@ -106996,7 +106653,7 @@ module.exports.sync = options => { /***/ }), -/* 923 */ +/* 915 */ /***/ (function(module, exports) { // A simple implementation of make-array @@ -107465,7 +107122,7 @@ module.exports = options => new IgnoreBase(options) /***/ }), -/* 924 */ +/* 916 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -107540,7 +107197,7 @@ module.exports = (input, options) => { /***/ }), -/* 925 */ +/* 917 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -107558,17 +107215,17 @@ module.exports = input => { /***/ }), -/* 926 */ +/* 918 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const path = __webpack_require__(16); -const {constants: fsConstants} = __webpack_require__(23); -const pEvent = __webpack_require__(927); -const CpFileError = __webpack_require__(930); -const fs = __webpack_require__(934); -const ProgressEmitter = __webpack_require__(937); +const path = __webpack_require__(4); +const {constants: fsConstants} = __webpack_require__(349); +const pEvent = __webpack_require__(919); +const CpFileError = __webpack_require__(922); +const fs = __webpack_require__(926); +const ProgressEmitter = __webpack_require__(929); const cpFileAsync = async (source, destination, options, progressEmitter) => { let readError; @@ -107682,12 +107339,12 @@ module.exports.sync = (source, destination, options) => { /***/ }), -/* 927 */ +/* 919 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const pTimeout = __webpack_require__(928); +const pTimeout = __webpack_require__(920); const symbolAsyncIterator = Symbol.asyncIterator || '@@asyncIterator'; @@ -107978,12 +107635,12 @@ module.exports.iterator = (emitter, event, options) => { /***/ }), -/* 928 */ +/* 920 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const pFinally = __webpack_require__(929); +const pFinally = __webpack_require__(921); class TimeoutError extends Error { constructor(message) { @@ -108029,7 +107686,7 @@ module.exports.TimeoutError = TimeoutError; /***/ }), -/* 929 */ +/* 921 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -108051,12 +107708,12 @@ module.exports = (promise, onFinally) => { /***/ }), -/* 930 */ +/* 922 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const NestedError = __webpack_require__(931); +const NestedError = __webpack_require__(923); class CpFileError extends NestedError { constructor(message, nested) { @@ -108070,10 +107727,10 @@ module.exports = CpFileError; /***/ }), -/* 931 */ +/* 923 */ /***/ (function(module, exports, __webpack_require__) { -var inherits = __webpack_require__(932); +var inherits = __webpack_require__(924); var NestedError = function (message, nested) { this.nested = nested; @@ -108124,20 +107781,20 @@ module.exports = NestedError; /***/ }), -/* 932 */ +/* 924 */ /***/ (function(module, exports, __webpack_require__) { try { - var util = __webpack_require__(29); + var util = __webpack_require__(397); if (typeof util.inherits !== 'function') throw ''; module.exports = util.inherits; } catch (e) { - module.exports = __webpack_require__(933); + module.exports = __webpack_require__(925); } /***/ }), -/* 933 */ +/* 925 */ /***/ (function(module, exports) { if (typeof Object.create === 'function') { @@ -108166,16 +107823,16 @@ if (typeof Object.create === 'function') { /***/ }), -/* 934 */ +/* 926 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const {promisify} = __webpack_require__(29); -const fs = __webpack_require__(22); -const makeDir = __webpack_require__(935); -const pEvent = __webpack_require__(927); -const CpFileError = __webpack_require__(930); +const {promisify} = __webpack_require__(397); +const fs = __webpack_require__(493); +const makeDir = __webpack_require__(927); +const pEvent = __webpack_require__(919); +const CpFileError = __webpack_require__(922); const stat = promisify(fs.stat); const lstat = promisify(fs.lstat); @@ -108272,15 +107929,15 @@ exports.copyFileSync = (source, destination, flags) => { /***/ }), -/* 935 */ +/* 927 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const fs = __webpack_require__(23); -const path = __webpack_require__(16); -const {promisify} = __webpack_require__(29); -const semver = __webpack_require__(936); +const fs = __webpack_require__(349); +const path = __webpack_require__(4); +const {promisify} = __webpack_require__(397); +const semver = __webpack_require__(928); const defaults = { mode: 0o777 & (~process.umask()), @@ -108429,7 +108086,7 @@ module.exports.sync = (input, options) => { /***/ }), -/* 936 */ +/* 928 */ /***/ (function(module, exports) { exports = module.exports = SemVer @@ -110031,12 +109688,12 @@ function coerce (version, options) { /***/ }), -/* 937 */ +/* 929 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const EventEmitter = __webpack_require__(399); +const EventEmitter = __webpack_require__(373); const written = new WeakMap(); @@ -110072,7 +109729,7 @@ module.exports = ProgressEmitter; /***/ }), -/* 938 */ +/* 930 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -110118,12 +109775,12 @@ exports.default = module.exports; /***/ }), -/* 939 */ +/* 931 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const NestedError = __webpack_require__(940); +const NestedError = __webpack_require__(932); class CpyError extends NestedError { constructor(message, nested) { @@ -110137,10 +109794,10 @@ module.exports = CpyError; /***/ }), -/* 940 */ +/* 932 */ /***/ (function(module, exports, __webpack_require__) { -var inherits = __webpack_require__(29).inherits; +var inherits = __webpack_require__(397).inherits; var NestedError = function (message, nested) { this.nested = nested; @@ -110193,7 +109850,7 @@ module.exports = NestedError; /***/ }), -/* 941 */ +/* 933 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; diff --git a/packages/kbn-pm/package.json b/packages/kbn-pm/package.json index 5938d15573d63..301d9653cda2b 100644 --- a/packages/kbn-pm/package.json +++ b/packages/kbn-pm/package.json @@ -22,7 +22,6 @@ "@types/glob": "^5.0.35", "@types/globby": "^6.1.0", "@types/has-ansi": "^3.0.0", - "@types/indent-string": "^3.0.0", "@types/lodash.clonedeepwith": "^4.5.3", "@types/log-symbols": "^2.0.0", "@types/ncp": "^2.0.1", @@ -32,7 +31,6 @@ "@types/strip-ansi": "^3.0.0", "@types/strong-log-transformer": "^1.0.0", "@types/tempy": "^0.2.0", - "@types/wrap-ansi": "^2.0.15", "@types/write-pkg": "^3.1.0", "@kbn/dev-utils": "1.0.0", "@yarnpkg/lockfile": "^1.1.0", @@ -47,7 +45,6 @@ "glob": "^7.1.2", "globby": "^8.0.1", "has-ansi": "^3.0.0", - "indent-string": "^3.2.0", "is-path-inside": "^3.0.2", "lodash.clonedeepwith": "^4.5.0", "log-symbols": "^2.2.0", @@ -66,7 +63,6 @@ "unlazy-loader": "^0.1.3", "webpack": "^4.41.5", "webpack-cli": "^3.3.10", - "wrap-ansi": "^3.0.1", "write-pkg": "^4.0.0" }, "dependencies": { diff --git a/packages/kbn-pm/src/cli.ts b/packages/kbn-pm/src/cli.ts index 94f348e1835ed..b72e9ae8690aa 100644 --- a/packages/kbn-pm/src/cli.ts +++ b/packages/kbn-pm/src/cli.ts @@ -17,46 +17,58 @@ * under the License. */ -import chalk from 'chalk'; import dedent from 'dedent'; import getopts from 'getopts'; import { resolve } from 'path'; +import { pickLevelFromFlags } from '@kbn/dev-utils'; import { commands } from './commands'; import { runCommand } from './run'; import { log } from './utils/log'; function help() { - const availableCommands = Object.keys(commands) - .map((commandName) => commands[commandName]) - .map((command) => `${command.name} - ${command.description}`); - - log.write(dedent` - usage: kbn [] - - By default commands are run for Kibana itself, all packages in the 'packages/' - folder and for all plugins in './plugins' and '../kibana-extra'. - - Available commands: - - ${availableCommands.join('\n ')} - - Global options: - - -e, --exclude Exclude specified project. Can be specified multiple times to exclude multiple projects, e.g. '-e kibana -e @kbn/pm'. - -i, --include Include only specified projects. If left unspecified, it defaults to including all projects. - --oss Do not include the x-pack when running command. - --skip-kibana-plugins Filter all plugins in ./plugins and ../kibana-extra when running command. - --no-cache Disable the bootstrap cache - `); + log.info( + dedent` + usage: kbn [] + + By default commands are run for Kibana itself, all packages in the 'packages/' + folder and for all plugins in './plugins' and '../kibana-extra'. + + Available commands: + + ${Object.values(commands) + .map((command) => `${command.name} - ${command.description}`) + .join('\n ')} + + Global options: + + -e, --exclude Exclude specified project. Can be specified multiple times to exclude multiple projects, e.g. '-e kibana -e @kbn/pm'. + -i, --include Include only specified projects. If left unspecified, it defaults to including all projects. + --oss Do not include the x-pack when running command. + --skip-kibana-plugins Filter all plugins in ./plugins and ../kibana-extra when running command. + --no-cache Disable the bootstrap cache + --verbose Set log level to verbose + --debug Set log level to debug + --quiet Set log level to error + --silent Disable log output + ` + '\n' + ); } export async function run(argv: string[]) { + log.setLogLevel( + pickLevelFromFlags( + getopts(argv, { + boolean: ['verbose', 'debug', 'quiet', 'silent'], + }) + ) + ); + // We can simplify this setup (and remove this extra handling) once Yarn // starts forwarding the `--` directly to this script, see // https://github.com/yarnpkg/yarn/blob/b2d3e1a8fe45ef376b716d597cc79b38702a9320/src/cli/index.js#L174-L182 if (argv.includes('--')) { - log.write(chalk.red(`Using "--" is not allowed, as it doesn't work with 'yarn kbn'.`)); + log.error(`Using "--" is not allowed, as it doesn't work with 'yarn kbn'.`); process.exit(1); } @@ -90,7 +102,7 @@ export async function run(argv: string[]) { const command = commands[commandName]; if (command === undefined) { - log.write(chalk.red(`[${commandName}] is not a valid command, see 'kbn --help'`)); + log.error(`[${commandName}] is not a valid command, see 'kbn --help'`); process.exit(1); } diff --git a/packages/kbn-pm/src/commands/__snapshots__/bootstrap.test.ts.snap b/packages/kbn-pm/src/commands/__snapshots__/bootstrap.test.ts.snap index c0505710f5670..be146d710c87a 100644 --- a/packages/kbn-pm/src/commands/__snapshots__/bootstrap.test.ts.snap +++ b/packages/kbn-pm/src/commands/__snapshots__/bootstrap.test.ts.snap @@ -90,29 +90,32 @@ Array [ exports[`calls "kbn:bootstrap" scripts and links executables after installing deps: script 1`] = ` Array [ Array [ - "kbn:bootstrap", - Array [], - Project { - "allDependencies": Object {}, - "devDependencies": Object {}, - "isWorkspaceProject": false, - "isWorkspaceRoot": false, - "json": Object { - "name": "bar", + Object { + "args": Array [], + "debug": undefined, + "pkg": Project { + "allDependencies": Object {}, + "devDependencies": Object {}, + "isWorkspaceProject": false, + "isWorkspaceRoot": false, + "json": Object { + "name": "bar", + "scripts": Object { + "kbn:bootstrap": "node ./bar.js", + }, + "version": "1.0.0", + }, + "nodeModulesLocation": "/packages/kbn-pm/src/commands/packages/bar/node_modules", + "packageJsonLocation": "/packages/kbn-pm/src/commands/packages/bar/package.json", + "path": "/packages/kbn-pm/src/commands/packages/bar", + "productionDependencies": Object {}, "scripts": Object { "kbn:bootstrap": "node ./bar.js", }, + "targetLocation": "/packages/kbn-pm/src/commands/packages/bar/target", "version": "1.0.0", }, - "nodeModulesLocation": "/packages/kbn-pm/src/commands/packages/bar/node_modules", - "packageJsonLocation": "/packages/kbn-pm/src/commands/packages/bar/package.json", - "path": "/packages/kbn-pm/src/commands/packages/bar", - "productionDependencies": Object {}, - "scripts": Object { - "kbn:bootstrap": "node ./bar.js", - }, - "targetLocation": "/packages/kbn-pm/src/commands/packages/bar/target", - "version": "1.0.0", + "script": "kbn:bootstrap", }, ], ] @@ -127,36 +130,6 @@ Array [ ] `; -exports[`does not run installer if no deps in package: logs 1`] = ` -Array [ - Array [ - " -Running installs in topological order:", - ], - Array [ - " - -Installing dependencies in [kibana]: -", - ], - Array [ - " -Installs completed, linking package executables: -", - ], - Array [ - " -Linking executables completed, running \`kbn:bootstrap\` scripts -", - ], - Array [ - " -Bootstrapping completed! -", - ], -] -`; - exports[`handles "frozen-lockfile": install in dir 1`] = ` Array [ Array [ @@ -184,45 +157,3 @@ Array [ ], ] `; - -exports[`handles dependencies of dependencies: logs 1`] = ` -Array [ - Array [ - " -Running installs in topological order:", - ], - Array [ - " - -Installing dependencies in [kibana]: -", - ], - Array [ - " - -Installing dependencies in [bar]: -", - ], - Array [ - " - -Installing dependencies in [foo]: -", - ], - Array [ - " -Installs completed, linking package executables: -", - ], - Array [ - " -Linking executables completed, running \`kbn:bootstrap\` scripts -", - ], - Array [ - " -Bootstrapping completed! -", - ], -] -`; diff --git a/packages/kbn-pm/src/commands/bootstrap.test.ts b/packages/kbn-pm/src/commands/bootstrap.test.ts index 072f34611f8fc..d6a30f0ef33d6 100644 --- a/packages/kbn-pm/src/commands/bootstrap.test.ts +++ b/packages/kbn-pm/src/commands/bootstrap.test.ts @@ -22,6 +22,8 @@ jest.mock('../utils/link_project_executables'); import { resolve } from 'path'; +import { ToolingLogCollectingWriter } from '@kbn/dev-utils'; + import { absolutePathSnapshotSerializer, stripAnsiSnapshotSerializer } from '../test_helpers'; import { linkProjectExecutables } from '../utils/link_project_executables'; import { IPackageJson } from '../utils/package_json'; @@ -30,12 +32,20 @@ import { buildProjectGraph } from '../utils/projects'; import { installInDir, runScriptInPackageStreaming, yarnWorkspacesInfo } from '../utils/scripts'; import { BootstrapCommand } from './bootstrap'; import { Kibana } from '../utils/kibana'; +import { log } from '../utils/log'; const mockInstallInDir = installInDir as jest.Mock; const mockRunScriptInPackageStreaming = runScriptInPackageStreaming as jest.Mock; const mockLinkProjectExecutables = linkProjectExecutables as jest.Mock; const mockYarnWorkspacesInfo = yarnWorkspacesInfo as jest.Mock; +const logWriter = new ToolingLogCollectingWriter('debug'); +log.setLogLevel('silent'); +log.setWriters([logWriter]); +beforeEach(() => { + logWriter.messages.length = 0; +}); + const createProject = (packageJson: IPackageJson, path = '.') => { const project = new Project( { @@ -55,10 +65,6 @@ const createProject = (packageJson: IPackageJson, path = '.') => { expect.addSnapshotSerializer(absolutePathSnapshotSerializer); expect.addSnapshotSerializer(stripAnsiSnapshotSerializer); -const noop = () => { - // noop -}; - beforeEach(() => { mockYarnWorkspacesInfo.mockResolvedValue({}); }); @@ -111,8 +117,6 @@ test('handles dependencies of dependencies', async () => { const kbn = new Kibana(projects); const projectGraph = buildProjectGraph(projects); - const logMock = jest.spyOn(console, 'log').mockImplementation(noop); - await BootstrapCommand.run(projects, projectGraph, { extraArgs: [], options: {}, @@ -121,7 +125,19 @@ test('handles dependencies of dependencies', async () => { }); expect(mockInstallInDir.mock.calls).toMatchSnapshot('install in dir'); - expect(logMock.mock.calls).toMatchSnapshot('logs'); + expect(logWriter.messages).toMatchInlineSnapshot(` + Array [ + " info [kibana] running yarn", + "", + "", + " info [bar] running yarn", + "", + "", + " info [foo] running yarn", + "", + "", + ] + `); }); test('does not run installer if no deps in package', async () => { @@ -148,8 +164,6 @@ test('does not run installer if no deps in package', async () => { const kbn = new Kibana(projects); const projectGraph = buildProjectGraph(projects); - const logMock = jest.spyOn(console, 'log').mockImplementation(noop); - await BootstrapCommand.run(projects, projectGraph, { extraArgs: [], options: {}, @@ -158,7 +172,13 @@ test('does not run installer if no deps in package', async () => { }); expect(mockInstallInDir.mock.calls).toMatchSnapshot('install in dir'); - expect(logMock.mock.calls).toMatchSnapshot('logs'); + expect(logWriter.messages).toMatchInlineSnapshot(` + Array [ + " info [kibana] running yarn", + "", + "", + ] + `); }); test('handles "frozen-lockfile"', async () => { @@ -175,8 +195,6 @@ test('handles "frozen-lockfile"', async () => { const kbn = new Kibana(projects); const projectGraph = buildProjectGraph(projects); - jest.spyOn(console, 'log').mockImplementation(noop); - await BootstrapCommand.run(projects, projectGraph, { extraArgs: [], options: { @@ -215,8 +233,6 @@ test('calls "kbn:bootstrap" scripts and links executables after installing deps' const kbn = new Kibana(projects); const projectGraph = buildProjectGraph(projects); - jest.spyOn(console, 'log').mockImplementation(noop); - await BootstrapCommand.run(projects, projectGraph, { extraArgs: [], options: {}, diff --git a/packages/kbn-pm/src/commands/bootstrap.ts b/packages/kbn-pm/src/commands/bootstrap.ts index 6146aeab21db4..80ccc5daecc56 100644 --- a/packages/kbn-pm/src/commands/bootstrap.ts +++ b/packages/kbn-pm/src/commands/bootstrap.ts @@ -17,12 +17,11 @@ * under the License. */ -import chalk from 'chalk'; - import { linkProjectExecutables } from '../utils/link_project_executables'; import { log } from '../utils/log'; import { parallelizeBatches } from '../utils/parallelize'; import { topologicallyBatchProjects } from '../utils/projects'; +import { Project } from '../utils/project'; import { ICommand } from './'; import { getAllChecksums } from '../utils/project_checksums'; import { BootstrapCacheFile } from '../utils/bootstrap_cache_file'; @@ -42,12 +41,10 @@ export const BootstrapCommand: ICommand = { ...(options['prefer-offline'] === true ? ['--prefer-offline'] : []), ]; - log.write(chalk.bold('\nRunning installs in topological order:')); - for (const batch of batchedProjectsByWorkspace) { for (const project of batch) { if (project.isWorkspaceProject) { - log.write(`Skipping workspace project: ${project.name}`); + log.verbose(`Skipping workspace project: ${project.name}`); continue; } @@ -57,7 +54,6 @@ export const BootstrapCommand: ICommand = { } } - log.write(chalk.bold('\nInstalls completed, linking package executables:\n')); await linkProjectExecutables(projects, projectGraph); /** @@ -66,22 +62,38 @@ export const BootstrapCommand: ICommand = { * transpiled before they can be used. Ideally we shouldn't do this unless we * have to, as it will slow down the bootstrapping process. */ - log.write(chalk.bold('\nLinking executables completed, running `kbn:bootstrap` scripts\n')); - const checksums = options.cache ? await getAllChecksums(kbn, log) : false; - await parallelizeBatches(batchedProjects, async (project) => { + const checksums = await getAllChecksums(kbn, log); + const caches = new Map(); + let cachedProjectCount = 0; + + for (const project of projects.values()) { if (project.hasScript('kbn:bootstrap')) { - const cacheFile = new BootstrapCacheFile(kbn, project, checksums); - if (cacheFile.isValid()) { - log.success(`[${project.name}] cache up to date`); - } else { - cacheFile.delete(); - await project.runScriptStreaming('kbn:bootstrap'); - cacheFile.write(); + const file = new BootstrapCacheFile(kbn, project, checksums); + const valid = options.cache && file.isValid(); + + if (valid) { + log.debug(`[${project.name}] cache up to date`); } + + caches.set(project, { file, valid }); + cachedProjectCount += 1; } - }); + } + + if (cachedProjectCount > 0) { + log.success(`${cachedProjectCount} bootsrap builds are cached`); + } - log.write(chalk.green.bold('\nBootstrapping completed!\n')); + await parallelizeBatches(batchedProjects, async (project) => { + const cache = caches.get(project); + if (cache && !cache.valid) { + log.info(`[${project.name}] running [kbn:bootstrap] script`); + cache.file.delete(); + await project.runScriptStreaming('kbn:bootstrap'); + cache.file.write(); + log.success(`[${project.name}] bootstrap complete`); + } + }); }, }; diff --git a/packages/kbn-pm/src/commands/clean.ts b/packages/kbn-pm/src/commands/clean.ts index b3d433e22bd79..26d6897992501 100644 --- a/packages/kbn-pm/src/commands/clean.ts +++ b/packages/kbn-pm/src/commands/clean.ts @@ -17,7 +17,6 @@ * under the License. */ -import chalk from 'chalk'; import del from 'del'; import ora from 'ora'; import { join, relative } from 'path'; @@ -57,10 +56,8 @@ export const CleanCommand: ICommand = { } if (toDelete.length === 0) { - log.write(chalk.bold.green('\n\nNothing to delete')); + log.success('Nothing to delete'); } else { - log.write(chalk.bold.red('\n\nDeleting:\n')); - /** * In order to avoid patterns like `/build` in packages from accidentally * impacting files outside the package we use `process.chdir()` to change @@ -75,7 +72,11 @@ export const CleanCommand: ICommand = { for (const { pattern, cwd } of toDelete) { process.chdir(cwd); const promise = del(pattern); - ora.promise(promise, relative(originalCwd, join(cwd, String(pattern)))); + + if (log.wouldLogLevel('info')) { + ora.promise(promise, relative(originalCwd, join(cwd, String(pattern)))); + } + await promise; } } finally { diff --git a/packages/kbn-pm/src/commands/run.ts b/packages/kbn-pm/src/commands/run.ts index 989bfef19c380..1c6760ed6f3ee 100644 --- a/packages/kbn-pm/src/commands/run.ts +++ b/packages/kbn-pm/src/commands/run.ts @@ -17,8 +17,7 @@ * under the License. */ -import chalk from 'chalk'; - +import { CliError } from '../utils/errors'; import { log } from '../utils/log'; import { parallelizeBatches } from '../utils/parallelize'; import { topologicallyBatchProjects } from '../utils/projects'; @@ -32,20 +31,19 @@ export const RunCommand: ICommand = { const batchedProjects = topologicallyBatchProjects(projects, projectGraph); if (extraArgs.length === 0) { - log.write(chalk.red.bold('\nNo script specified')); - process.exit(1); + throw new CliError('No script specified'); } const scriptName = extraArgs[0]; const scriptArgs = extraArgs.slice(1); - log.write( - chalk.bold(`\nRunning script [${chalk.green(scriptName)}] in batched topological order\n`) - ); - - await parallelizeBatches(batchedProjects, async (pkg) => { - if (pkg.hasScript(scriptName)) { - await pkg.runScriptStreaming(scriptName, scriptArgs); + await parallelizeBatches(batchedProjects, async (project) => { + if (project.hasScript(scriptName)) { + log.info(`[${project.name}] running "${scriptName}" script`); + await project.runScriptStreaming(scriptName, { + args: scriptArgs, + }); + log.success(`[${project.name}] complete`); } }); }, diff --git a/packages/kbn-pm/src/commands/watch.ts b/packages/kbn-pm/src/commands/watch.ts index 2e18b02a1c860..6775f728c1494 100644 --- a/packages/kbn-pm/src/commands/watch.ts +++ b/packages/kbn-pm/src/commands/watch.ts @@ -17,7 +17,7 @@ * under the License. */ -import chalk from 'chalk'; +import { CliError } from '../utils/errors'; import { log } from '../utils/log'; import { parallelizeBatches } from '../utils/parallelize'; import { ProjectMap, topologicallyBatchProjects } from '../utils/projects'; @@ -58,20 +58,13 @@ export const WatchCommand: ICommand = { } if (projectsToWatch.size === 0) { - log.write( - chalk.red( - `\nThere are no projects to watch found. Make sure that projects define 'kbn:watch' script in 'package.json'.\n` - ) + throw new CliError( + `There are no projects to watch found. Make sure that projects define 'kbn:watch' script in 'package.json'.` ); - return; } const projectNames = Array.from(projectsToWatch.keys()); - log.write( - chalk.bold( - chalk.green(`Running ${watchScriptName} scripts for [${projectNames.join(', ')}].`) - ) - ); + log.info(`Running ${watchScriptName} scripts for [${projectNames.join(', ')}].`); // Kibana should always be run the last, so we don't rely on automatic // topological batching and push it to the last one-entry batch manually. @@ -85,12 +78,12 @@ export const WatchCommand: ICommand = { await parallelizeBatches(batchedProjects, async (pkg) => { const completionHint = await waitUntilWatchIsReady( - pkg.runScriptStreaming(watchScriptName).stdout + pkg.runScriptStreaming(watchScriptName, { + debug: false, + }).stdout ); - log.write( - chalk.bold(`[${chalk.green(pkg.name)}] Initial build completed (${completionHint}).`) - ); + log.success(`[${pkg.name}] Initial build completed (${completionHint}).`); }); }, }; diff --git a/packages/kbn-pm/src/production/build_production_projects.ts b/packages/kbn-pm/src/production/build_production_projects.ts index 689bf51cd7bdf..f5c59fd582c59 100644 --- a/packages/kbn-pm/src/production/build_production_projects.ts +++ b/packages/kbn-pm/src/production/build_production_projects.ts @@ -47,7 +47,7 @@ export async function buildProductionProjects({ const batchedProjects = topologicallyBatchProjects(projects, projectGraph); const projectNames = [...projects.values()].map((project) => project.name); - log.write(`Preparing production build for [${projectNames.join(', ')}]`); + log.info(`Preparing production build for [${projectNames.join(', ')}]`); for (const batch of batchedProjects) { for (const project of batch) { diff --git a/packages/kbn-pm/src/run.test.ts b/packages/kbn-pm/src/run.test.ts index ff0dc2666afea..b2479af3809c4 100644 --- a/packages/kbn-pm/src/run.test.ts +++ b/packages/kbn-pm/src/run.test.ts @@ -18,9 +18,13 @@ */ import { resolve } from 'path'; + import { ICommand, ICommandConfig } from './commands'; import { runCommand } from './run'; import { Project } from './utils/project'; +import { log } from './utils/log'; + +log.setLogLevel('silent'); const rootPath = resolve(`${__dirname}/utils/__fixtures__/kibana`); @@ -51,11 +55,6 @@ beforeEach(() => { options: {}, rootPath, }; - - // Reduce the noise that comes from the run command. - jest.spyOn(console, 'log').mockImplementation(() => { - // noop - }); }); test('passes all found projects to the command if no filter is specified', async () => { diff --git a/packages/kbn-pm/src/run.ts b/packages/kbn-pm/src/run.ts index c3879c701d785..04286590bd821 100644 --- a/packages/kbn-pm/src/run.ts +++ b/packages/kbn-pm/src/run.ts @@ -17,10 +17,6 @@ * under the License. */ -import chalk from 'chalk'; -import indentString from 'indent-string'; -import wrapAnsi from 'wrap-ansi'; - import { ICommand, ICommandConfig } from './commands'; import { CliError } from './utils/errors'; import { log } from './utils/log'; @@ -30,11 +26,7 @@ import { Kibana } from './utils/kibana'; export async function runCommand(command: ICommand, config: Omit) { try { - log.write( - chalk.bold( - `Running [${chalk.green(command.name)}] command from [${chalk.yellow(config.rootPath)}]:\n` - ) - ); + log.debug(`Running [${command.name}] command from [${config.rootPath}]`); const kbn = await Kibana.loadFrom(config.rootPath); const projects = kbn.getFilteredProjects({ @@ -45,42 +37,39 @@ export async function runCommand(command: ICommand, config: Omit 0) { - const metaOutput = keys.map((key) => { - const value = e.meta[key]; - return `${key}: ${value}`; - }); + const metaOutput = Object.entries(error.meta) + .map(([key, value]) => `${key}: ${value}`) + .join('\n'); - log.write('Additional debugging info:\n'); - log.write(indentString(metaOutput.join('\n'), 3)); + if (metaOutput) { + log.info('Additional debugging info:\n'); + log.indent(2); + log.info(metaOutput); + log.indent(-2); } } else { - log.write(e.stack); + log.error(error); } process.exit(1); diff --git a/packages/kbn-pm/src/utils/__snapshots__/link_project_executables.test.ts.snap b/packages/kbn-pm/src/utils/__snapshots__/link_project_executables.test.ts.snap index 62091205b01a4..5bda7b544e201 100644 --- a/packages/kbn-pm/src/utils/__snapshots__/link_project_executables.test.ts.snap +++ b/packages/kbn-pm/src/utils/__snapshots__/link_project_executables.test.ts.snap @@ -68,14 +68,3 @@ Object { "unlink": Array [], } `; - -exports[`bin script points to a file creates a symlink in the project node_modules/.bin directory: logs 1`] = ` -Array [ - Array [ - "[foo] bar -> ../bar/bin/bar.js", - ], - Array [ - "[baz] bar -> ../bar/bin/bar.js", - ], -] -`; diff --git a/packages/kbn-pm/src/utils/child_process.ts b/packages/kbn-pm/src/utils/child_process.ts index 784446924a8dc..bafe2bf57adc2 100644 --- a/packages/kbn-pm/src/utils/child_process.ts +++ b/packages/kbn-pm/src/utils/child_process.ts @@ -17,19 +17,20 @@ * under the License. */ +import { Writable } from 'stream'; + import chalk from 'chalk'; import execa from 'execa'; -import logSymbols from 'log-symbols'; import logTransformer from 'strong-log-transformer'; -function generateColors() { - const colorWheel = [chalk.cyan, chalk.magenta, chalk.blue, chalk.yellow, chalk.green]; - - const count = colorWheel.length; - let children = 0; +import { log } from './log'; - return () => colorWheel[children++ % count]; -} +const colorWheel = [chalk.cyan, chalk.magenta, chalk.blue, chalk.yellow, chalk.green]; +const getColor = () => { + const color = colorWheel.shift()!; + colorWheel.push(color); + return color; +}; export function spawn(command: string, args: string[], opts: execa.Options) { return execa(command, args, { @@ -39,13 +40,26 @@ export function spawn(command: string, args: string[], opts: execa.Options) { }); } -const nextColor = generateColors(); +function streamToLog(debug: boolean = true) { + return new Writable({ + objectMode: true, + write(line, _, cb) { + if (line.endsWith('\n')) { + log[debug ? 'debug' : 'write'](line.slice(0, -1)); + } else { + log[debug ? 'debug' : 'write'](line); + } + + cb(); + }, + }); +} export function spawnStreaming( command: string, args: string[], opts: execa.Options, - { prefix }: { prefix: string } + { prefix, debug }: { prefix: string; debug?: boolean } ) { const spawned = execa(command, args, { stdio: ['ignore', 'pipe', 'pipe'], @@ -53,15 +67,12 @@ export function spawnStreaming( ...opts, }); - const color = nextColor(); - const prefixedStdout = logTransformer({ tag: `${color.bold(prefix)}:` }); - const prefixedStderr = logTransformer({ - mergeMultiline: true, - tag: `${logSymbols.error} ${color.bold(prefix)}:`, - }); + const color = getColor(); + const prefixedStdout = logTransformer({ tag: color.bold(prefix) }); + const prefixedStderr = logTransformer({ mergeMultiline: true, tag: color.bold(prefix) }); - spawned.stdout.pipe(prefixedStdout).pipe(process.stdout); - spawned.stderr.pipe(prefixedStderr).pipe(process.stderr); + spawned.stdout.pipe(prefixedStdout).pipe(streamToLog(debug)); + spawned.stderr.pipe(prefixedStderr).pipe(streamToLog(debug)); return spawned; } diff --git a/packages/kbn-pm/src/utils/link_project_executables.test.ts b/packages/kbn-pm/src/utils/link_project_executables.test.ts index a19e1fd66f334..887c474a12eca 100644 --- a/packages/kbn-pm/src/utils/link_project_executables.test.ts +++ b/packages/kbn-pm/src/utils/link_project_executables.test.ts @@ -23,10 +23,19 @@ jest.mock('./fs'); import { resolve } from 'path'; +import { ToolingLogCollectingWriter } from '@kbn/dev-utils'; + import { absolutePathSnapshotSerializer, stripAnsiSnapshotSerializer } from '../test_helpers'; import { linkProjectExecutables } from './link_project_executables'; import { Project } from './project'; import { buildProjectGraph } from './projects'; +import { log } from './log'; + +const logWriter = new ToolingLogCollectingWriter(); +log.setWriters([logWriter]); +beforeEach(() => { + logWriter.messages.length = 0; +}); const projectsByName = new Map([ [ @@ -101,12 +110,15 @@ describe('bin script points to a file', () => { const fs = require('./fs'); fs.isFile.mockReturnValue(true); - const logMock = jest.spyOn(console, 'log').mockImplementation(() => { - // noop - }); await linkProjectExecutables(projectsByName, projectGraph); expect(getFsMockCalls()).toMatchSnapshot('fs module calls'); - expect(logMock.mock.calls).toMatchSnapshot('logs'); + expect(logWriter.messages).toMatchInlineSnapshot(` + Array [ + " debg Linking package executables", + " debg [foo] bar -> ../bar/bin/bar.js", + " debg [baz] bar -> ../bar/bin/bar.js", + ] + `); }); }); diff --git a/packages/kbn-pm/src/utils/link_project_executables.ts b/packages/kbn-pm/src/utils/link_project_executables.ts index b403dfb2ecf2e..f7362788b417d 100644 --- a/packages/kbn-pm/src/utils/link_project_executables.ts +++ b/packages/kbn-pm/src/utils/link_project_executables.ts @@ -19,8 +19,6 @@ import { dirname, relative, resolve, sep } from 'path'; -import chalk from 'chalk'; - import { chmod, createSymlink, isFile, mkdirp } from './fs'; import { log } from './log'; import { ProjectGraph, ProjectMap } from './projects'; @@ -37,6 +35,7 @@ export async function linkProjectExecutables( projectsByName: ProjectMap, projectGraph: ProjectGraph ) { + log.debug(`Linking package executables`); for (const [projectName, projectDeps] of projectGraph) { const project = projectsByName.get(projectName)!; const binsDir = resolve(project.nodeModulesLocation, '.bin'); @@ -57,7 +56,7 @@ export async function linkProjectExecutables( // Get relative project path with normalized path separators. const projectRelativePath = relative(project.path, srcPath).split(sep).join('/'); - log.write(chalk`{dim [${project.name}]} ${name} -> {dim ${projectRelativePath}}`); + log.debug(`[${project.name}] ${name} -> ${projectRelativePath}`); await mkdirp(dirname(dest)); await createSymlink(srcPath, dest, 'exec'); diff --git a/packages/kbn-pm/src/utils/log.ts b/packages/kbn-pm/src/utils/log.ts index 9e5630be5bd19..786ff8b19ef4e 100644 --- a/packages/kbn-pm/src/utils/log.ts +++ b/packages/kbn-pm/src/utils/log.ts @@ -17,27 +17,36 @@ * under the License. */ -import { ToolingLog, ToolingLogCollectingWriter } from '@kbn/dev-utils'; +import { + ToolingLog, + ToolingLogTextWriter, + LogLevel, + parseLogLevel, + ParsedLogLevel, +} from '@kbn/dev-utils'; class Log extends ToolingLog { - testWriter?: ToolingLogCollectingWriter; + private logLevel!: ParsedLogLevel; constructor() { - super({ - level: 'info', - writeTo: process.stdout, - }); + super(); + this.setLogLevel('info'); } - /** - * Log something to the console. Ideally we would use a real logger in - * kbn-pm, but that's a pretty big change for now. - * @param ...args - */ - write(...args: any[]) { - // eslint-disable-next-line no-console - console.log(...args); + setLogLevel(level: LogLevel) { + this.logLevel = parseLogLevel(level); + this.setWriters([ + new ToolingLogTextWriter({ + level: this.logLevel.name, + writeTo: process.stdout, + }), + ]); + } + + wouldLogLevel(level: LogLevel) { + return this.logLevel.flags[level]; } } export const log = new Log(); +export { LogLevel, Log }; diff --git a/packages/kbn-pm/src/utils/project.ts b/packages/kbn-pm/src/utils/project.ts index 91a3a5365b60e..8f45df52c7a2f 100644 --- a/packages/kbn-pm/src/utils/project.ts +++ b/packages/kbn-pm/src/utils/project.ts @@ -17,7 +17,6 @@ * under the License. */ -import chalk from 'chalk'; import fs from 'fs'; import Path from 'path'; import { inspect } from 'util'; @@ -190,16 +189,20 @@ export class Project { } public async runScript(scriptName: string, args: string[] = []) { - log.write( - chalk.bold( - `\n\nRunning script [${chalk.green(scriptName)}] in [${chalk.green(this.name)}]:\n` - ) - ); + log.info(`Running script [${scriptName}] in [${this.name}]:`); return runScriptInPackage(scriptName, args, this); } - public runScriptStreaming(scriptName: string, args: string[] = []) { - return runScriptInPackageStreaming(scriptName, args, this); + public runScriptStreaming( + scriptName: string, + options: { args?: string[]; debug?: boolean } = {} + ) { + return runScriptInPackageStreaming({ + script: scriptName, + args: options.args || [], + pkg: this, + debug: options.debug, + }); } public hasDependencies() { @@ -207,8 +210,12 @@ export class Project { } public async installDependencies({ extraArgs }: { extraArgs: string[] }) { - log.write(chalk.bold(`\n\nInstalling dependencies in [${chalk.green(this.name)}]:\n`)); + log.info(`[${this.name}] running yarn`); + + log.write(''); await installInDir(this.path, extraArgs); + log.write(''); + await this.removeExtraneousNodeModules(); } @@ -239,7 +246,7 @@ export class Project { const isDevDependency = devDependencies && devDependencies.hasOwnProperty(name); if (!isDependency && !isDevDependency && fs.existsSync(nodeModulesPath)) { - log.write(`No dependency on ${name}, removing link in node_modules`); + log.debug(`No dependency on ${name}, removing link in node_modules`); fs.unlinkSync(nodeModulesPath); } }); diff --git a/packages/kbn-pm/src/utils/project_checksums.ts b/packages/kbn-pm/src/utils/project_checksums.ts index 46dde1b32c158..839c44f4f18c4 100644 --- a/packages/kbn-pm/src/utils/project_checksums.ts +++ b/packages/kbn-pm/src/utils/project_checksums.ts @@ -23,12 +23,12 @@ import Crypto from 'crypto'; import { promisify } from 'util'; import execa from 'execa'; -import { ToolingLog } from '@kbn/dev-utils'; import { readYarnLock, YarnLock } from './yarn_lock'; import { ProjectMap } from '../utils/projects'; import { Project } from '../utils/project'; import { Kibana } from '../utils/kibana'; +import { Log } from '../utils/log'; export type ChecksumMap = Map; /** map of [repo relative path to changed file, type of change] */ @@ -38,7 +38,7 @@ const statAsync = promisify(Fs.stat); const projectBySpecificitySorter = (a: Project, b: Project) => b.path.length - a.path.length; /** Get the changed files for a set of projects */ -async function getChangesForProjects(projects: ProjectMap, kbn: Kibana, log: ToolingLog) { +async function getChangesForProjects(projects: ProjectMap, kbn: Kibana, log: Log) { log.verbose('getting changed files'); const { stdout } = await execa( @@ -150,7 +150,7 @@ async function getLatestSha(project: Project, kbn: Kibana) { * in the yarn.lock file, does not include other projects in the workspace * or their dependencies */ -function resolveDepsForProject(project: Project, yarnLock: YarnLock, kbn: Kibana, log: ToolingLog) { +function resolveDepsForProject(project: Project, yarnLock: YarnLock, kbn: Kibana, log: Log) { /** map of [name@range, name@resolved] */ const resolved = new Map(); @@ -198,7 +198,7 @@ async function getChecksum( changes: Changes | undefined, yarnLock: YarnLock, kbn: Kibana, - log: ToolingLog + log: Log ) { const sha = await getLatestSha(project, kbn); if (sha) { @@ -256,7 +256,7 @@ async function getChecksum( * - un-committed changes * - resolved dependencies from yarn.lock referenced by project package.json */ -export async function getAllChecksums(kbn: Kibana, log: ToolingLog) { +export async function getAllChecksums(kbn: Kibana, log: Log) { const projects = kbn.getAllProjects(); const changesByProject = await getChangesForProjects(projects, kbn, log); const yarnLock = await readYarnLock(kbn); diff --git a/packages/kbn-pm/src/utils/scripts.ts b/packages/kbn-pm/src/utils/scripts.ts index 009efa1285c0c..6b1dc729906f2 100644 --- a/packages/kbn-pm/src/utils/scripts.ts +++ b/packages/kbn-pm/src/utils/scripts.ts @@ -20,6 +20,8 @@ import { spawn, spawnStreaming } from './child_process'; import { Project } from './project'; +const YARN_EXEC = process.env.npm_execpath || 'yarn'; + interface WorkspaceInfo { location: string; workspaceDependencies: string[]; @@ -37,7 +39,7 @@ export async function installInDir(directory: string, extraArgs: string[] = []) // We pass the mutex flag to ensure only one instance of yarn runs at any // given time (e.g. to avoid conflicts). - await spawn('yarn', options, { + await spawn(YARN_EXEC, options, { cwd: directory, }); } @@ -50,24 +52,35 @@ export async function runScriptInPackage(script: string, args: string[], pkg: Pr cwd: pkg.path, }; - await spawn('yarn', ['run', script, ...args], execOpts); + await spawn(YARN_EXEC, ['run', script, ...args], execOpts); } /** * Run script in the given directory */ -export function runScriptInPackageStreaming(script: string, args: string[], pkg: Project) { +export function runScriptInPackageStreaming({ + script, + args, + pkg, + debug, +}: { + script: string; + args: string[]; + pkg: Project; + debug?: boolean; +}) { const execOpts = { cwd: pkg.path, }; - return spawnStreaming('yarn', ['run', script, ...args], execOpts, { + return spawnStreaming(YARN_EXEC, ['run', script, ...args], execOpts, { prefix: pkg.name, + debug, }); } export async function yarnWorkspacesInfo(directory: string): Promise { - const { stdout } = await spawn('yarn', ['--json', 'workspaces', 'info'], { + const { stdout } = await spawn(YARN_EXEC, ['--json', 'workspaces', 'info'], { cwd: directory, stdio: 'pipe', }); diff --git a/packages/kbn-storybook/storybook_config/webpack.config.js b/packages/kbn-storybook/storybook_config/webpack.config.js index 2dd051882bb4b..543bb47656df8 100644 --- a/packages/kbn-storybook/storybook_config/webpack.config.js +++ b/packages/kbn-storybook/storybook_config/webpack.config.js @@ -17,7 +17,7 @@ * under the License. */ -const { resolve } = require('path'); +const { parse, resolve } = require('path'); const webpack = require('webpack'); const { stringifyRequest } = require('loader-utils'); const CopyWebpackPlugin = require('copy-webpack-plugin'); @@ -95,6 +95,27 @@ module.exports = async ({ config }) => { }, }, }, + { + loader: 'resolve-url-loader', + options: { + // If you don't have arguments (_, __) to the join function, the + // resolve-url-loader fails with a loader misconfiguration error. + // + // eslint-disable-next-line no-unused-vars + join: (_, __) => (uri, base) => { + if (!base || !parse(base).dir.includes('legacy')) { + return null; + } + + // URIs on mixins in src/legacy/public/styles need to be resolved. + if (uri.startsWith('ui/assets')) { + return resolve(REPO_ROOT, 'src/core/server/core_app/', uri.replace('ui/', '')); + } + + return null; + }, + }, + }, { loader: 'sass-loader', options: { diff --git a/packages/kbn-ui-shared-deps/package.json b/packages/kbn-ui-shared-deps/package.json index 744a656c54a7f..2c9251b03059a 100644 --- a/packages/kbn-ui-shared-deps/package.json +++ b/packages/kbn-ui-shared-deps/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@elastic/charts": "19.2.0", - "@elastic/eui": "23.3.1", + "@elastic/eui": "24.1.0", "@elastic/numeral": "^2.5.0", "@kbn/i18n": "1.0.0", "@kbn/monaco": "1.0.0", diff --git a/renovate.json5 b/renovate.json5 index 674c4e0df7904..b4f1441a50d60 100644 --- a/renovate.json5 +++ b/renovate.json5 @@ -418,14 +418,6 @@ '@types/history', ], }, - { - groupSlug: 'indent-string', - groupName: 'indent-string related packages', - packageNames: [ - 'indent-string', - '@types/indent-string', - ], - }, { groupSlug: 'inquirer', groupName: 'inquirer related packages', @@ -1067,14 +1059,6 @@ '@types/chokidar', ], }, - { - groupSlug: 'wrap-ansi', - groupName: 'wrap-ansi related packages', - packageNames: [ - 'wrap-ansi', - '@types/wrap-ansi', - ], - }, { groupSlug: 'write-pkg', groupName: 'write-pkg related packages', diff --git a/src/core/public/application/application_service.mock.ts b/src/core/public/application/application_service.mock.ts index 300b09e17d15d..47a8a01d917eb 100644 --- a/src/core/public/application/application_service.mock.ts +++ b/src/core/public/application/application_service.mock.ts @@ -17,6 +17,7 @@ * under the License. */ +import { History } from 'history'; import { BehaviorSubject, Subject } from 'rxjs'; import { capabilitiesServiceMock } from './capabilities/capabilities_service.mock'; @@ -57,6 +58,28 @@ const createStartContractMock = (): jest.Mocked => { }; }; +const createHistoryMock = (): jest.Mocked => { + return { + block: jest.fn(), + createHref: jest.fn(), + go: jest.fn(), + goBack: jest.fn(), + goForward: jest.fn(), + listen: jest.fn(), + push: jest.fn(), + replace: jest.fn(), + action: 'PUSH', + length: 1, + location: { + pathname: '/', + search: '', + hash: '', + key: '', + state: undefined, + }, + }; +}; + const createInternalStartContractMock = (): jest.Mocked => { const currentAppId$ = new Subject(); @@ -69,6 +92,7 @@ const createInternalStartContractMock = (): jest.Mocked currentAppId$.next(appId)), navigateToUrl: jest.fn(), registerMountContext: jest.fn(), + history: createHistoryMock(), }; }; diff --git a/src/core/public/application/application_service.tsx b/src/core/public/application/application_service.tsx index 2224f72e2bd91..850422a61bde7 100644 --- a/src/core/public/application/application_service.tsx +++ b/src/core/public/application/application_service.tsx @@ -301,6 +301,7 @@ export class ApplicationService { distinctUntilChanged(), takeUntil(this.stop$) ), + history: this.history, registerMountContext: this.mountContext.registerContext, getUrlForApp: ( appId, diff --git a/src/core/public/application/index.ts b/src/core/public/application/index.ts index d51a4c0d69d42..74356cbd88b34 100644 --- a/src/core/public/application/index.ts +++ b/src/core/public/application/index.ts @@ -43,5 +43,6 @@ export { PublicAppInfo, PublicLegacyAppInfo, // Internal types + InternalApplicationSetup, InternalApplicationStart, } from './types'; diff --git a/src/core/public/application/types.ts b/src/core/public/application/types.ts index 8006ec846138f..7c83c684ac73d 100644 --- a/src/core/public/application/types.ts +++ b/src/core/public/application/types.ts @@ -18,6 +18,7 @@ */ import { Observable } from 'rxjs'; +import { History } from 'history'; import { Capabilities } from './capabilities'; import { ChromeStart } from '../chrome'; @@ -766,6 +767,12 @@ export interface InternalApplicationStart extends Omit | undefined; } /** @internal */ diff --git a/src/core/public/chrome/ui/header/__snapshots__/collapsible_nav.test.tsx.snap b/src/core/public/chrome/ui/header/__snapshots__/collapsible_nav.test.tsx.snap index f5b17f8d214e9..60963c0acb990 100644 --- a/src/core/public/chrome/ui/header/__snapshots__/collapsible_nav.test.tsx.snap +++ b/src/core/public/chrome/ui/header/__snapshots__/collapsible_nav.test.tsx.snap @@ -1014,7 +1014,7 @@ exports[`CollapsibleNav renders links grouped by category 1`] = ` @@ -1662,7 +1658,7 @@ exports[`CollapsibleNav renders links grouped by category 1`] = ` @@ -3119,38 +3111,43 @@ exports[`CollapsibleNav renders links grouped by category 1`] = ` - - - + + +
- - - + + +
@@ -4717,7 +4715,7 @@ exports[`CollapsibleNav renders the default nav 3`] = ` @@ -5120,38 +5114,43 @@ exports[`CollapsibleNav renders the default nav 3`] = ` - - - + + +
@@ -9220,7 +9273,7 @@ exports[`Header renders 3`] = `
@@ -9707,38 +9756,43 @@ exports[`Header renders 3`] = ` - - - + + +
@@ -14226,6 +14300,7 @@ exports[`Header renders 4`] = ` > diff --git a/src/plugins/vis_type_vega/public/data_model/search_cache.js b/src/core/public/core_app/core_app.mock.ts similarity index 52% rename from src/plugins/vis_type_vega/public/data_model/search_cache.js rename to src/core/public/core_app/core_app.mock.ts index 41e4c67c3b2ad..b0e3871a40bf5 100644 --- a/src/plugins/vis_type_vega/public/data_model/search_cache.js +++ b/src/core/public/core_app/core_app.mock.ts @@ -17,32 +17,15 @@ * under the License. */ -import LruCache from 'lru-cache'; +import { CoreApp } from './core_app'; -export class SearchCache { - constructor(es, cacheOpts) { - this._es = es; - this._cache = new LruCache(cacheOpts); - } +type CoreAppContract = PublicMethodsOf; +const createMock = (): jest.Mocked => ({ + setup: jest.fn(), + start: jest.fn(), + stop: jest.fn(), +}); - /** - * Execute multiple searches, possibly combining the results of the cached searches - * with the new ones already in cache - * @param {object[]} requests array of search requests - */ - search(requests) { - const promises = []; - - for (const request of requests) { - const key = JSON.stringify(request); - let pending = this._cache.get(key); - if (pending === undefined) { - pending = this._es.search(request); - this._cache.set(key, pending); - } - promises.push(pending); - } - - return Promise.all(promises); - } -} +export const coreAppMock = { + create: createMock, +}; diff --git a/src/core/public/core_app/core_app.ts b/src/core/public/core_app/core_app.ts new file mode 100644 index 0000000000000..04d58b7c3c65c --- /dev/null +++ b/src/core/public/core_app/core_app.ts @@ -0,0 +1,83 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { UnregisterCallback } from 'history'; +import { + InternalApplicationSetup, + InternalApplicationStart, + AppNavLinkStatus, + AppMountParameters, +} from '../application'; +import { HttpSetup, HttpStart } from '../http'; +import { CoreContext } from '../core_system'; +import { renderApp, setupUrlOverflowDetection } from './errors'; +import { NotificationsStart } from '../notifications'; +import { IUiSettingsClient } from '../ui_settings'; + +interface SetupDeps { + application: InternalApplicationSetup; + http: HttpSetup; +} + +interface StartDeps { + application: InternalApplicationStart; + http: HttpStart; + notifications: NotificationsStart; + uiSettings: IUiSettingsClient; +} + +export class CoreApp { + private stopHistoryListening?: UnregisterCallback; + + constructor(private readonly coreContext: CoreContext) {} + + public setup({ http, application }: SetupDeps) { + application.register(this.coreContext.coreId, { + id: 'error', + title: 'App Error', + navLinkStatus: AppNavLinkStatus.hidden, + mount(params: AppMountParameters) { + // Do not use an async import here in order to ensure that network failures + // cannot prevent the error UI from displaying. This UI is tiny so an async + // import here is probably not useful anyways. + return renderApp(params, { basePath: http.basePath }); + }, + }); + } + + public start({ application, http, notifications, uiSettings }: StartDeps) { + if (!application.history) { + return; + } + + this.stopHistoryListening = setupUrlOverflowDetection({ + basePath: http.basePath, + history: application.history, + toasts: notifications.toasts, + uiSettings, + }); + } + + public stop() { + if (this.stopHistoryListening) { + this.stopHistoryListening(); + this.stopHistoryListening = undefined; + } + } +} diff --git a/src/core/public/core_app/errors/error_application.test.ts b/src/core/public/core_app/errors/error_application.test.ts new file mode 100644 index 0000000000000..ec3992330008f --- /dev/null +++ b/src/core/public/core_app/errors/error_application.test.ts @@ -0,0 +1,61 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { act } from 'react-dom/test-utils'; +import { History, createMemoryHistory } from 'history'; +import { IBasePath } from '../../http'; +import { BasePath } from '../../http/base_path'; + +import { renderApp } from './error_application'; + +describe('renderApp', () => { + let basePath: IBasePath; + let element: HTMLDivElement; + let history: History; + let unmount: any; + + beforeEach(() => { + basePath = new BasePath(); + element = document.createElement('div'); + history = createMemoryHistory(); + unmount = renderApp({ element, history } as any, { basePath }); + }); + + afterEach(() => unmount()); + + it('renders generic errors', () => { + act(() => { + history.push('/app/error'); + }); + // innerText not working in jsdom, so use innerHTML + expect(element.querySelector('.euiTitle')!.innerHTML).toMatchInlineSnapshot( + `"Application error"` + ); + }); + + it('renders urlOverflow errors', () => { + act(() => { + history.push('/app/error?errorType=urlOverflow'); + }); + expect(element.querySelector('.euiTitle')!.innerHTML).toMatchInlineSnapshot( + `"The URL for this object is too long, and we can't display it"` + ); + expect(element.innerHTML).toMatch('Things to try'); + }); +}); diff --git a/src/core/public/core_app/errors/error_application.tsx b/src/core/public/core_app/errors/error_application.tsx new file mode 100644 index 0000000000000..7124776d7086a --- /dev/null +++ b/src/core/public/core_app/errors/error_application.tsx @@ -0,0 +1,102 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import React, { ReactChild, useState, useLayoutEffect } from 'react'; +import ReactDOM from 'react-dom'; +import { History } from 'history'; +import { i18n } from '@kbn/i18n'; +import { I18nProvider } from '@kbn/i18n/react'; + +import { EuiEmptyPrompt, EuiPage, EuiPageBody, EuiPageContent } from '@elastic/eui'; +import { UrlOverflowUi } from './url_overflow_ui'; +import { IBasePath } from '../../http'; +import { AppMountParameters } from '../../application'; + +interface Props { + title?: string; + children?: ReactChild; +} + +const ErrorPage: React.FC = ({ title, children }) => { + title = + title ?? + i18n.translate('core.application.appRenderError.defaultTitle', { + defaultMessage: 'Application error', + }); + + return ( + + + + {title}} + body={children} + /> + + + + ); +}; + +const ErrorApp: React.FC<{ basePath: IBasePath; history: History }> = ({ basePath, history }) => { + const [currentLocation, setCurrentLocation] = useState(history.location); + useLayoutEffect(() => { + return history.listen((location) => setCurrentLocation(location)); + }, [history]); + + const searchParams = new URLSearchParams(currentLocation.search); + const errorType = searchParams.get('errorType'); + + if (errorType === 'urlOverflow') { + return ( + + + + ); + } + + return ; +}; + +interface Deps { + basePath: IBasePath; +} + +/** + * Renders UI for displaying error messages. + * @internal + */ +export const renderApp = ({ element, history }: AppMountParameters, { basePath }: Deps) => { + ReactDOM.render( + + + , + element + ); + + return () => { + ReactDOM.unmountComponentAtNode(element); + }; +}; diff --git a/src/core/public/core_app/errors/index.ts b/src/core/public/core_app/errors/index.ts new file mode 100644 index 0000000000000..a8da0d98b3962 --- /dev/null +++ b/src/core/public/core_app/errors/index.ts @@ -0,0 +1,21 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export { renderApp } from './error_application'; +export { setupUrlOverflowDetection, URL_MAX_LENGTH } from './url_overflow'; diff --git a/src/core/public/core_app/errors/url_overflow.test.ts b/src/core/public/core_app/errors/url_overflow.test.ts new file mode 100644 index 0000000000000..115bf53aa2a84 --- /dev/null +++ b/src/core/public/core_app/errors/url_overflow.test.ts @@ -0,0 +1,127 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { createMemoryHistory, History } from 'history'; + +import { BasePath } from '../../http/base_path'; +import { notificationServiceMock } from '../../notifications/notifications_service.mock'; +import { uiSettingsServiceMock } from '../../ui_settings/ui_settings_service.mock'; +import { IBasePath } from '../../http'; +import { IToasts } from '../../notifications'; +import { IUiSettingsClient } from '../../ui_settings'; + +import { setupUrlOverflowDetection, URL_MAX_LENGTH, URL_WARNING_LENGTH } from './url_overflow'; + +const longUrl = '/' + 'a'.repeat(URL_MAX_LENGTH); + +describe('url overflow detection', () => { + let basePath: IBasePath; + let history: History; + let toasts: jest.Mocked; + let uiSettings: jest.Mocked; + let assignSpy: jest.SpyInstance; + let unlisten: any; + + beforeEach(() => { + basePath = new BasePath('/test-123'); + history = createMemoryHistory(); + toasts = notificationServiceMock.createStartContract().toasts; + uiSettings = uiSettingsServiceMock.createStartContract(); + + // No-op mock impl to avoid jsdom warning about navigation not being implemented + assignSpy = jest.spyOn(window.location, 'assign').mockImplementation(() => {}); + + unlisten = setupUrlOverflowDetection({ + basePath, + history, + toasts, + uiSettings, + }); + }); + + afterEach(() => { + unlisten(); + assignSpy.mockRestore(); + }); + + it('redirects to error page when URL is too long', () => { + history.push(longUrl); + expect(assignSpy).toHaveBeenCalledWith('/app/error?errorType=urlOverflow'); + }); + + it('displays a toast if URL exceeds warning threshold', () => { + const warningUrl = '/' + 'a'.repeat(URL_WARNING_LENGTH); + history.push(warningUrl); + expect(history.location.pathname).toEqual(warningUrl); + expect(assignSpy).not.toHaveBeenCalled(); + expect(toasts.addWarning).toHaveBeenCalledWith( + expect.objectContaining({ + title: 'The URL is big and Kibana might stop working', + text: expect.any(Function), + }) + ); + + // Verify toast can be rendered correctly + const { text: mountToast } = toasts.addWarning.mock.calls[0][0] as any; + const element = document.createElement('div'); + const unmount = mountToast(element); + expect(element).toMatchInlineSnapshot(` +
+ Either enable the + + state:storeInSessionStorage + + option in + + advanced settings + + or simplify the onscreen visuals. +
+ `); + unmount(); + }); + + it('does not redirect or show warning if URL is not too long', () => { + history.push('/regular-length-url'); + expect(history.location.pathname).toEqual('/regular-length-url'); + expect(assignSpy).not.toHaveBeenCalled(); + expect(toasts.addWarning).not.toHaveBeenCalled(); + }); + + it('does not redirect or show warning if state:storeInSessionStorage is set', () => { + uiSettings.get.mockReturnValue(true); + history.push(longUrl); + expect(history.location.pathname).toEqual(longUrl); + expect(assignSpy).not.toHaveBeenCalled(); + expect(toasts.addWarning).not.toHaveBeenCalled(); + }); + + it('does not redirect or show warning if already on the error page', () => { + history.push('/app/error'); + const longQueryParam = 'a'.repeat(URL_MAX_LENGTH); + const longErrorUrl = `/app/error?q=${longQueryParam}`; + history.push(longErrorUrl); + expect(history.location.pathname).toEqual('/app/error'); + expect(history.location.search).toEqual(`?q=${longQueryParam}`); + expect(assignSpy).not.toHaveBeenCalled(); + expect(toasts.addWarning).not.toHaveBeenCalled(); + }); +}); diff --git a/src/core/public/core_app/errors/url_overflow.tsx b/src/core/public/core_app/errors/url_overflow.tsx new file mode 100644 index 0000000000000..da287a74d09ae --- /dev/null +++ b/src/core/public/core_app/errors/url_overflow.tsx @@ -0,0 +1,96 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import React from 'react'; +import { History, Location } from 'history'; + +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; + +import { mountReactNode } from '../../utils'; +import { IToasts } from '../../notifications'; +import { IBasePath } from '../../http'; +import { IUiSettingsClient } from '../../ui_settings'; + +const IE_REGEX = /(; ?MSIE |Edge\/\d|Trident\/[\d+\.]+;.*rv:*11\.\d+)/; +export const IS_IE = IE_REGEX.test(window.navigator.userAgent); +/** + * The max URL length allowed by the current browser. Should be used to display warnings to users when query parameters + * cause URL to exceed this limit. + * @public + */ +export const URL_MAX_LENGTH = IS_IE ? 2000 : 25000; +export const URL_WARNING_LENGTH = IS_IE ? 1000 : 24000; +const ERROR_ROUTE = '/app/error'; + +interface Deps { + basePath: IBasePath; + history: History; + toasts: IToasts; + uiSettings: IUiSettingsClient; +} + +export const setupUrlOverflowDetection = ({ basePath, history, toasts, uiSettings }: Deps) => + history.listen((location: Location) => { + // Bail if storeInSessionStorage is set or we're already on the error page + if ( + uiSettings.get('state:storeInSessionStorage') || + history.location.pathname.startsWith(ERROR_ROUTE) + ) { + return; + } + + const absUrl = history.createHref(location); + const absUrlLength = absUrl.length; + + if (absUrlLength > URL_MAX_LENGTH) { + const href = history.createHref({ + pathname: ERROR_ROUTE, + search: `errorType=urlOverflow`, + }); + // Force the browser to reload so that any potentially unstable state is unloaded + window.location.assign(href); + // window.location.href = href; + // window.location.reload(); + } else if (absUrlLength >= URL_WARNING_LENGTH) { + toasts.addWarning({ + title: i18n.translate('core.ui.errorUrlOverflow.bigUrlWarningNotificationTitle', { + defaultMessage: 'The URL is big and Kibana might stop working', + }), + text: mountReactNode( + state:storeInSessionStorage, + advancedSettingsLink: ( + + + + ), + }} + /> + ), + }); + } + }); diff --git a/src/core/public/core_app/errors/url_overflow_ui.tsx b/src/core/public/core_app/errors/url_overflow_ui.tsx new file mode 100644 index 0000000000000..30ee0f4ac41e5 --- /dev/null +++ b/src/core/public/core_app/errors/url_overflow_ui.tsx @@ -0,0 +1,73 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import React from 'react'; + +import { FormattedMessage } from '@kbn/i18n/react'; +import { EuiText } from '@elastic/eui'; + +import { IBasePath } from '../../http'; +import { IS_IE } from './url_overflow'; + +export const UrlOverflowUi: React.FC<{ basePath: IBasePath }> = ({ basePath }) => { + return ( + +

+ +

+ +
    +
  • + state:storeInSessionStorage, + kibanaSettingsLink: ( + + + + ), + }} + /> +
  • +
  • + +
  • + {IS_IE && ( +
  • + +
  • + )} +
+
+ ); +}; diff --git a/src/legacy/ui/public/error_url_overflow/index.js b/src/core/public/core_app/index.ts similarity index 87% rename from src/legacy/ui/public/error_url_overflow/index.js rename to src/core/public/core_app/index.ts index 06a98789349f8..9876be1575ffd 100644 --- a/src/legacy/ui/public/error_url_overflow/index.js +++ b/src/core/public/core_app/index.ts @@ -17,5 +17,5 @@ * under the License. */ -import './error_url_overflow'; -export { UrlOverflowService } from '../../../../plugins/kibana_legacy/public'; +export { CoreApp } from './core_app'; +export { URL_MAX_LENGTH } from './errors'; diff --git a/src/core/public/core_system.test.mocks.ts b/src/core/public/core_system.test.mocks.ts index 75ab6cdb628f7..b5b99418b44b4 100644 --- a/src/core/public/core_system.test.mocks.ts +++ b/src/core/public/core_system.test.mocks.ts @@ -32,6 +32,7 @@ import { docLinksServiceMock } from './doc_links/doc_links_service.mock'; import { renderingServiceMock } from './rendering/rendering_service.mock'; import { contextServiceMock } from './context/context_service.mock'; import { integrationsServiceMock } from './integrations/integrations_service.mock'; +import { coreAppMock } from './core_app/core_app.mock'; export const MockLegacyPlatformService = legacyPlatformServiceMock.create(); export const LegacyPlatformServiceConstructor = jest @@ -136,3 +137,9 @@ export const IntegrationsServiceConstructor = jest jest.doMock('./integrations', () => ({ IntegrationsService: IntegrationsServiceConstructor, })); + +export const MockCoreApp = coreAppMock.create(); +export const CoreAppConstructor = jest.fn().mockImplementation(() => MockCoreApp); +jest.doMock('./core_app', () => ({ + CoreApp: CoreAppConstructor, +})); diff --git a/src/core/public/core_system.test.ts b/src/core/public/core_system.test.ts index 2979dd7661e59..4c1993c90a2e1 100644 --- a/src/core/public/core_system.test.ts +++ b/src/core/public/core_system.test.ts @@ -44,6 +44,8 @@ import { MockContextService, IntegrationsServiceConstructor, MockIntegrationsService, + CoreAppConstructor, + MockCoreApp, } from './core_system.test.mocks'; import { CoreSystem } from './core_system'; @@ -88,6 +90,7 @@ describe('constructor', () => { expect(OverlayServiceConstructor).toHaveBeenCalledTimes(1); expect(RenderingServiceConstructor).toHaveBeenCalledTimes(1); expect(IntegrationsServiceConstructor).toHaveBeenCalledTimes(1); + expect(CoreAppConstructor).toHaveBeenCalledTimes(1); }); it('passes injectedMetadata param to InjectedMetadataService', () => { @@ -231,6 +234,11 @@ describe('#setup()', () => { await setupCore(); expect(MockIntegrationsService.setup).toHaveBeenCalledTimes(1); }); + + it('calls coreApp#setup()', async () => { + await setupCore(); + expect(MockCoreApp.setup).toHaveBeenCalledTimes(1); + }); }); describe('#start()', () => { @@ -315,10 +323,15 @@ describe('#start()', () => { }); }); - it('calls start#setup()', async () => { + it('calls integrations#start()', async () => { await startCore(); expect(MockIntegrationsService.start).toHaveBeenCalledTimes(1); }); + + it('calls coreApp#start()', async () => { + await startCore(); + expect(MockCoreApp.start).toHaveBeenCalledTimes(1); + }); }); describe('#stop()', () => { @@ -377,6 +390,14 @@ describe('#stop()', () => { expect(MockIntegrationsService.stop).toHaveBeenCalled(); }); + it('calls coreApp.stop()', () => { + const coreSystem = createCoreSystem(); + + expect(MockCoreApp.stop).not.toHaveBeenCalled(); + coreSystem.stop(); + expect(MockCoreApp.stop).toHaveBeenCalled(); + }); + it('clears the rootDomElement', async () => { const rootDomElement = document.createElement('div'); const coreSystem = createCoreSystem({ diff --git a/src/core/public/core_system.ts b/src/core/public/core_system.ts index 46e1ecb83e9e4..aa52212344f4d 100644 --- a/src/core/public/core_system.ts +++ b/src/core/public/core_system.ts @@ -43,6 +43,7 @@ import { SavedObjectsService } from './saved_objects'; import { ContextService } from './context'; import { IntegrationsService } from './integrations'; import { InternalApplicationSetup, InternalApplicationStart } from './application/types'; +import { CoreApp } from './core_app'; interface Params { rootDomElement: HTMLElement; @@ -99,6 +100,7 @@ export class CoreSystem { private readonly rendering: RenderingService; private readonly context: ContextService; private readonly integrations: IntegrationsService; + private readonly coreApp: CoreApp; private readonly rootDomElement: HTMLElement; private readonly coreContext: CoreContext; @@ -142,6 +144,7 @@ export class CoreSystem { this.context = new ContextService(this.coreContext); this.plugins = new PluginsService(this.coreContext, injectedMetadata.uiPlugins); + this.coreApp = new CoreApp(this.coreContext); this.legacy = new LegacyPlatformService({ requireLegacyFiles, @@ -177,6 +180,7 @@ export class CoreSystem { ]), }); const application = this.application.setup({ context, http, injectedMetadata }); + this.coreApp.setup({ application, http }); const core: InternalCoreSetup = { application, @@ -245,6 +249,8 @@ export class CoreSystem { uiSettings, }); + this.coreApp.start({ application, http, notifications, uiSettings }); + application.registerMountContext(this.coreContext.coreId, 'core', () => ({ application: pick(application, ['capabilities', 'navigateToApp']), chrome, @@ -308,6 +314,7 @@ export class CoreSystem { public stop() { this.legacy.stop(); this.plugins.stop(); + this.coreApp.stop(); this.notifications.stop(); this.http.stop(); this.integrations.stop(); diff --git a/src/core/public/index.ts b/src/core/public/index.ts index bd275ca1d4565..40f614ebc3bea 100644 --- a/src/core/public/index.ts +++ b/src/core/public/index.ts @@ -191,6 +191,8 @@ export { export { MountPoint, UnmountCallback, PublicUiSettingsParams } from './types'; +export { URL_MAX_LENGTH } from './core_app'; + /** * Core services exposed to the `Plugin` setup lifecycle * diff --git a/src/core/public/public.api.md b/src/core/public/public.api.md index 74c41d010ca8d..b44eb48b9ffa9 100644 --- a/src/core/public/public.api.md +++ b/src/core/public/public.api.md @@ -1424,6 +1424,9 @@ export type UiSettingsType = 'undefined' | 'json' | 'markdown' | 'number' | 'sel // @public export type UnmountCallback = () => void; +// @public +export const URL_MAX_LENGTH: number; + // @public export interface URLMeaningfulParts { // (undocumented) diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vega/vega_visualization.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vega/vega_visualization.js index 6d6eb69e66792..485390dc50a79 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vega/vega_visualization.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vega/vega_visualization.js @@ -44,7 +44,7 @@ import vegaMapImage256 from './vega_map_image_256.png'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { VegaParser } from '../../../../../../plugins/vis_type_vega/public/data_model/vega_parser'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { SearchCache } from '../../../../../../plugins/vis_type_vega/public/data_model/search_cache'; +import { SearchAPI } from '../../../../../../plugins/vis_type_vega/public/data_model/search_api'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { createVegaTypeDefinition } from '../../../../../../plugins/vis_type_vega/public/vega_type'; @@ -205,7 +205,14 @@ describe('VegaVisualizations', () => { try { vegaVis = new VegaVisualization(domNode, vis); - const vegaParser = new VegaParser(vegaliteGraph, new SearchCache()); + const vegaParser = new VegaParser( + vegaliteGraph, + new SearchAPI({ + search: npStart.plugins.data.search, + uiSettings: npStart.core.uiSettings, + injectedMetadata: npStart.core.injectedMetadata, + }) + ); await vegaParser.parseAsync(); await vegaVis.render(vegaParser, vis.params, { data: true }); @@ -227,7 +234,14 @@ describe('VegaVisualizations', () => { let vegaVis; try { vegaVis = new VegaVisualization(domNode, vis); - const vegaParser = new VegaParser(vegaGraph, new SearchCache()); + const vegaParser = new VegaParser( + vegaGraph, + new SearchAPI({ + search: npStart.plugins.data.search, + uiSettings: npStart.core.uiSettings, + injectedMetadata: npStart.core.injectedMetadata, + }) + ); await vegaParser.parseAsync(); await vegaVis.render(vegaParser, vis.params, { data: true }); @@ -243,7 +257,14 @@ describe('VegaVisualizations', () => { let vegaVis; try { vegaVis = new VegaVisualization(domNode, vis); - const vegaParser = new VegaParser(vegaTooltipGraph, new SearchCache()); + const vegaParser = new VegaParser( + vegaTooltipGraph, + new SearchAPI({ + search: npStart.plugins.data.search, + uiSettings: npStart.core.uiSettings, + injectedMetadata: npStart.core.injectedMetadata, + }) + ); await vegaParser.parseAsync(); await vegaVis.render(vegaParser, vis.params, { data: true }); @@ -285,7 +306,14 @@ describe('VegaVisualizations', () => { let vegaVis; try { vegaVis = new VegaVisualization(domNode, vis); - const vegaParser = new VegaParser(vegaMapGraph, new SearchCache()); + const vegaParser = new VegaParser( + vegaMapGraph, + new SearchAPI({ + search: npStart.plugins.data.search, + uiSettings: npStart.core.uiSettings, + injectedMetadata: npStart.core.injectedMetadata, + }) + ); await vegaParser.parseAsync(); domNode.style.width = '256px'; @@ -324,7 +352,11 @@ describe('VegaVisualizations', () => { } ] }`, - new SearchCache() + new SearchAPI({ + search: npStart.plugins.data.search, + uiSettings: npStart.core.uiSettings, + injectedMetadata: npStart.core.injectedMetadata, + }) ); await vegaParser.parseAsync(); diff --git a/src/legacy/server/sass/build.test.js b/src/legacy/server/sass/build.test.js index 46a898c30f84e..71c43ac010962 100644 --- a/src/legacy/server/sass/build.test.js +++ b/src/legacy/server/sass/build.test.js @@ -33,6 +33,8 @@ afterEach(async () => { }); it('builds light themed SASS', async () => { + // Increased timeout from 5000ms due to intermittent timeout failures + jest.setTimeout(60000); const targetPath = resolve(TMP, 'style.css'); await new Build({ sourcePath: FIXTURE, diff --git a/src/legacy/ui/public/_index.scss b/src/legacy/ui/public/_index.scss index d258ef190a100..323de2ea7d263 100644 --- a/src/legacy/ui/public/_index.scss +++ b/src/legacy/ui/public/_index.scss @@ -10,4 +10,3 @@ @import './accessibility/index'; @import './directives/index'; -@import './error_url_overflow/index'; diff --git a/src/legacy/ui/public/error_url_overflow/__tests__/ie_regex.js b/src/legacy/ui/public/error_url_overflow/__tests__/ie_regex.js deleted file mode 100644 index 3d770c13a81aa..0000000000000 --- a/src/legacy/ui/public/error_url_overflow/__tests__/ie_regex.js +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import expect from '@kbn/expect'; -import { IE_REGEX } from '../../../../../plugins/kibana_legacy/public'; - -describe('IE_REGEX', () => { - it('should detect IE 9', () => { - const userAgent = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'; - expect(IE_REGEX.test(userAgent)).to.be(true); - }); - - it('should detect IE 10', () => { - const userAgent = - 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)'; - expect(IE_REGEX.test(userAgent)).to.be(true); - }); - - it('should detect IE 11', () => { - const userAgent = - 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; ' + - '.NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; rv:11.0) like Gecko'; - expect(IE_REGEX.test(userAgent)).to.be(true); - }); - - it('should detect Edge', () => { - const userAgent = - 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' + - '(KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/13.10586'; - expect(IE_REGEX.test(userAgent)).to.be(true); - }); - - it('should not detect Chrome on MacOS', () => { - const userAgent = - 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 ' + - '(KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'; - expect(IE_REGEX.test(userAgent)).to.be(false); - }); - - it('should not detect Chrome on Windows', () => { - const userAgent = - 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' + - '(KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'; - expect(IE_REGEX.test(userAgent)).to.be(false); - }); - - it('should not detect Safari on MacOS', () => { - const userAgent = - 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 ' + - '(KHTML, like Gecko) Version/10.1.1 Safari/603.2.4'; - expect(IE_REGEX.test(userAgent)).to.be(false); - }); - - it('should not detect Firefox on MacOS', () => { - const userAgent = - 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:46.0) Gecko/20100101 Firefox/46.0'; - expect(IE_REGEX.test(userAgent)).to.be(false); - }); - - it('should not detect Firefox on Windows', () => { - const userAgent = - 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:46.0) Gecko/20100101 Firefox/46.0'; - expect(IE_REGEX.test(userAgent)).to.be(false); - }); -}); diff --git a/src/legacy/ui/public/error_url_overflow/_error_url_overflow.scss b/src/legacy/ui/public/error_url_overflow/_error_url_overflow.scss deleted file mode 100644 index df96d72521a5a..0000000000000 --- a/src/legacy/ui/public/error_url_overflow/_error_url_overflow.scss +++ /dev/null @@ -1,3 +0,0 @@ -.kbnError--url-overflow-app { - padding: $euiSizeL; -} diff --git a/src/legacy/ui/public/error_url_overflow/_index.scss b/src/legacy/ui/public/error_url_overflow/_index.scss deleted file mode 100644 index 15e2f77798268..0000000000000 --- a/src/legacy/ui/public/error_url_overflow/_index.scss +++ /dev/null @@ -1 +0,0 @@ -@import './error_url_overflow'; diff --git a/src/legacy/ui/public/error_url_overflow/error_url_overflow.html b/src/legacy/ui/public/error_url_overflow/error_url_overflow.html deleted file mode 100644 index 643c39ffed08d..0000000000000 --- a/src/legacy/ui/public/error_url_overflow/error_url_overflow.html +++ /dev/null @@ -1,55 +0,0 @@ -
-

- - - -

- -

- -

-

- -
    -
  1. -
  2. -
  3. -
-
-
-

- -

-
diff --git a/src/legacy/ui/public/error_url_overflow/error_url_overflow.js b/src/legacy/ui/public/error_url_overflow/error_url_overflow.js deleted file mode 100644 index 223b81fa36fde..0000000000000 --- a/src/legacy/ui/public/error_url_overflow/error_url_overflow.js +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import { i18n } from '@kbn/i18n'; -import uiRoutes from '../routes'; -import { KbnUrlProvider } from '../url'; - -import template from './error_url_overflow.html'; -import { UrlOverflowService } from '../../../../plugins/kibana_legacy/public'; - -export { UrlOverflowService }; - -uiRoutes.when('/error/url-overflow', { - template, - k7Breadcrumbs: () => [ - { - text: i18n.translate('common.ui.errorUrlOverflow.breadcrumbs.errorText', { - defaultMessage: 'Error', - }), - }, - ], - controllerAs: 'controller', - controller: class OverflowController { - constructor(Private, $scope) { - const kbnUrl = Private(KbnUrlProvider); - const urlOverflow = new UrlOverflowService(); - - if (!urlOverflow.get()) { - kbnUrl.redirectPath('/'); - return; - } - - this.url = urlOverflow.get(); - this.limit = urlOverflow.failLength(); - this.advancedSettingsLabel = i18n.translate( - 'common.ui.errorUrlOverflow.howTofixError.enableOptionText.advancedSettingsLinkText', - { defaultMessage: 'advanced settings' } - ); - $scope.$on('$destroy', () => urlOverflow.clear()); - } - }, -}); diff --git a/src/plugins/data/public/index.ts b/src/plugins/data/public/index.ts index eb3f937a4168b..301ff8d3f67d8 100644 --- a/src/plugins/data/public/index.ts +++ b/src/plugins/data/public/index.ts @@ -358,6 +358,7 @@ export { ISearchSource, parseSearchSourceJSON, injectSearchSourceReferences, + getSearchParamsFromRequest, extractSearchSourceReferences, SearchSourceFields, EsQuerySortValue, diff --git a/src/plugins/data/public/public.api.md b/src/plugins/data/public/public.api.md index 7054575e8ef9e..bd3ec0d3f2294 100644 --- a/src/plugins/data/public/public.api.md +++ b/src/plugins/data/public/public.api.md @@ -30,6 +30,7 @@ import { IconType } from '@elastic/eui'; import { InjectedIntl } from '@kbn/i18n/react'; import { IStorageWrapper } from 'src/plugins/kibana_utils/public'; import { IUiSettingsClient } from 'src/core/public'; +import { IUiSettingsClient as IUiSettingsClient_3 } from 'kibana/public'; import { Location } from 'history'; import { LocationDescriptorObject } from 'history'; import { MaybePromise } from '@kbn/utility-types'; @@ -641,6 +642,23 @@ export function getQueryLog(uiSettings: IUiSettingsClient, storage: IStorageWrap // @public (undocumented) export function getSearchErrorType({ message }: Pick): "UNSUPPORTED_QUERY" | undefined; +// Warning: (ae-missing-release-tag) "getSearchParamsFromRequest" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export function getSearchParamsFromRequest(searchRequest: SearchRequest, dependencies: { + injectedMetadata: CoreStart['injectedMetadata']; + uiSettings: IUiSettingsClient_3; +}): { + rest_total_hits_as_int: boolean; + ignore_unavailable: boolean; + ignore_throttled: boolean; + max_concurrent_shard_requests: any; + preference: any; + timeout: string | undefined; + index: any; + body: any; +}; + // Warning: (ae-missing-release-tag) "getTime" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -1851,20 +1869,20 @@ export const UI_SETTINGS: { // src/plugins/data/public/index.ts:236:27 - (ae-forgotten-export) The symbol "getFromSavedObject" needs to be exported by the entry point index.d.ts // src/plugins/data/public/index.ts:236:27 - (ae-forgotten-export) The symbol "flattenHitWrapper" needs to be exported by the entry point index.d.ts // src/plugins/data/public/index.ts:236:27 - (ae-forgotten-export) The symbol "formatHitProvider" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:375:20 - (ae-forgotten-export) The symbol "getRequestInspectorStats" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:375:20 - (ae-forgotten-export) The symbol "getResponseInspectorStats" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:375:20 - (ae-forgotten-export) The symbol "tabifyAggResponse" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:375:20 - (ae-forgotten-export) The symbol "tabifyGetColumns" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:377:1 - (ae-forgotten-export) The symbol "CidrMask" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:378:1 - (ae-forgotten-export) The symbol "dateHistogramInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:387:1 - (ae-forgotten-export) The symbol "InvalidEsCalendarIntervalError" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:388:1 - (ae-forgotten-export) The symbol "InvalidEsIntervalFormatError" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:389:1 - (ae-forgotten-export) The symbol "isDateHistogramBucketAggConfig" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:393:1 - (ae-forgotten-export) The symbol "isValidEsInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:394:1 - (ae-forgotten-export) The symbol "isValidInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:397:1 - (ae-forgotten-export) The symbol "parseInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:398:1 - (ae-forgotten-export) The symbol "propFilter" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:401:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:376:20 - (ae-forgotten-export) The symbol "getRequestInspectorStats" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:376:20 - (ae-forgotten-export) The symbol "getResponseInspectorStats" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:376:20 - (ae-forgotten-export) The symbol "tabifyAggResponse" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:376:20 - (ae-forgotten-export) The symbol "tabifyGetColumns" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:378:1 - (ae-forgotten-export) The symbol "CidrMask" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:379:1 - (ae-forgotten-export) The symbol "dateHistogramInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:388:1 - (ae-forgotten-export) The symbol "InvalidEsCalendarIntervalError" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:389:1 - (ae-forgotten-export) The symbol "InvalidEsIntervalFormatError" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:390:1 - (ae-forgotten-export) The symbol "isDateHistogramBucketAggConfig" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:394:1 - (ae-forgotten-export) The symbol "isValidEsInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:395:1 - (ae-forgotten-export) The symbol "isValidInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:398:1 - (ae-forgotten-export) The symbol "parseInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:399:1 - (ae-forgotten-export) The symbol "propFilter" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:402:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts // src/plugins/data/public/query/state_sync/connect_to_query_state.ts:33:33 - (ae-forgotten-export) The symbol "FilterStateStore" needs to be exported by the entry point index.d.ts // src/plugins/data/public/query/state_sync/connect_to_query_state.ts:37:1 - (ae-forgotten-export) The symbol "QueryStateChange" needs to be exported by the entry point index.d.ts // src/plugins/data/public/types.ts:52:5 - (ae-forgotten-export) The symbol "createFiltersFromValueClickAction" needs to be exported by the entry point index.d.ts diff --git a/src/plugins/data/public/search/fetch/get_search_params.ts b/src/plugins/data/public/search/fetch/get_search_params.ts index 60bdc9ed6473a..f2ad243ce72d0 100644 --- a/src/plugins/data/public/search/fetch/get_search_params.ts +++ b/src/plugins/data/public/search/fetch/get_search_params.ts @@ -17,8 +17,9 @@ * under the License. */ -import { IUiSettingsClient } from 'kibana/public'; +import { IUiSettingsClient, CoreStart } from 'kibana/public'; import { UI_SETTINGS } from '../../../common'; +import { SearchRequest } from './types'; const sessionId = Date.now(); @@ -53,3 +54,18 @@ export function getPreference(config: IUiSettingsClient) { export function getTimeout(esShardTimeout: number) { return esShardTimeout > 0 ? `${esShardTimeout}ms` : undefined; } + +export function getSearchParamsFromRequest( + searchRequest: SearchRequest, + dependencies: { injectedMetadata: CoreStart['injectedMetadata']; uiSettings: IUiSettingsClient } +) { + const { injectedMetadata, uiSettings } = dependencies; + const esShardTimeout = injectedMetadata.getInjectedVar('esShardTimeout') as number; + const searchParams = getSearchParams(uiSettings, esShardTimeout); + + return { + index: searchRequest.index.title || searchRequest.index, + body: searchRequest.body, + ...searchParams, + }; +} diff --git a/src/plugins/data/public/search/fetch/index.ts b/src/plugins/data/public/search/fetch/index.ts index 39845ec31bfaa..ab856d681ba12 100644 --- a/src/plugins/data/public/search/fetch/index.ts +++ b/src/plugins/data/public/search/fetch/index.ts @@ -20,6 +20,7 @@ export * from './types'; export { getSearchParams, + getSearchParamsFromRequest, getPreference, getTimeout, getIgnoreThrottled, diff --git a/src/plugins/data/public/search/index.ts b/src/plugins/data/public/search/index.ts index 53686f9be9b4d..1b5395e1071c5 100644 --- a/src/plugins/data/public/search/index.ts +++ b/src/plugins/data/public/search/index.ts @@ -44,6 +44,7 @@ export { SearchRequest, SearchResponse, getSearchErrorType, + getSearchParamsFromRequest, } from './fetch'; export { diff --git a/src/plugins/data/public/search/search_source/search_source.ts b/src/plugins/data/public/search/search_source/search_source.ts index b926739112e0e..a33cda964bd1d 100644 --- a/src/plugins/data/public/search/search_source/search_source.ts +++ b/src/plugins/data/public/search/search_source/search_source.ts @@ -77,7 +77,7 @@ import { filterDocvalueFields } from './filter_docvalue_fields'; import { fieldWildcardFilter } from '../../../../kibana_utils/public'; import { IIndexPattern, ISearchGeneric, SearchRequest } from '../..'; import { SearchSourceOptions, SearchSourceFields } from './types'; -import { FetchOptions, RequestFailure, getSearchParams, handleResponse } from '../fetch'; +import { FetchOptions, RequestFailure, handleResponse, getSearchParamsFromRequest } from '../fetch'; import { getEsQueryConfig, buildEsQuery, Filter, UI_SETTINGS } from '../../../common'; import { getHighlightRequest } from '../../../common/field_formats'; @@ -204,13 +204,12 @@ export class SearchSource { */ private fetch$(searchRequest: SearchRequest, signal?: AbortSignal) { const { search, injectedMetadata, uiSettings } = this.dependencies; - const esShardTimeout = injectedMetadata.getInjectedVar('esShardTimeout') as number; - const searchParams = getSearchParams(uiSettings, esShardTimeout); - const params = { - index: searchRequest.index.title || searchRequest.index, - body: searchRequest.body, - ...searchParams, - }; + + const params = getSearchParamsFromRequest(searchRequest, { + injectedMetadata, + uiSettings, + }); + return search({ params, indexType: searchRequest.indexType }, { signal }).pipe( map(({ rawResponse }) => handleResponse(searchRequest, rawResponse)) ); diff --git a/src/plugins/home/server/services/sample_data/data_sets/ecommerce/ecommerce.json.gz b/src/plugins/home/server/services/sample_data/data_sets/ecommerce/ecommerce.json.gz index b1a5dff7b2b5f..d47426df12ddf 100644 Binary files a/src/plugins/home/server/services/sample_data/data_sets/ecommerce/ecommerce.json.gz and b/src/plugins/home/server/services/sample_data/data_sets/ecommerce/ecommerce.json.gz differ diff --git a/src/plugins/home/server/services/sample_data/data_sets/ecommerce/field_mappings.ts b/src/plugins/home/server/services/sample_data/data_sets/ecommerce/field_mappings.ts index 5fecf8699bec8..c29df2c88fd74 100644 --- a/src/plugins/home/server/services/sample_data/data_sets/ecommerce/field_mappings.ts +++ b/src/plugins/home/server/services/sample_data/data_sets/ecommerce/field_mappings.ts @@ -173,4 +173,11 @@ export const fieldMappings = { city_name: { type: 'keyword' }, }, }, + event: { + properties: { + dataset: { + type: 'keyword', + }, + }, + }, }; diff --git a/src/plugins/home/server/services/sample_data/data_sets/ecommerce/saved_objects.ts b/src/plugins/home/server/services/sample_data/data_sets/ecommerce/saved_objects.ts index b2392742c0197..f680329045625 100644 --- a/src/plugins/home/server/services/sample_data/data_sets/ecommerce/saved_objects.ts +++ b/src/plugins/home/server/services/sample_data/data_sets/ecommerce/saved_objects.ts @@ -296,7 +296,7 @@ export const getSavedObjects = (): SavedObject[] => [ title: 'kibana_sample_data_ecommerce', timeFieldName: 'order_date', fields: - '[{"name":"_id","type":"string","esTypes":["_id"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":false},{"name":"_index","type":"string","esTypes":["_index"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":false},{"name":"_score","type":"number","count":0,"scripted":false,"searchable":false,"aggregatable":false,"readFromDocValues":false},{"name":"_source","type":"_source","esTypes":["_source"],"count":0,"scripted":false,"searchable":false,"aggregatable":false,"readFromDocValues":false},{"name":"_type","type":"string","esTypes":["_type"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":false},{"name":"category","type":"string","esTypes":["text"],"count":0,"scripted":false,"searchable":true,"aggregatable":false,"readFromDocValues":false},{"name":"category.keyword","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true,"subType":{"multi":{"parent": "category"}}},{"name":"currency","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"customer_birth_date","type":"date","esTypes":["date"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"customer_first_name","type":"string","esTypes":["text"],"count":0,"scripted":false,"searchable":true,"aggregatable":false,"readFromDocValues":false},{"name":"customer_first_name.keyword","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true,"subType":{"multi":{"parent": "customer_first_name"}}},{"name":"customer_full_name","type":"string","esTypes":["text"],"count":0,"scripted":false,"searchable":true,"aggregatable":false,"readFromDocValues":false},{"name":"customer_full_name.keyword","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true,"subType":{"multi":{"parent": "customer_full_name"}}},{"name":"customer_gender","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"customer_id","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"customer_last_name","type":"string","esTypes":["text"],"count":0,"scripted":false,"searchable":true,"aggregatable":false,"readFromDocValues":false},{"name":"customer_last_name.keyword","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true,"subType":{"multi":{"parent": "customer_last_name"}}},{"name":"customer_phone","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"day_of_week","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"day_of_week_i","type":"number","esTypes":["integer"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"email","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"geoip.city_name","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"geoip.continent_name","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"geoip.country_iso_code","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"geoip.location","type":"geo_point","esTypes":["geo_point"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"geoip.region_name","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"manufacturer","type":"string","esTypes":["text"],"count":0,"scripted":false,"searchable":true,"aggregatable":false,"readFromDocValues":false},{"name":"manufacturer.keyword","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true,"subType":{"multi":{"parent": "manufacturer"}}},{"name":"order_date","type":"date","esTypes":["date"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"order_id","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products._id","type":"string","esTypes":["text"],"count":0,"scripted":false,"searchable":true,"aggregatable":false,"readFromDocValues":false},{"name":"products._id.keyword","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true,"subType":{"multi":{"parent": "products._id"}}},{"name":"products.base_price","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.base_unit_price","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.category","type":"string","esTypes":["text"],"count":0,"scripted":false,"searchable":true,"aggregatable":false,"readFromDocValues":false},{"name":"products.category.keyword","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true,"subType":{"multi":{"parent": "products.category"}}},{"name":"products.created_on","type":"date","esTypes":["date"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.discount_amount","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.discount_percentage","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.manufacturer","type":"string","esTypes":["text"],"count":0,"scripted":false,"searchable":true,"aggregatable":false,"readFromDocValues":false},{"name":"products.manufacturer.keyword","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true,"subType":{"multi":{"parent": "products.manufacturer"}}},{"name":"products.min_price","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.price","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.product_id","type":"number","esTypes":["long"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.product_name","type":"string","esTypes":["text"],"count":0,"scripted":false,"searchable":true,"aggregatable":false,"readFromDocValues":false},{"name":"products.product_name.keyword","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true,"subType":{"multi":{"parent": "products.product_name"}}},{"name":"products.quantity","type":"number","esTypes":["integer"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.sku","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.tax_amount","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.taxful_price","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.taxless_price","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.unit_discount_amount","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"sku","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"taxful_total_price","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"taxless_total_price","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"total_quantity","type":"number","esTypes":["integer"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"total_unique_products","type":"number","esTypes":["integer"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"type","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"user","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true}]', + '[{"name":"_id","type":"string","esTypes":["_id"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":false},{"name":"_index","type":"string","esTypes":["_index"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":false},{"name":"_score","type":"number","count":0,"scripted":false,"searchable":false,"aggregatable":false,"readFromDocValues":false},{"name":"_source","type":"_source","esTypes":["_source"],"count":0,"scripted":false,"searchable":false,"aggregatable":false,"readFromDocValues":false},{"name":"_type","type":"string","esTypes":["_type"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":false},{"name":"category","type":"string","esTypes":["text"],"count":0,"scripted":false,"searchable":true,"aggregatable":false,"readFromDocValues":false},{"name":"category.keyword","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true,"subType":{"multi":{"parent":"category"}}},{"name":"currency","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"customer_birth_date","type":"date","esTypes":["date"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"customer_first_name","type":"string","esTypes":["text"],"count":0,"scripted":false,"searchable":true,"aggregatable":false,"readFromDocValues":false},{"name":"customer_first_name.keyword","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true,"subType":{"multi":{"parent":"customer_first_name"}}},{"name":"customer_full_name","type":"string","esTypes":["text"],"count":0,"scripted":false,"searchable":true,"aggregatable":false,"readFromDocValues":false},{"name":"customer_full_name.keyword","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true,"subType":{"multi":{"parent":"customer_full_name"}}},{"name":"customer_gender","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"customer_id","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"customer_last_name","type":"string","esTypes":["text"],"count":0,"scripted":false,"searchable":true,"aggregatable":false,"readFromDocValues":false},{"name":"customer_last_name.keyword","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true,"subType":{"multi":{"parent":"customer_last_name"}}},{"name":"customer_phone","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"day_of_week","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"day_of_week_i","type":"number","esTypes":["integer"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"email","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"event.dataset","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"geoip.city_name","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"geoip.continent_name","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"geoip.country_iso_code","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"geoip.location","type":"geo_point","esTypes":["geo_point"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"geoip.region_name","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"manufacturer","type":"string","esTypes":["text"],"count":0,"scripted":false,"searchable":true,"aggregatable":false,"readFromDocValues":false},{"name":"manufacturer.keyword","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true,"subType":{"multi":{"parent":"manufacturer"}}},{"name":"order_date","type":"date","esTypes":["date"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"order_id","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products._id","type":"string","esTypes":["text"],"count":0,"scripted":false,"searchable":true,"aggregatable":false,"readFromDocValues":false},{"name":"products._id.keyword","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true,"subType":{"multi":{"parent":"products._id"}}},{"name":"products.base_price","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.base_unit_price","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.category","type":"string","esTypes":["text"],"count":0,"scripted":false,"searchable":true,"aggregatable":false,"readFromDocValues":false},{"name":"products.category.keyword","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true,"subType":{"multi":{"parent":"products.category"}}},{"name":"products.created_on","type":"date","esTypes":["date"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.discount_amount","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.discount_percentage","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.manufacturer","type":"string","esTypes":["text"],"count":0,"scripted":false,"searchable":true,"aggregatable":false,"readFromDocValues":false},{"name":"products.manufacturer.keyword","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true,"subType":{"multi":{"parent":"products.manufacturer"}}},{"name":"products.min_price","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.price","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.product_id","type":"number","esTypes":["long"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.product_name","type":"string","esTypes":["text"],"count":0,"scripted":false,"searchable":true,"aggregatable":false,"readFromDocValues":false},{"name":"products.product_name.keyword","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true,"subType":{"multi":{"parent":"products.product_name"}}},{"name":"products.quantity","type":"number","esTypes":["integer"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.sku","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.tax_amount","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.taxful_price","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.taxless_price","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"products.unit_discount_amount","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"sku","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"taxful_total_price","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"taxless_total_price","type":"number","esTypes":["half_float"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"total_quantity","type":"number","esTypes":["integer"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"total_unique_products","type":"number","esTypes":["integer"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"type","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true},{"name":"user","type":"string","esTypes":["keyword"],"count":0,"scripted":false,"searchable":true,"aggregatable":true,"readFromDocValues":true}]', fieldFormatMap: '{"taxful_total_price":{"id":"number","params":{"pattern":"$0,0.[00]"}}}', }, references: [], diff --git a/src/plugins/kibana_legacy/public/angular/angular_config.tsx b/src/plugins/kibana_legacy/public/angular/angular_config.tsx index fcfe2bc7f86a2..25cbb0631a652 100644 --- a/src/plugins/kibana_legacy/public/angular/angular_config.tsx +++ b/src/plugins/kibana_legacy/public/angular/angular_config.tsx @@ -18,32 +18,23 @@ */ import { - auto, ICompileProvider, IHttpProvider, IHttpService, ILocationProvider, - ILocationService, IModule, IRootScopeService, } from 'angular'; import $ from 'jquery'; import { cloneDeep, forOwn, get, set } from 'lodash'; -import React, { Fragment } from 'react'; import * as Rx from 'rxjs'; import { ChromeBreadcrumb, EnvironmentMode, PackageInfo } from 'kibana/public'; import { History } from 'history'; -import { i18n } from '@kbn/i18n'; -import { FormattedMessage } from '@kbn/i18n/react'; import { CoreStart, LegacyCoreStart } from 'kibana/public'; -import { modifyUrl } from '../../../../core/public'; -import { toMountPoint } from '../../../kibana_react/public'; -import { isSystemApiRequest, UrlOverflowService } from '../utils'; +import { isSystemApiRequest } from '../utils'; import { formatAngularHttpError, isAngularHttpError } from '../notify/lib'; -const URL_LIMIT_WARN_WITHIN = 1000; - export interface RouteConfiguration { controller?: string | ((...args: any[]) => void); redirectTo?: string; @@ -127,7 +118,6 @@ export const configureAppAngularModule = ( .run($setupBreadcrumbsAutoClear(core, isLocalAngular)) .run($setupBadgeAutoClear(core, isLocalAngular)) .run($setupHelpExtensionAutoClear(core, isLocalAngular)) - .run($setupUrlOverflowHandling(core, isLocalAngular)) .run($setupUICapabilityRedirect(core)); }; @@ -390,68 +380,3 @@ const $setupHelpExtensionAutoClear = (newPlatform: CoreStart, isLocalAngular: bo newPlatform.chrome.setHelpExtension(current.helpExtension); }); }; - -const $setupUrlOverflowHandling = (newPlatform: CoreStart, isLocalAngular: boolean) => ( - $location: ILocationService, - $rootScope: IRootScopeService, - $injector: auto.IInjectorService -) => { - const $route = $injector.has('$route') ? $injector.get('$route') : {}; - const urlOverflow = new UrlOverflowService(); - const check = () => { - if (isDummyRoute($route, isLocalAngular)) { - return; - } - // disable long url checks when storing state in session storage - if (newPlatform.uiSettings.get('state:storeInSessionStorage')) { - return; - } - - if ($location.path() === '/error/url-overflow') { - return; - } - - try { - if (urlOverflow.check($location.absUrl()) <= URL_LIMIT_WARN_WITHIN) { - newPlatform.notifications.toasts.addWarning({ - title: i18n.translate('kibana_legacy.bigUrlWarningNotificationTitle', { - defaultMessage: 'The URL is big and Kibana might stop working', - }), - text: toMountPoint( - - state:storeInSessionStorage, - advancedSettingsLink: ( - - - - ), - }} - /> - - ), - }); - } - } catch (e) { - window.location.href = modifyUrl(window.location.href, (parts: any) => { - parts.hash = '#/error/url-overflow'; - }); - // force the browser to reload to that Kibana's potentially unstable state is unloaded - window.location.reload(); - } - }; - - $rootScope.$on('$routeUpdate', check); - $rootScope.$on('$routeChangeStart', check); -}; diff --git a/src/plugins/kibana_legacy/public/utils/index.ts b/src/plugins/kibana_legacy/public/utils/index.ts index 886ae0e877c38..339079d3ac352 100644 --- a/src/plugins/kibana_legacy/public/utils/index.ts +++ b/src/plugins/kibana_legacy/public/utils/index.ts @@ -19,7 +19,6 @@ export * from './migrate_legacy_query'; export * from './system_api'; -export * from './url_overflow_service'; // @ts-ignore export { KbnAccessibleClickProvider } from './kbn_accessible_click'; // @ts-ignore diff --git a/src/plugins/kibana_legacy/public/utils/url_overflow_service.ts b/src/plugins/kibana_legacy/public/utils/url_overflow_service.ts deleted file mode 100644 index e0c0f93bf36cd..0000000000000 --- a/src/plugins/kibana_legacy/public/utils/url_overflow_service.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -const URL_MAX_IE = 2000; -const URL_MAX_OTHERS = 25000; -export const IE_REGEX = /(; ?MSIE |Edge\/\d|Trident\/[\d+\.]+;.*rv:*11\.\d+)/; - -export class UrlOverflowService { - private readonly _ieLike: boolean; - private _val?: string | null; - private readonly _sync: () => void; - constructor() { - const key = 'error/url-overflow/url'; - const store = window.sessionStorage || { - getItem() {}, - setItem() {}, - removeItem() {}, - }; - - // FIXME: Couldn't find a way to test for browser compatibility without - // complex redirect and cookie based "feature-detection" page, so going - // with user-agent detection for now. - this._ieLike = IE_REGEX.test(window.navigator.userAgent); - - this._val = store.getItem(key); - this._sync = () => { - if (typeof this._val === 'string') { - store.setItem(key, this._val); - } else { - store.removeItem(key); - } - }; - } - - failLength() { - return this._ieLike ? URL_MAX_IE : URL_MAX_OTHERS; - } - - set(v: string) { - this._val = v; - this._sync(); - } - - get() { - return this._val; - } - - check(absUrl: string) { - if (!this.get()) { - const urlLength = absUrl.length; - const remaining = this.failLength() - urlLength; - - if (remaining > 0) { - return remaining; - } - - this.set(absUrl); - } - - throw new Error(` - The URL has gotten too big and kibana can no longer - continue. Please refresh to return to your previous state. - `); - } - - clear() { - this._val = undefined; - this._sync(); - } -} diff --git a/src/plugins/telemetry/server/config.ts b/src/plugins/telemetry/server/config.ts index 99dde0c3b3d96..ae9b70bb9f367 100644 --- a/src/plugins/telemetry/server/config.ts +++ b/src/plugins/telemetry/server/config.ts @@ -56,7 +56,7 @@ export const configSchema = schema.object({ }) ), sendUsageFrom: schema.oneOf([schema.literal('server'), schema.literal('browser')], { - defaultValue: 'browser', + defaultValue: 'server', }), }); diff --git a/src/plugins/vis_type_timeseries/public/application/components/panel_config/timeseries.js b/src/plugins/vis_type_timeseries/public/application/components/panel_config/timeseries.js index 0b8b4be67b7a0..3e5e335a9ea39 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/panel_config/timeseries.js +++ b/src/plugins/vis_type_timeseries/public/application/components/panel_config/timeseries.js @@ -61,6 +61,7 @@ class TimeseriesPanelConfigUi extends Component { axis_min: '', legend_position: 'right', show_grid: 1, + tooltip_mode: 'show_all', }; const model = { ...defaults, ...this.props.model }; const { selectedTab } = this.state; @@ -85,6 +86,22 @@ class TimeseriesPanelConfigUi extends Component { value: 'left', }, ]; + const tooltipModeOptions = [ + { + label: intl.formatMessage({ + id: 'visTypeTimeseries.timeseries.tooltipOptions.showAll', + defaultMessage: 'Show all values', + }), + value: 'show_all', + }, + { + label: intl.formatMessage({ + id: 'visTypeTimeseries.timeseries.tooltipOptions.showFocused', + defaultMessage: 'Show focused values', + }), + value: 'show_focused', + }, + ]; const selectedPositionOption = positionOptions.find((option) => { return model.axis_position === option.value; }); @@ -134,6 +151,10 @@ class TimeseriesPanelConfigUi extends Component { return model.legend_position === option.value; }); + const selectedTooltipMode = tooltipModeOptions.find((option) => { + return model.tooltip_mode === option.value; + }); + let view; if (selectedTab === 'data') { view = ( @@ -356,6 +377,24 @@ class TimeseriesPanelConfigUi extends Component { + + + + + + + +
diff --git a/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/vis.js b/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/vis.js index b4c563f3c11fd..ddfaf3c1428d9 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/vis.js +++ b/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/vis.js @@ -250,6 +250,7 @@ export class TimeseriesVisualization extends Component { showGrid={Boolean(model.show_grid)} legend={Boolean(model.show_legend)} legendPosition={model.legend_position} + tooltipMode={model.tooltip_mode} xAxisLabel={getAxisLabelString(interval)} xAxisFormatter={this.xAxisFormatter(interval)} annotations={this.prepareAnnotations()} diff --git a/src/plugins/vis_type_timeseries/public/application/visualizations/views/timeseries/index.js b/src/plugins/vis_type_timeseries/public/application/visualizations/views/timeseries/index.js index 274b46bce2715..c53482b5db075 100644 --- a/src/plugins/vis_type_timeseries/public/application/visualizations/views/timeseries/index.js +++ b/src/plugins/vis_type_timeseries/public/application/visualizations/views/timeseries/index.js @@ -61,6 +61,7 @@ export const TimeSeries = ({ showGrid, legend, legendPosition, + tooltipMode, xAxisLabel, series, yAxis, @@ -131,7 +132,7 @@ export const TimeSeries = ({ baseTheme={theme} tooltip={{ snap: true, - type: TooltipType.VerticalCursor, + type: tooltipMode === 'show_focused' ? TooltipType.Follow : TooltipType.VerticalCursor, headerFormatter: tooltipFormatter, }} /> diff --git a/src/plugins/vis_type_timeseries/public/metrics_type.ts b/src/plugins/vis_type_timeseries/public/metrics_type.ts index 2b0734ceb4d4d..c06f94efb3c49 100644 --- a/src/plugins/vis_type_timeseries/public/metrics_type.ts +++ b/src/plugins/vis_type_timeseries/public/metrics_type.ts @@ -69,6 +69,7 @@ export const metricsVisDefinition = { axis_scale: 'normal', show_legend: 1, show_grid: 1, + tooltip_mode: 'show_all', }, component: VisEditor, }, diff --git a/src/plugins/vis_type_timeseries/server/routes/post_vis_schema.ts b/src/plugins/vis_type_timeseries/server/routes/post_vis_schema.ts index e8838f57ae365..bf2ea8651c5a2 100644 --- a/src/plugins/vis_type_timeseries/server/routes/post_vis_schema.ts +++ b/src/plugins/vis_type_timeseries/server/routes/post_vis_schema.ts @@ -247,6 +247,9 @@ export const visPayloadSchema = schema.object({ series: schema.arrayOf(seriesItems), show_grid: numberIntegerRequired, show_legend: numberIntegerRequired, + tooltip_mode: schema.maybe( + schema.oneOf([schema.literal('show_all'), schema.literal('show_focused')]) + ), time_field: stringOptionalNullable, time_range_mode: stringOptionalNullable, type: stringRequired, diff --git a/src/plugins/vis_type_vega/public/__mocks__/services.ts b/src/plugins/vis_type_vega/public/__mocks__/services.ts index 1bf051232e4c9..4775241a66d50 100644 --- a/src/plugins/vis_type_vega/public/__mocks__/services.ts +++ b/src/plugins/vis_type_vega/public/__mocks__/services.ts @@ -16,10 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +import { CoreStart, IUiSettingsClient, NotificationsStart, SavedObjectsStart } from 'kibana/public'; import { createGetterSetter } from '../../../kibana_utils/public'; import { DataPublicPluginStart } from '../../../data/public'; -import { IUiSettingsClient, NotificationsStart, SavedObjectsStart } from 'kibana/public'; import { dataPluginMock } from '../../../data/public/mocks'; import { coreMock } from '../../../../core/public/mocks'; @@ -34,22 +34,24 @@ setNotifications(coreMock.createStart().notifications); export const [getUISettings, setUISettings] = createGetterSetter('UISettings'); setUISettings(coreMock.createStart().uiSettings); +export const [getInjectedMetadata, setInjectedMetadata] = createGetterSetter< + CoreStart['injectedMetadata'] +>('InjectedMetadata'); +setInjectedMetadata(coreMock.createStart().injectedMetadata); + export const [getSavedObjects, setSavedObjects] = createGetterSetter( 'SavedObjects' ); setSavedObjects(coreMock.createStart().savedObjects); export const [getInjectedVars, setInjectedVars] = createGetterSetter<{ - esShardTimeout: number; enableExternalUrls: boolean; emsTileLayerId: unknown; }>('InjectedVars'); setInjectedVars({ emsTileLayerId: {}, enableExternalUrls: true, - esShardTimeout: 10000, }); -export const getEsShardTimeout = () => getInjectedVars().esShardTimeout; export const getEnableExternalUrls = () => getInjectedVars().enableExternalUrls; export const getEmsTileLayerId = () => getInjectedVars().emsTileLayerId; diff --git a/src/plugins/vis_type_vega/public/data_model/es_query_parser.js b/src/plugins/vis_type_vega/public/data_model/es_query_parser.js index 066c9f06fc109..387301c2c7de9 100644 --- a/src/plugins/vis_type_vega/public/data_model/es_query_parser.js +++ b/src/plugins/vis_type_vega/public/data_model/es_query_parser.js @@ -17,11 +17,9 @@ * under the License. */ -import _ from 'lodash'; import moment from 'moment'; import { i18n } from '@kbn/i18n'; - -import { getEsShardTimeout } from '../services'; +import { isPlainObject, cloneDeep } from 'lodash'; const TIMEFILTER = '%timefilter%'; const AUTOINTERVAL = '%autointerval%'; @@ -37,12 +35,11 @@ const TIMEFIELD = '%timefield%'; * This class parses ES requests specified in the data.url objects. */ export class EsQueryParser { - constructor(timeCache, searchCache, filters, onWarning) { + constructor(timeCache, searchAPI, filters, onWarning) { this._timeCache = timeCache; - this._searchCache = searchCache; + this._searchAPI = searchAPI; this._filters = filters; this._onWarning = onWarning; - this._esShardTimeout = getEsShardTimeout(); } // noinspection JSMethodCanBeStatic @@ -59,7 +56,7 @@ export class EsQueryParser { if (body === undefined) { url.body = body = {}; - } else if (!_.isPlainObject(body)) { + } else if (!isPlainObject(body)) { throw new Error( i18n.translate('visTypeVega.esQueryParser.urlBodyValueTypeErrorMessage', { defaultMessage: '{configName} must be an object', @@ -167,7 +164,7 @@ export class EsQueryParser { if (context) { // Use dashboard context - const newQuery = _.cloneDeep(this._filters); + const newQuery = cloneDeep(this._filters); if (timefield) { newQuery.bool.must.push(body.query); } @@ -179,34 +176,20 @@ export class EsQueryParser { return { dataObject, url }; } - mapRequest = (request) => { - const esRequest = request.url; - if (this._esShardTimeout) { - // remove possible timeout query param to prevent two conflicting timeout parameters - const { body = {}, timeout, ...rest } = esRequest; //eslint-disable-line no-unused-vars - body.timeout = `${this._esShardTimeout}ms`; - return { - body, - ...rest, - }; - } else { - return esRequest; - } - }; - /** * Process items generated by parseUrl() * @param {object[]} requests each object is generated by parseUrl() * @returns {Promise} */ async populateData(requests) { - const esSearches = requests.map(this.mapRequest); + const esSearches = requests.map((r) => r.url); + const data$ = this._searchAPI.search(esSearches); - const results = await this._searchCache.search(esSearches); + const results = await data$.toPromise(); - for (let i = 0; i < requests.length; i++) { - requests[i].dataObject.values = results[i]; - } + results.forEach((data) => { + requests[data.id].dataObject.values = data.rawResponse; + }); } /** @@ -222,7 +205,7 @@ export class EsQueryParser { const item = obj[pos]; if (isQuery && (item === MUST_CLAUSE || item === MUST_NOT_CLAUSE)) { const ctxTag = item === MUST_CLAUSE ? 'must' : 'must_not'; - const ctx = _.cloneDeep(this._filters); + const ctx = cloneDeep(this._filters); if (ctx && ctx.bool && ctx.bool[ctxTag]) { if (Array.isArray(ctx.bool[ctxTag])) { // replace one value with an array of values diff --git a/src/plugins/vis_type_vega/public/data_model/es_query_parser.test.js b/src/plugins/vis_type_vega/public/data_model/es_query_parser.test.js index c519da33ab1c9..fd474bef73b8c 100644 --- a/src/plugins/vis_type_vega/public/data_model/es_query_parser.test.js +++ b/src/plugins/vis_type_vega/public/data_model/es_query_parser.test.js @@ -94,28 +94,36 @@ describe(`EsQueryParser time`, () => { }); describe('EsQueryParser.populateData', () => { - let searchStub; + let searchApiStub; + let data; let parser; beforeEach(() => { - searchStub = jest.fn(() => Promise.resolve([{}, {}])); - parser = new EsQueryParser({}, { search: searchStub }, undefined, undefined); + searchApiStub = { + search: jest.fn(() => ({ + toPromise: jest.fn(() => Promise.resolve(data)), + })), + }; + parser = new EsQueryParser({}, searchApiStub, undefined, undefined); }); test('should set the timeout for each request', async () => { + data = [ + { id: 0, rawResponse: {} }, + { id: 1, rawResponse: {} }, + ]; await parser.populateData([ { url: { body: {} }, dataObject: {} }, { url: { body: {} }, dataObject: {} }, ]); - expect(searchStub.mock.calls[0][0][0].body.timeout).toBe.defined; + + expect(searchApiStub.search.mock.calls[0][0][0].body).toBeDefined(); }); test('should remove possible timeout parameters on a request', async () => { - await parser.populateData([ - { url: { timeout: '500h', body: { timeout: '500h' } }, dataObject: {} }, - ]); - expect(searchStub.mock.calls[0][0][0].body.timeout).toBe.defined; - expect(searchStub.mock.calls[0][0][0].timeout).toBe(undefined); + data = [{ id: 0, rawResponse: {} }]; + await parser.populateData([{ url: { body: { timeout: '500h' } }, dataObject: {} }]); + expect(searchApiStub.search.mock.calls[0][0][0].body.timeout).toBeDefined(); }); }); diff --git a/src/plugins/vis_type_vega/public/data_model/search_api.ts b/src/plugins/vis_type_vega/public/data_model/search_api.ts new file mode 100644 index 0000000000000..c2eecf13c2d51 --- /dev/null +++ b/src/plugins/vis_type_vega/public/data_model/search_api.ts @@ -0,0 +1,60 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { combineLatest } from 'rxjs'; +import { map } from 'rxjs/operators'; +import { CoreStart, IUiSettingsClient } from 'kibana/public'; +import { + getSearchParamsFromRequest, + SearchRequest, + DataPublicPluginStart, +} from '../../../data/public'; + +export interface SearchAPIDependencies { + uiSettings: IUiSettingsClient; + injectedMetadata: CoreStart['injectedMetadata']; + search: DataPublicPluginStart['search']; +} + +export class SearchAPI { + constructor( + private readonly dependencies: SearchAPIDependencies, + private readonly abortSignal?: AbortSignal + ) {} + + search(searchRequests: SearchRequest[]) { + const { search } = this.dependencies.search; + + return combineLatest( + searchRequests.map((request, index) => { + const params = getSearchParamsFromRequest(request, { + uiSettings: this.dependencies.uiSettings, + injectedMetadata: this.dependencies.injectedMetadata, + }); + + return search({ params }, { signal: this.abortSignal }).pipe( + map((data) => ({ + id: index, + rawResponse: data.rawResponse, + })) + ); + }) + ); + } +} diff --git a/src/plugins/vis_type_vega/public/data_model/search_cache.test.js b/src/plugins/vis_type_vega/public/data_model/search_cache.test.js deleted file mode 100644 index 92f80545ce1b5..0000000000000 --- a/src/plugins/vis_type_vega/public/data_model/search_cache.test.js +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import { SearchCache } from './search_cache'; -jest.mock('../services'); - -describe(`SearchCache`, () => { - class FauxEs { - constructor() { - // contains all request batches, separated by 0 - this.searches = []; - } - - async search(request) { - this.searches.push(request); - return { req: request }; - } - } - - const request1 = { body: 'b1' }; - const expected1 = { req: { body: 'b1' } }; - const request2 = { body: 'b2' }; - const expected2 = { req: { body: 'b2' } }; - const request3 = { body: 'b3' }; - const expected3 = { req: { body: 'b3' } }; - - it(`sequence`, async () => { - const sc = new SearchCache(new FauxEs()); - - // empty request - let res = await sc.search([]); - expect(res).toEqual([]); - expect(sc._es.searches).toEqual([]); - - // single request - res = await sc.search([request1]); - expect(res).toEqual([expected1]); - expect(sc._es.searches).toEqual([request1]); - - // repeat the same search, use array notation - res = await sc.search([request1]); - expect(res).toEqual([expected1]); - expect(sc._es.searches).toEqual([request1]); // no new entries - - // new single search - res = await sc.search([request2]); - expect(res).toEqual([expected2]); - expect(sc._es.searches).toEqual([request1, request2]); - - // multiple search, some new, some old - res = await sc.search([request1, request3, request2]); - expect(res).toEqual([expected1, expected3, expected2]); - expect(sc._es.searches).toEqual([request1, request2, request3]); - }); -}); diff --git a/src/plugins/vis_type_vega/public/data_model/vega_parser.js b/src/plugins/vis_type_vega/public/data_model/vega_parser.js index f541b9f104adc..cbfe2a6ede4f2 100644 --- a/src/plugins/vis_type_vega/public/data_model/vega_parser.js +++ b/src/plugins/vis_type_vega/public/data_model/vega_parser.js @@ -46,7 +46,7 @@ const locToDirMap = { const DEFAULT_PARSER = 'elasticsearch'; export class VegaParser { - constructor(spec, searchCache, timeCache, filters, serviceSettings) { + constructor(spec, searchAPI, timeCache, filters, serviceSettings) { this.spec = spec; this.hideWarnings = false; this.error = undefined; @@ -54,7 +54,7 @@ export class VegaParser { const onWarn = this._onWarning.bind(this); this._urlParsers = { - elasticsearch: new EsQueryParser(timeCache, searchCache, filters, onWarn), + elasticsearch: new EsQueryParser(timeCache, searchAPI, filters, onWarn), emsfile: new EmsFileParser(serviceSettings), url: new UrlParser(onWarn), }; diff --git a/src/plugins/vis_type_vega/public/data_model/vega_parser.test.js b/src/plugins/vis_type_vega/public/data_model/vega_parser.test.js index 1bd26b8713044..a40ef31260b6f 100644 --- a/src/plugins/vis_type_vega/public/data_model/vega_parser.test.js +++ b/src/plugins/vis_type_vega/public/data_model/vega_parser.test.js @@ -78,9 +78,25 @@ describe(`VegaParser._setDefaultColors`, () => { }); describe('VegaParser._resolveEsQueries', () => { + let searchApiStub; + const data = [ + { + id: 0, + rawResponse: [42], + }, + ]; + + beforeEach(() => { + searchApiStub = { + search: jest.fn(() => ({ + toPromise: jest.fn(() => Promise.resolve(data)), + })), + }; + }); + function check(spec, expected, warnCount) { return async () => { - const vp = new VegaParser(spec, { search: async () => [[42]] }, 0, 0, { + const vp = new VegaParser(spec, searchApiStub, 0, 0, { getFileLayers: async () => [{ name: 'file1', url: 'url1' }], getUrlForRegionLayer: async (layer) => { return layer.url; diff --git a/src/plugins/vis_type_vega/public/plugin.ts b/src/plugins/vis_type_vega/public/plugin.ts index 1bce7ac92e564..b3e35dac3711f 100644 --- a/src/plugins/vis_type_vega/public/plugin.ts +++ b/src/plugins/vis_type_vega/public/plugin.ts @@ -28,6 +28,7 @@ import { setUISettings, setKibanaMapFactory, setMapsLegacyConfig, + setInjectedMetadata, } from './services'; import { createVegaFn } from './vega_fn'; @@ -96,5 +97,6 @@ export class VegaPlugin implements Plugin, void> { setNotifications(core.notifications); setSavedObjects(core.savedObjects); setData(data); + setInjectedMetadata(core.injectedMetadata); } } diff --git a/src/plugins/vis_type_vega/public/services.ts b/src/plugins/vis_type_vega/public/services.ts index f2fddb41cf72b..7d988d464b52b 100644 --- a/src/plugins/vis_type_vega/public/services.ts +++ b/src/plugins/vis_type_vega/public/services.ts @@ -17,8 +17,13 @@ * under the License. */ -import { SavedObjectsStart } from 'kibana/public'; -import { NotificationsStart, IUiSettingsClient } from 'src/core/public'; +import { + CoreStart, + SavedObjectsStart, + NotificationsStart, + IUiSettingsClient, +} from 'src/core/public'; + import { DataPublicPluginStart } from '../../data/public'; import { createGetterSetter } from '../../kibana_utils/public'; import { MapsLegacyConfigType } from '../../maps_legacy/public'; @@ -34,6 +39,10 @@ export const [getKibanaMapFactory, setKibanaMapFactory] = createGetterSetter('UISettings'); +export const [getInjectedMetadata, setInjectedMetadata] = createGetterSetter< + CoreStart['injectedMetadata'] +>('InjectedMetadata'); + export const [getSavedObjects, setSavedObjects] = createGetterSetter( 'SavedObjects' ); @@ -48,6 +57,5 @@ export const [getMapsLegacyConfig, setMapsLegacyConfig] = createGetterSetter getInjectedVars().esShardTimeout; export const getEnableExternalUrls = () => getInjectedVars().enableExternalUrls; export const getEmsTileLayerId = () => getMapsLegacyConfig().emsTileLayerId; diff --git a/src/plugins/vis_type_vega/public/vega_fn.ts b/src/plugins/vis_type_vega/public/vega_fn.ts index 6d45e043f7cee..a9c915fcfb636 100644 --- a/src/plugins/vis_type_vega/public/vega_fn.ts +++ b/src/plugins/vis_type_vega/public/vega_fn.ts @@ -54,8 +54,8 @@ export const createVegaFn = ( help: '', }, }, - async fn(input, args) { - const vegaRequestHandler = createVegaRequestHandler(dependencies); + async fn(input, args, context) { + const vegaRequestHandler = createVegaRequestHandler(dependencies, context.abortSignal); const response = await vegaRequestHandler({ timeRange: get(input, 'timeRange'), diff --git a/src/plugins/vis_type_vega/public/vega_request_handler.ts b/src/plugins/vis_type_vega/public/vega_request_handler.ts index efc02e368efa8..ac28f0b3782b2 100644 --- a/src/plugins/vis_type_vega/public/vega_request_handler.ts +++ b/src/plugins/vis_type_vega/public/vega_request_handler.ts @@ -19,14 +19,14 @@ import { Filter, esQuery, TimeRange, Query } from '../../data/public'; -// @ts-ignore -import { SearchCache } from './data_model/search_cache'; +import { SearchAPI } from './data_model/search_api'; + // @ts-ignore import { TimeCache } from './data_model/time_cache'; import { VegaVisualizationDependencies } from './plugin'; import { VisParams } from './vega_fn'; -import { getData } from './services'; +import { getData, getInjectedMetadata } from './services'; interface VegaRequestHandlerParams { query: Query; @@ -35,12 +35,11 @@ interface VegaRequestHandlerParams { visParams: VisParams; } -export function createVegaRequestHandler({ - plugins: { data }, - core: { uiSettings }, - serviceSettings, -}: VegaVisualizationDependencies) { - let searchCache: SearchCache | undefined; +export function createVegaRequestHandler( + { plugins: { data }, core: { uiSettings }, serviceSettings }: VegaVisualizationDependencies, + abortSignal?: AbortSignal +) { + let searchAPI: SearchAPI; const { timefilter } = data.query.timefilter; const timeCache = new TimeCache(timefilter, 3 * 1000); @@ -50,11 +49,15 @@ export function createVegaRequestHandler({ query, visParams, }: VegaRequestHandlerParams) { - if (!searchCache) { - searchCache = new SearchCache(getData().search.__LEGACY.esClient, { - max: 10, - maxAge: 4 * 1000, - }); + if (!searchAPI) { + searchAPI = new SearchAPI( + { + uiSettings, + search: getData().search, + injectedMetadata: getInjectedMetadata(), + }, + abortSignal + ); } timeCache.setTimeRange(timeRange); @@ -63,7 +66,7 @@ export function createVegaRequestHandler({ const filtersDsl = esQuery.buildEsQuery(undefined, query, filters, esQueryConfigs); // @ts-ignore const { VegaParser } = await import('./data_model/vega_parser'); - const vp = new VegaParser(visParams.spec, searchCache, timeCache, filtersDsl, serviceSettings); + const vp = new VegaParser(visParams.spec, searchAPI, timeCache, filtersDsl, serviceSettings); return await vp.parseAsync(); }; diff --git a/src/plugins/visualizations/public/wizard/__snapshots__/new_vis_modal.test.tsx.snap b/src/plugins/visualizations/public/wizard/__snapshots__/new_vis_modal.test.tsx.snap index 22cc873cbdb5d..53ef164685a1c 100644 --- a/src/plugins/visualizations/public/wizard/__snapshots__/new_vis_modal.test.tsx.snap +++ b/src/plugins/visualizations/public/wizard/__snapshots__/new_vis_modal.test.tsx.snap @@ -1264,6 +1264,7 @@ exports[`NewVisModal filter for visualization types should render as expected 1` > @@ -2772,6 +2773,7 @@ exports[`NewVisModal should render as expected 1`] = ` > diff --git a/test/functional/services/apps_menu.ts b/test/functional/services/apps_menu.ts index 969bddbd30f9a..aa7934d6b1156 100644 --- a/test/functional/services/apps_menu.ts +++ b/test/functional/services/apps_menu.ts @@ -58,6 +58,10 @@ export function AppsMenuProvider({ getService, getPageObjects }: FtrProviderCont public async closeCollapsibleNav() { const CLOSE_BUTTON = '[data-test-subj=collapsibleNav] > button'; if (await find.existsByCssSelector(CLOSE_BUTTON)) { + // Close button is only visible when focused + const button = await find.byCssSelector(CLOSE_BUTTON); + await button.focus(); + await find.clickByCssSelector(CLOSE_BUTTON); } } diff --git a/test/interpreter_functional/plugins/kbn_tp_run_pipeline/package.json b/test/interpreter_functional/plugins/kbn_tp_run_pipeline/package.json index acd78cb4955e3..24b38fae96653 100644 --- a/test/interpreter_functional/plugins/kbn_tp_run_pipeline/package.json +++ b/test/interpreter_functional/plugins/kbn_tp_run_pipeline/package.json @@ -8,7 +8,7 @@ }, "license": "Apache-2.0", "dependencies": { - "@elastic/eui": "23.3.1", + "@elastic/eui": "24.1.0", "react": "^16.12.0", "react-dom": "^16.12.0" }, diff --git a/test/plugin_functional/plugins/kbn_sample_panel_action/package.json b/test/plugin_functional/plugins/kbn_sample_panel_action/package.json index 45d07933c4209..71a635c444b8c 100644 --- a/test/plugin_functional/plugins/kbn_sample_panel_action/package.json +++ b/test/plugin_functional/plugins/kbn_sample_panel_action/package.json @@ -8,7 +8,7 @@ }, "license": "Apache-2.0", "dependencies": { - "@elastic/eui": "23.3.1", + "@elastic/eui": "24.1.0", "react": "^16.12.0" }, "scripts": { diff --git a/test/plugin_functional/plugins/kbn_tp_custom_visualizations/package.json b/test/plugin_functional/plugins/kbn_tp_custom_visualizations/package.json index ca99e9b5995c1..78f0b42a6fbda 100644 --- a/test/plugin_functional/plugins/kbn_tp_custom_visualizations/package.json +++ b/test/plugin_functional/plugins/kbn_tp_custom_visualizations/package.json @@ -8,7 +8,7 @@ }, "license": "Apache-2.0", "dependencies": { - "@elastic/eui": "23.3.1", + "@elastic/eui": "24.1.0", "react": "^16.12.0" }, "scripts": { diff --git a/test/plugin_functional/plugins/kbn_tp_embeddable_explorer/package.json b/test/plugin_functional/plugins/kbn_tp_embeddable_explorer/package.json index 63dde0fa96dd3..6dbc9c71f2e81 100644 --- a/test/plugin_functional/plugins/kbn_tp_embeddable_explorer/package.json +++ b/test/plugin_functional/plugins/kbn_tp_embeddable_explorer/package.json @@ -8,7 +8,7 @@ }, "license": "Apache-2.0", "dependencies": { - "@elastic/eui": "23.3.1", + "@elastic/eui": "24.1.0", "react": "^16.12.0" }, "scripts": { diff --git a/test/scripts/jenkins_visual_regression.sh b/test/scripts/jenkins_visual_regression.sh index c6fefd45b005d..a32782deec65b 100755 --- a/test/scripts/jenkins_visual_regression.sh +++ b/test/scripts/jenkins_visual_regression.sh @@ -11,8 +11,7 @@ mkdir -p "$installDir" tar -xzf "$linuxBuild" -C "$installDir" --strip=1 echo " -> running visual regression tests from kibana directory" -checks-reporter-with-killswitch "X-Pack visual regression tests" \ - yarn percy exec -t 500 -- -- \ +yarn percy exec -t 500 -- -- \ node scripts/functional_tests \ --debug --bail \ --kibana-install-dir "$installDir" \ diff --git a/test/scripts/jenkins_xpack_visual_regression.sh b/test/scripts/jenkins_xpack_visual_regression.sh index 96521ccc8f787..e406bb3e6106f 100755 --- a/test/scripts/jenkins_xpack_visual_regression.sh +++ b/test/scripts/jenkins_xpack_visual_regression.sh @@ -13,9 +13,11 @@ tar -xzf "$linuxBuild" -C "$installDir" --strip=1 echo " -> running visual regression tests from x-pack directory" cd "$XPACK_DIR" -checks-reporter-with-killswitch "X-Pack visual regression tests" \ - yarn percy exec -t 500 -- -- \ +yarn percy exec -t 500 -- -- \ node scripts/functional_tests \ --debug --bail \ --kibana-install-dir "$installDir" \ --config test/visual_regression/config.ts; + +cd "$KIBANA_DIR" +source "test/scripts/jenkins_xpack_page_load_metrics.sh" diff --git a/x-pack/package.json b/x-pack/package.json index b3dcde2194d3f..fb708ab09d841 100644 --- a/x-pack/package.json +++ b/x-pack/package.json @@ -190,7 +190,7 @@ "@elastic/apm-rum-react": "^1.1.1", "@elastic/datemath": "5.0.3", "@elastic/ems-client": "7.8.0", - "@elastic/eui": "23.3.1", + "@elastic/eui": "24.1.0", "@elastic/filesaver": "1.1.2", "@elastic/maki": "6.3.0", "@elastic/node-crypto": "1.1.1", diff --git a/x-pack/plugins/apm/jest.config.js b/x-pack/plugins/apm/jest.config.js index c3ae694fe8e14..43bdeb583c819 100644 --- a/x-pack/plugins/apm/jest.config.js +++ b/x-pack/plugins/apm/jest.config.js @@ -31,6 +31,7 @@ module.exports = { collectCoverageFrom: [ '**/*.{js,jsx,ts,tsx}', '!**/{__test__,__snapshots__,__examples__,integration_tests,tests}/**', + '!**/*.stories.{js,ts,tsx}', '!**/*.test.{js,ts,tsx}', '!**/dev_docs/**', '!**/e2e/**', diff --git a/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/List/__test__/__snapshots__/List.test.tsx.snap b/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/List/__test__/__snapshots__/List.test.tsx.snap index 3de725dc58ea7..6a20e3c103709 100644 --- a/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/List/__test__/__snapshots__/List.test.tsx.snap +++ b/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/List/__test__/__snapshots__/List.test.tsx.snap @@ -161,6 +161,7 @@ exports[`ErrorGroupOverview -> List should render empty state 1`] = ` @@ -575,6 +576,7 @@ exports[`ErrorGroupOverview -> List should render with data 1`] = ` @@ -754,6 +756,7 @@ exports[`ErrorGroupOverview -> List should render with data 1`] = ` @@ -859,6 +862,7 @@ exports[`ErrorGroupOverview -> List should render with data 1`] = ` > @@ -889,6 +893,7 @@ exports[`ErrorGroupOverview -> List should render with data 1`] = `
@@ -958,6 +963,7 @@ exports[`ErrorGroupOverview -> List should render with data 1`] = ` > @@ -984,6 +990,7 @@ exports[`ErrorGroupOverview -> List should render with data 1`] = ` @@ -1089,6 +1096,7 @@ exports[`ErrorGroupOverview -> List should render with data 1`] = ` > @@ -1119,6 +1127,7 @@ exports[`ErrorGroupOverview -> List should render with data 1`] = `
@@ -1188,6 +1197,7 @@ exports[`ErrorGroupOverview -> List should render with data 1`] = ` > @@ -1214,6 +1224,7 @@ exports[`ErrorGroupOverview -> List should render with data 1`] = ` @@ -1319,6 +1330,7 @@ exports[`ErrorGroupOverview -> List should render with data 1`] = ` > @@ -1349,6 +1361,7 @@ exports[`ErrorGroupOverview -> List should render with data 1`] = `
@@ -1418,6 +1431,7 @@ exports[`ErrorGroupOverview -> List should render with data 1`] = ` > @@ -1444,6 +1458,7 @@ exports[`ErrorGroupOverview -> List should render with data 1`] = ` @@ -1549,6 +1564,7 @@ exports[`ErrorGroupOverview -> List should render with data 1`] = ` > @@ -1579,6 +1595,7 @@ exports[`ErrorGroupOverview -> List should render with data 1`] = `
@@ -1648,6 +1665,7 @@ exports[`ErrorGroupOverview -> List should render with data 1`] = ` > diff --git a/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/List/index.tsx b/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/List/index.tsx index ed683b8ecd11d..1096c0c77db30 100644 --- a/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/List/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/List/index.tsx @@ -103,7 +103,7 @@ const ErrorGroupList: React.FC = (props) => { }), field: 'type', sortable: false, - render: (type: string, item: ErrorGroupListAPIResponse[0]) => { + render: (type: string) => { return ( ; + return ; }, { info: { propTables: false, source: false }, diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Cytoscape.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Cytoscape.tsx index cb908785d64d8..c57d702b9a546 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/Cytoscape.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Cytoscape.tsx @@ -121,15 +121,6 @@ export function Cytoscape({ const trackApmEvent = useUiTracker({ app: 'apm' }); - // Trigger a custom "data" event when data changes - useEffect(() => { - if (cy) { - cy.remove(cy.elements()); - cy.add(elements); - cy.trigger('data'); - } - }, [cy, elements]); - // Set up cytoscape event handlers useEffect(() => { const resetConnectedEdgeStyle = (node?: cytoscape.NodeSingular) => { @@ -223,6 +214,10 @@ export function Cytoscape({ cy.on('mouseout', 'edge, node', mouseoutHandler); cy.on('select', 'node', selectHandler); cy.on('unselect', 'node', unselectHandler); + + cy.remove(cy.elements()); + cy.add(elements); + cy.trigger('data'); } return () => { @@ -241,7 +236,7 @@ export function Cytoscape({ } clearTimeout(layoutstopDelayTimeout); }; - }, [cy, height, serviceName, trackApmEvent, width]); + }, [cy, elements, height, serviceName, trackApmEvent, width]); return ( diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/SettingsPage.tsx b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/SettingsPage.tsx index 3a08d4e74da94..d4b541442fa32 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/SettingsPage.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/SettingsPage.tsx @@ -39,7 +39,7 @@ import { getOptionLabel } from '../../../../../../../common/agent_configuration/ function removeEmpty(obj: T): T { return Object.fromEntries( - Object.entries(obj).filter(([k, v]) => v != null && v !== '') + Object.entries(obj).filter(([_, v]) => v != null && v !== '') ); } diff --git a/x-pack/plugins/apm/public/components/shared/ErrorRateAlertTrigger/index.stories.tsx b/x-pack/plugins/apm/public/components/shared/ErrorRateAlertTrigger/index.stories.tsx index ddfca94e567d9..ebcb1627984ad 100644 --- a/x-pack/plugins/apm/public/components/shared/ErrorRateAlertTrigger/index.stories.tsx +++ b/x-pack/plugins/apm/public/components/shared/ErrorRateAlertTrigger/index.stories.tsx @@ -7,20 +7,29 @@ import { storiesOf } from '@storybook/react'; import React from 'react'; import { ErrorRateAlertTrigger } from '.'; +import { ApmPluginContextValue } from '../../../context/ApmPluginContext'; +import { + mockApmPluginContextValue, + MockApmPluginContextWrapper, +} from '../../../context/ApmPluginContext/MockApmPluginContext'; -storiesOf('app/ErrorRateAlertTrigger', module).add('example', (props) => { +storiesOf('app/ErrorRateAlertTrigger', module).add('example', () => { const params = { threshold: 2, window: '5m', }; return ( -
- undefined} - setAlertProperty={() => undefined} - /> -
+ +
+ undefined} + setAlertProperty={() => undefined} + /> +
+
); }); diff --git a/x-pack/plugins/apm/public/components/shared/StickyProperties/index.tsx b/x-pack/plugins/apm/public/components/shared/StickyProperties/index.tsx index 74c75e4585c3e..8bfea721c854d 100644 --- a/x-pack/plugins/apm/public/components/shared/StickyProperties/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/StickyProperties/index.tsx @@ -69,7 +69,6 @@ function getPropertyLabel({ fieldName, label }: Partial) { function getPropertyValue({ val, - fieldName, truncated = false, }: Partial) { if (truncated) { diff --git a/x-pack/plugins/apm/public/components/shared/TransactionDurationAlertTrigger/index.stories.tsx b/x-pack/plugins/apm/public/components/shared/TransactionDurationAlertTrigger/index.stories.tsx index 7b22218bf23df..da9adbb8dfead 100644 --- a/x-pack/plugins/apm/public/components/shared/TransactionDurationAlertTrigger/index.stories.tsx +++ b/x-pack/plugins/apm/public/components/shared/TransactionDurationAlertTrigger/index.stories.tsx @@ -3,48 +3,51 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ +// import { storiesOf } from '@storybook/react'; import { cloneDeep, merge } from 'lodash'; -import { storiesOf } from '@storybook/react'; import React from 'react'; import { TransactionDurationAlertTrigger } from '.'; +import { ApmPluginContextValue } from '../../../context/ApmPluginContext'; import { - MockApmPluginContextWrapper, mockApmPluginContextValue, + MockApmPluginContextWrapper, } from '../../../context/ApmPluginContext/MockApmPluginContext'; import { MockUrlParamsContextProvider } from '../../../context/UrlParamsContext/MockUrlParamsContextProvider'; -import { ApmPluginContextValue } from '../../../context/ApmPluginContext'; -storiesOf('app/TransactionDurationAlertTrigger', module).add( - 'example', - (context) => { - const params = { - threshold: 1500, - aggregationType: 'avg' as const, - window: '5m', - }; +// Disabling this because we currently don't have a way to mock `useEnvironments` +// which is used by this component. Using the fetch-mock module should work, but +// our current storybook setup has core-js-related problems when trying to import +// it. +// storiesOf('app/TransactionDurationAlertTrigger', module).add('example', +// eslint-disable-next-line no-unused-expressions +() => { + const params = { + threshold: 1500, + aggregationType: 'avg' as const, + window: '5m', + }; - const contextMock = (merge(cloneDeep(mockApmPluginContextValue), { - core: { - http: { - get: () => { - return Promise.resolve({ transactionTypes: ['request'] }); - }, + const contextMock = (merge(cloneDeep(mockApmPluginContextValue), { + core: { + http: { + get: () => { + return Promise.resolve({ transactionTypes: ['request'] }); }, }, - }) as unknown) as ApmPluginContextValue; + }, + }) as unknown) as ApmPluginContextValue; - return ( -
- - - undefined} - setAlertProperty={() => undefined} - /> - - -
- ); - } -); + return ( +
+ + + undefined} + setAlertProperty={() => undefined} + /> + + +
+ ); +}; diff --git a/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/ChoroplethMap/index.tsx b/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/ChoroplethMap/index.tsx index 937c18807f80f..ebd6061831f4e 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/ChoroplethMap/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/TransactionCharts/ChoroplethMap/index.tsx @@ -137,7 +137,7 @@ export const ChoroplethMap: React.FC = (props) => { }, [map, items, tooltipState]); const updateTooltipStateOnMousemoveRef = useRef( - (event: mapboxgl.MapMouseEvent & mapboxgl.EventData) => {} + (_event: mapboxgl.MapMouseEvent & mapboxgl.EventData) => {} ); // initialization side effect, only runs once diff --git a/x-pack/plugins/apm/public/context/LoadingIndicatorContext.tsx b/x-pack/plugins/apm/public/context/LoadingIndicatorContext.tsx index 32e52f8e396b5..a26653d3d5294 100644 --- a/x-pack/plugins/apm/public/context/LoadingIndicatorContext.tsx +++ b/x-pack/plugins/apm/public/context/LoadingIndicatorContext.tsx @@ -10,7 +10,7 @@ import { useDelayedVisibility } from '../components/shared/useDelayedVisibility' export const LoadingIndicatorContext = React.createContext({ statuses: {}, - dispatchStatus: (action: Action) => {}, + dispatchStatus: (_action: Action) => {}, }); interface State { diff --git a/x-pack/plugins/apm/public/context/UrlParamsContext/index.tsx b/x-pack/plugins/apm/public/context/UrlParamsContext/index.tsx index bc8cabb6f6641..6083a216bbf95 100644 --- a/x-pack/plugins/apm/public/context/UrlParamsContext/index.tsx +++ b/x-pack/plugins/apm/public/context/UrlParamsContext/index.tsx @@ -40,7 +40,7 @@ function useUiFilters(params: IUrlParams): UIFilters { return useDeepObjectIdentity({ kuery, environment, ...localUiFilters }); } -const defaultRefresh = (time: TimeRange) => {}; +const defaultRefresh = (_time: TimeRange) => {}; const UrlParamsContext = createContext({ urlParams: {} as IUrlParams, diff --git a/x-pack/plugins/apm/public/services/rest/ml.ts b/x-pack/plugins/apm/public/services/rest/ml.ts index 7d1f386fa896c..99c162bde02da 100644 --- a/x-pack/plugins/apm/public/services/rest/ml.ts +++ b/x-pack/plugins/apm/public/services/rest/ml.ts @@ -36,7 +36,7 @@ interface StartedMLJobApiResponse { jobs: MlResponseItem[]; } -async function getTransactionIndices(http: HttpSetup) { +async function getTransactionIndices() { const indices = await callApmApi({ method: 'GET', pathname: `/api/apm/settings/apm-indices`, @@ -53,7 +53,7 @@ export async function startMLJob({ transactionType: string; http: HttpSetup; }) { - const transactionIndices = await getTransactionIndices(http); + const transactionIndices = await getTransactionIndices(); const groups = [ 'apm', encodeForMlApi(serviceName), diff --git a/x-pack/plugins/apm/scripts/optimize-tsconfig/tsconfig.json b/x-pack/plugins/apm/scripts/optimize-tsconfig/tsconfig.json index 34b67c834554d..5a810fa90259a 100644 --- a/x-pack/plugins/apm/scripts/optimize-tsconfig/tsconfig.json +++ b/x-pack/plugins/apm/scripts/optimize-tsconfig/tsconfig.json @@ -4,8 +4,8 @@ "./plugins/observability/**/*", "./typings/**/*" ], - "exclude": [ - "**/__fixtures__/**/*", - "./plugins/apm/e2e/cypress/**/*" - ] + "exclude": ["**/__fixtures__/**/*", "./plugins/apm/e2e/cypress/**/*"], + "compilerOptions": { + "noErrorTruncation": true + } } diff --git a/x-pack/plugins/apm/scripts/upload-telemetry-data/generate-sample-documents.ts b/x-pack/plugins/apm/scripts/upload-telemetry-data/generate-sample-documents.ts index e9f1e99f1fc39..50de0d5b234d4 100644 --- a/x-pack/plugins/apm/scripts/upload-telemetry-data/generate-sample-documents.ts +++ b/x-pack/plugins/apm/scripts/upload-telemetry-data/generate-sample-documents.ts @@ -78,7 +78,7 @@ export async function generateSampleDocuments( const dateOfScriptExecution = new Date(); return flatten( - range(0, opts.instances).map((instanceNo) => { + range(0, opts.instances).map(() => { const instanceId = uuid.v4(); const defaults = { cluster_uuid: instanceId, diff --git a/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts b/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts index df82d44fb5041..632e653a2f6e9 100644 --- a/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts +++ b/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts @@ -120,7 +120,7 @@ export async function createApmTelemetry({ usageCollector.registerCollector(collector); - core.getStartServices().then(([coreStart, pluginsStart]) => { + core.getStartServices().then(([_coreStart, pluginsStart]) => { const { taskManager: taskManagerStart } = pluginsStart as { taskManager: TaskManagerStartContract; }; diff --git a/x-pack/plugins/apm/server/lib/service_map/get_service_map_from_trace_ids.ts b/x-pack/plugins/apm/server/lib/service_map/get_service_map_from_trace_ids.ts index e34479e92a06c..01cbc1aa9b989 100644 --- a/x-pack/plugins/apm/server/lib/service_map/get_service_map_from_trace_ids.ts +++ b/x-pack/plugins/apm/server/lib/service_map/get_service_map_from_trace_ids.ts @@ -270,7 +270,7 @@ export async function getServiceMapFromTraceIds({ return conns; }, [] as Connection[]); }, [] as Connection[]), - (value, index, array) => { + (value, _index, array) => { return find(array, value); } ); diff --git a/x-pack/plugins/apm/server/lib/services/annotations/index.ts b/x-pack/plugins/apm/server/lib/services/annotations/index.ts index 4d3efc478a4fd..9365213a87f6e 100644 --- a/x-pack/plugins/apm/server/lib/services/annotations/index.ts +++ b/x-pack/plugins/apm/server/lib/services/annotations/index.ts @@ -41,7 +41,7 @@ export async function getServiceAnnotations({ : []; if (storedAnnotations.length) { - derivedAnnotationsPromise.catch((error) => { + derivedAnnotationsPromise.catch(() => { // handle error silently to prevent Kibana from crashing }); return { annotations: storedAnnotations }; diff --git a/x-pack/plugins/apm/server/lib/settings/apm_indices/save_apm_indices.ts b/x-pack/plugins/apm/server/lib/settings/apm_indices/save_apm_indices.ts index 9601bdd51824d..d4ef6e2f91051 100644 --- a/x-pack/plugins/apm/server/lib/settings/apm_indices/save_apm_indices.ts +++ b/x-pack/plugins/apm/server/lib/settings/apm_indices/save_apm_indices.ts @@ -28,6 +28,6 @@ export async function saveApmIndices( function removeEmpty(apmIndices: Partial) { return Object.entries(apmIndices) .map(([key, value]) => [key, value?.trim()]) - .filter(([key, value]) => !!value) + .filter(([_, value]) => !!value) .reduce((obj, [key, value]) => ({ ...obj, [key as string]: value }), {}); } diff --git a/x-pack/plugins/apm/server/routes/errors.ts b/x-pack/plugins/apm/server/routes/errors.ts index 7e45f412d4bdb..1615550027d3c 100644 --- a/x-pack/plugins/apm/server/routes/errors.ts +++ b/x-pack/plugins/apm/server/routes/errors.ts @@ -12,7 +12,7 @@ import { getErrorGroups } from '../lib/errors/get_error_groups'; import { setupRequest } from '../lib/helpers/setup_request'; import { uiFiltersRt, rangeRt } from './default_api_types'; -export const errorsRoute = createRoute((core) => ({ +export const errorsRoute = createRoute(() => ({ path: '/api/apm/services/{serviceName}/errors', params: { path: t.type({ diff --git a/x-pack/plugins/apm/server/routes/service_nodes.ts b/x-pack/plugins/apm/server/routes/service_nodes.ts index a6e9175fcb651..8721407671825 100644 --- a/x-pack/plugins/apm/server/routes/service_nodes.ts +++ b/x-pack/plugins/apm/server/routes/service_nodes.ts @@ -9,7 +9,7 @@ import { setupRequest } from '../lib/helpers/setup_request'; import { getServiceNodes } from '../lib/service_nodes'; import { rangeRt, uiFiltersRt } from './default_api_types'; -export const serviceNodesRoute = createRoute((core) => ({ +export const serviceNodesRoute = createRoute(() => ({ path: '/api/apm/services/{serviceName}/serviceNodes', params: { path: t.type({ diff --git a/x-pack/plugins/apm/server/routes/services.ts b/x-pack/plugins/apm/server/routes/services.ts index 996bfbd9184d1..8672c6c108c4c 100644 --- a/x-pack/plugins/apm/server/routes/services.ts +++ b/x-pack/plugins/apm/server/routes/services.ts @@ -17,7 +17,7 @@ import { uiFiltersRt, rangeRt } from './default_api_types'; import { getServiceAnnotations } from '../lib/services/annotations'; import { dateAsStringRt } from '../../common/runtime_types/date_as_string_rt'; -export const servicesRoute = createRoute((core) => ({ +export const servicesRoute = createRoute(() => ({ path: '/api/apm/services', params: { query: t.intersection([uiFiltersRt, rangeRt]), diff --git a/x-pack/plugins/apm/server/routes/settings/agent_configuration.ts b/x-pack/plugins/apm/server/routes/settings/agent_configuration.ts index 6fd864a337165..f5c9cc2adf238 100644 --- a/x-pack/plugins/apm/server/routes/settings/agent_configuration.ts +++ b/x-pack/plugins/apm/server/routes/settings/agent_configuration.ts @@ -24,7 +24,7 @@ import { import { jsonRt } from '../../../common/runtime_types/json_rt'; // get list of configurations -export const agentConfigurationRoute = createRoute((core) => ({ +export const agentConfigurationRoute = createRoute(() => ({ path: '/api/apm/settings/agent-configuration', handler: async ({ context, request }) => { const setup = await setupRequest(context, request); @@ -137,7 +137,7 @@ export const createOrUpdateAgentConfigurationRoute = createRoute(() => ({ })); // Lookup single configuration (used by APM Server) -export const agentConfigurationSearchRoute = createRoute((core) => ({ +export const agentConfigurationSearchRoute = createRoute(() => ({ method: 'POST', path: '/api/apm/settings/agent-configuration/search', params: { diff --git a/x-pack/plugins/apm/server/routes/settings/apm_indices.ts b/x-pack/plugins/apm/server/routes/settings/apm_indices.ts index 2d5722744f93e..e52ce760e026a 100644 --- a/x-pack/plugins/apm/server/routes/settings/apm_indices.ts +++ b/x-pack/plugins/apm/server/routes/settings/apm_indices.ts @@ -34,7 +34,7 @@ export const apmIndicesRoute = createRoute(() => ({ })); // save ui indices -export const saveApmIndicesRoute = createRoute((core) => ({ +export const saveApmIndicesRoute = createRoute(() => ({ method: 'POST', path: '/api/apm/settings/apm-indices/save', options: { @@ -50,7 +50,7 @@ export const saveApmIndicesRoute = createRoute((core) => ({ 'apm_oss.metricsIndices': t.string, }), }, - handler: async ({ context, request }) => { + handler: async ({ context }) => { const { body } = context.params; const savedObjectsClient = context.core.savedObjects.client; return await saveApmIndices(savedObjectsClient, body); diff --git a/x-pack/plugins/apm/server/routes/settings/custom_link.ts b/x-pack/plugins/apm/server/routes/settings/custom_link.ts index f32840fe08b9c..83c23a75e999d 100644 --- a/x-pack/plugins/apm/server/routes/settings/custom_link.ts +++ b/x-pack/plugins/apm/server/routes/settings/custom_link.ts @@ -17,7 +17,7 @@ import { getTransaction } from '../../lib/settings/custom_link/get_transaction'; import { listCustomLinks } from '../../lib/settings/custom_link/list_custom_links'; import { createRoute } from '../create_route'; -export const customLinkTransactionRoute = createRoute((core) => ({ +export const customLinkTransactionRoute = createRoute(() => ({ path: '/api/apm/settings/custom_links/transaction', params: { query: filterOptionsRt, @@ -31,7 +31,7 @@ export const customLinkTransactionRoute = createRoute((core) => ({ }, })); -export const listCustomLinksRoute = createRoute((core) => ({ +export const listCustomLinksRoute = createRoute(() => ({ path: '/api/apm/settings/custom_links', params: { query: filterOptionsRt, diff --git a/x-pack/plugins/canvas/public/apps/workpad/workpad_app/workpad_telemetry.tsx b/x-pack/plugins/canvas/public/apps/workpad/workpad_app/workpad_telemetry.tsx index 47b461f22ad65..3014369d94857 100644 --- a/x-pack/plugins/canvas/public/apps/workpad/workpad_app/workpad_telemetry.tsx +++ b/x-pack/plugins/canvas/public/apps/workpad/workpad_app/workpad_telemetry.tsx @@ -69,6 +69,7 @@ export const withUnconnectedElementsLoadedTelemetry =

( ) => function ElementsLoadedTelemetry(props: ElementsLoadedTelemetryProps) { const { telemetryElementCounts, workpad, telemetryResolvedArgs, ...other } = props; + const { error, pending } = telemetryElementCounts; const [currentWorkpadId, setWorkpadId] = useState(undefined); const [hasReported, setHasReported] = useState(false); @@ -87,27 +88,20 @@ export const withUnconnectedElementsLoadedTelemetry =

( 0 ); - if ( - workpadElementCount === 0 || - (resolvedArgsAreForWorkpad && telemetryElementCounts.pending === 0) - ) { + if (workpadElementCount === 0 || (resolvedArgsAreForWorkpad && pending === 0)) { setHasReported(true); } else { setHasReported(false); } - } else if ( - !hasReported && - telemetryElementCounts.pending === 0 && - resolvedArgsAreForWorkpad - ) { - if (telemetryElementCounts.error > 0) { + } else if (!hasReported && pending === 0 && resolvedArgsAreForWorkpad) { + if (error > 0) { trackMetric(METRIC_TYPE.LOADED, [WorkpadLoadedMetric, WorkpadLoadedWithErrorsMetric]); } else { trackMetric(METRIC_TYPE.LOADED, WorkpadLoadedMetric); } setHasReported(true); } - }); + }, [currentWorkpadId, hasReported, error, pending, telemetryResolvedArgs, workpad]); return ; }; diff --git a/x-pack/plugins/canvas/public/components/asset_manager/__examples__/__snapshots__/asset.examples.storyshot b/x-pack/plugins/canvas/public/components/asset_manager/__examples__/__snapshots__/asset.examples.storyshot index 6601f570209e9..14791cd3d8b25 100644 --- a/x-pack/plugins/canvas/public/components/asset_manager/__examples__/__snapshots__/asset.examples.storyshot +++ b/x-pack/plugins/canvas/public/components/asset_manager/__examples__/__snapshots__/asset.examples.storyshot @@ -63,6 +63,7 @@ exports[`Storyshots components/Assets/Asset airplane 1`] = ` > @@ -88,6 +89,7 @@ exports[`Storyshots components/Assets/Asset airplane 1`] = ` > @@ -118,6 +120,7 @@ exports[`Storyshots components/Assets/Asset airplane 1`] = ` > @@ -148,6 +151,7 @@ exports[`Storyshots components/Assets/Asset airplane 1`] = ` > @@ -237,6 +241,7 @@ exports[`Storyshots components/Assets/Asset marker 1`] = ` > @@ -262,6 +267,7 @@ exports[`Storyshots components/Assets/Asset marker 1`] = ` > @@ -292,6 +298,7 @@ exports[`Storyshots components/Assets/Asset marker 1`] = ` > @@ -322,6 +329,7 @@ exports[`Storyshots components/Assets/Asset marker 1`] = ` > diff --git a/x-pack/plugins/canvas/public/components/asset_manager/__examples__/__snapshots__/asset_manager.stories.storyshot b/x-pack/plugins/canvas/public/components/asset_manager/__examples__/__snapshots__/asset_manager.stories.storyshot index aff630b21c770..1b8f1480759f6 100644 --- a/x-pack/plugins/canvas/public/components/asset_manager/__examples__/__snapshots__/asset_manager.stories.storyshot +++ b/x-pack/plugins/canvas/public/components/asset_manager/__examples__/__snapshots__/asset_manager.stories.storyshot @@ -422,6 +422,7 @@ Array [ > @@ -447,6 +448,7 @@ Array [ > @@ -477,6 +479,7 @@ Array [ > @@ -507,6 +510,7 @@ Array [ > @@ -585,6 +589,7 @@ Array [ > @@ -610,6 +615,7 @@ Array [ > @@ -640,6 +646,7 @@ Array [ > @@ -670,6 +677,7 @@ Array [ > diff --git a/x-pack/plugins/canvas/public/components/router/index.ts b/x-pack/plugins/canvas/public/components/router/index.ts index 5e014870f5158..fa857c6f0cd3c 100644 --- a/x-pack/plugins/canvas/public/components/router/index.ts +++ b/x-pack/plugins/canvas/public/components/router/index.ts @@ -11,7 +11,6 @@ import { enableAutoplay, setRefreshInterval, setAutoplayInterval, - // @ts-ignore untyped local } from '../../state/actions/workpad'; // @ts-ignore untyped local import { Router as Component } from './router'; diff --git a/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/__snapshots__/element_controls.stories.storyshot b/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/__snapshots__/element_controls.stories.storyshot index 6f12f68356467..408b0679c415f 100644 --- a/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/__snapshots__/element_controls.stories.storyshot +++ b/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/__snapshots__/element_controls.stories.storyshot @@ -16,6 +16,7 @@ exports[`Storyshots components/SavedElementsModal/ElementControls has two button > @@ -42,6 +43,7 @@ exports[`Storyshots components/SavedElementsModal/ElementControls has two button > diff --git a/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/__snapshots__/element_grid.stories.storyshot b/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/__snapshots__/element_grid.stories.storyshot index be0fb0573c394..1c506819df1fb 100644 --- a/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/__snapshots__/element_grid.stories.storyshot +++ b/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/__snapshots__/element_grid.stories.storyshot @@ -66,6 +66,7 @@ exports[`Storyshots components/SavedElementsModal/ElementGrid default 1`] = ` > @@ -92,6 +93,7 @@ exports[`Storyshots components/SavedElementsModal/ElementGrid default 1`] = ` > @@ -170,6 +172,7 @@ exports[`Storyshots components/SavedElementsModal/ElementGrid default 1`] = ` > @@ -196,6 +199,7 @@ exports[`Storyshots components/SavedElementsModal/ElementGrid default 1`] = ` > @@ -274,6 +278,7 @@ exports[`Storyshots components/SavedElementsModal/ElementGrid default 1`] = ` > @@ -300,6 +305,7 @@ exports[`Storyshots components/SavedElementsModal/ElementGrid default 1`] = ` > diff --git a/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/__snapshots__/saved_elements_modal.stories.storyshot b/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/__snapshots__/saved_elements_modal.stories.storyshot index 03093b41300b8..04b2184f27462 100644 --- a/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/__snapshots__/saved_elements_modal.stories.storyshot +++ b/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/__snapshots__/saved_elements_modal.stories.storyshot @@ -362,6 +362,7 @@ Array [ > @@ -388,6 +389,7 @@ Array [ > @@ -466,6 +468,7 @@ Array [ > @@ -492,6 +495,7 @@ Array [ > @@ -570,6 +574,7 @@ Array [ > @@ -596,6 +601,7 @@ Array [ > @@ -851,6 +857,7 @@ Array [ > @@ -877,6 +884,7 @@ Array [ > diff --git a/x-pack/plugins/canvas/public/components/sidebar_header/__examples__/__snapshots__/sidebar_header.stories.storyshot b/x-pack/plugins/canvas/public/components/sidebar_header/__examples__/__snapshots__/sidebar_header.stories.storyshot index 4d5b9570ee20f..16263aa7ea384 100644 --- a/x-pack/plugins/canvas/public/components/sidebar_header/__examples__/__snapshots__/sidebar_header.stories.storyshot +++ b/x-pack/plugins/canvas/public/components/sidebar_header/__examples__/__snapshots__/sidebar_header.stories.storyshot @@ -55,6 +55,7 @@ exports[`Storyshots components/Sidebar/SidebarHeader with layer controls 1`] = ` > @@ -80,6 +81,7 @@ exports[`Storyshots components/Sidebar/SidebarHeader with layer controls 1`] = ` > @@ -105,6 +107,7 @@ exports[`Storyshots components/Sidebar/SidebarHeader with layer controls 1`] = ` > @@ -130,6 +133,7 @@ exports[`Storyshots components/Sidebar/SidebarHeader with layer controls 1`] = ` > diff --git a/x-pack/plugins/canvas/public/components/workpad_color_picker/index.ts b/x-pack/plugins/canvas/public/components/workpad_color_picker/index.ts index c6dddab3b5dd1..abd40731078ec 100644 --- a/x-pack/plugins/canvas/public/components/workpad_color_picker/index.ts +++ b/x-pack/plugins/canvas/public/components/workpad_color_picker/index.ts @@ -5,7 +5,6 @@ */ import { connect } from 'react-redux'; -// @ts-ignore import { addColor, removeColor } from '../../state/actions/workpad'; import { getWorkpadColors } from '../../state/selectors/workpad'; diff --git a/x-pack/plugins/canvas/public/components/workpad_config/index.js b/x-pack/plugins/canvas/public/components/workpad_config/index.ts similarity index 63% rename from x-pack/plugins/canvas/public/components/workpad_config/index.js rename to x-pack/plugins/canvas/public/components/workpad_config/index.ts index 913cf7093e726..e417821fd4f67 100644 --- a/x-pack/plugins/canvas/public/components/workpad_config/index.js +++ b/x-pack/plugins/canvas/public/components/workpad_config/index.ts @@ -7,28 +7,29 @@ import { connect } from 'react-redux'; import { get } from 'lodash'; -import { sizeWorkpad, setName, setWorkpadCSS } from '../../state/actions/workpad'; +import { sizeWorkpad as setSize, setName, setWorkpadCSS } from '../../state/actions/workpad'; import { getWorkpad } from '../../state/selectors/workpad'; import { DEFAULT_WORKPAD_CSS } from '../../../common/lib/constants'; import { WorkpadConfig as Component } from './workpad_config'; +import { State } from '../../../types'; -const mapStateToProps = (state) => { +const mapStateToProps = (state: State) => { const workpad = getWorkpad(state); return { - name: get(workpad, 'name'), + name: get(workpad, 'name'), size: { - width: get(workpad, 'width'), - height: get(workpad, 'height'), + width: get(workpad, 'width'), + height: get(workpad, 'height'), }, - css: get(workpad, 'css', DEFAULT_WORKPAD_CSS), + css: get(workpad, 'css', DEFAULT_WORKPAD_CSS), }; }; const mapDispatchToProps = { - setSize: (size) => sizeWorkpad(size), - setName: (name) => setName(name), - setWorkpadCSS: (css) => setWorkpadCSS(css), + setSize, + setName, + setWorkpadCSS, }; export const WorkpadConfig = connect(mapStateToProps, mapDispatchToProps)(Component); diff --git a/x-pack/plugins/canvas/public/components/workpad_config/workpad_config.js b/x-pack/plugins/canvas/public/components/workpad_config/workpad_config.js deleted file mode 100644 index 45758c9965653..0000000000000 --- a/x-pack/plugins/canvas/public/components/workpad_config/workpad_config.js +++ /dev/null @@ -1,169 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { PureComponent } from 'react'; -import PropTypes from 'prop-types'; -import { - EuiFieldText, - EuiFieldNumber, - EuiBadge, - EuiButtonIcon, - EuiFormRow, - EuiFlexGroup, - EuiFlexItem, - EuiSpacer, - EuiTitle, - EuiToolTip, - EuiTextArea, - EuiAccordion, - EuiText, - EuiButton, -} from '@elastic/eui'; -import { DEFAULT_WORKPAD_CSS } from '../../../common/lib/constants'; -import { ComponentStrings } from '../../../i18n'; - -const { WorkpadConfig: strings } = ComponentStrings; - -export class WorkpadConfig extends PureComponent { - static propTypes = { - size: PropTypes.object.isRequired, - name: PropTypes.string.isRequired, - css: PropTypes.string, - setSize: PropTypes.func.isRequired, - setName: PropTypes.func.isRequired, - setWorkpadCSS: PropTypes.func.isRequired, - }; - - state = { - css: this.props.css, - }; - - render() { - const { size, name, setSize, setName, setWorkpadCSS } = this.props; - const { css } = this.state; - const rotate = () => setSize({ width: size.height, height: size.width }); - - const badges = [ - { - name: '1080p', - size: { height: 1080, width: 1920 }, - }, - { - name: '720p', - size: { height: 720, width: 1280 }, - }, - { - name: 'A4', - size: { height: 842, width: 590 }, - }, - { - name: strings.getUSLetterButtonLabel(), - size: { height: 792, width: 612 }, - }, - ]; - - return ( -

-
- -

{strings.getTitle()}

-
-
- - - - - setName(e.target.value)} /> - - - - - - - - setSize({ width: Number(e.target.value), height: size.height })} - value={size.width} - /> - - - - - - - - - - - - setSize({ height: Number(e.target.value), width: size.width })} - value={size.height} - /> - - - - - - -
- {badges.map((badge, i) => ( - setSize(badge.size)} - aria-label={strings.getPageSizeBadgeAriaLabel(badge.name)} - onClickAriaLabel={strings.getPageSizeBadgeOnClickAriaLabel(badge.name)} - > - {badge.name} - - ))} -
- - -
- - - {strings.getGlobalCSSLabel()} - - - } - > -
- this.setState({ css: e.target.value })} - rows={10} - /> - - setWorkpadCSS(css || DEFAULT_WORKPAD_CSS)}> - {strings.getApplyStylesheetButtonLabel()} - - -
-
-
-
- ); - } -} diff --git a/x-pack/plugins/canvas/public/components/workpad_config/workpad_config.tsx b/x-pack/plugins/canvas/public/components/workpad_config/workpad_config.tsx new file mode 100644 index 0000000000000..7b7a1e08b2c5d --- /dev/null +++ b/x-pack/plugins/canvas/public/components/workpad_config/workpad_config.tsx @@ -0,0 +1,175 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { FunctionComponent, useState } from 'react'; +import PropTypes from 'prop-types'; +import { + EuiFieldText, + EuiFieldNumber, + EuiBadge, + EuiButtonIcon, + EuiFormRow, + EuiFlexGroup, + EuiFlexItem, + EuiSpacer, + EuiTitle, + EuiToolTip, + EuiTextArea, + EuiAccordion, + EuiText, + EuiButton, +} from '@elastic/eui'; +import { DEFAULT_WORKPAD_CSS } from '../../../common/lib/constants'; +import { ComponentStrings } from '../../../i18n'; + +const { WorkpadConfig: strings } = ComponentStrings; + +interface Props { + size: { + height: number; + width: number; + }; + name: string; + css?: string; + setSize: ({ height, width }: { height: number; width: number }) => void; + setName: (name: string) => void; + setWorkpadCSS: (css: string) => void; +} + +export const WorkpadConfig: FunctionComponent = (props) => { + const [css, setCSS] = useState(props.css); + const { size, name, setSize, setName, setWorkpadCSS } = props; + const rotate = () => setSize({ width: size.height, height: size.width }); + + const badges = [ + { + name: '1080p', + size: { height: 1080, width: 1920 }, + }, + { + name: '720p', + size: { height: 720, width: 1280 }, + }, + { + name: 'A4', + size: { height: 842, width: 590 }, + }, + { + name: strings.getUSLetterButtonLabel(), + size: { height: 792, width: 612 }, + }, + ]; + + return ( +
+
+ +

{strings.getTitle()}

+
+
+ + + + + setName(e.target.value)} /> + + + + + + + + setSize({ width: Number(e.target.value), height: size.height })} + value={size.width} + /> + + + + + + + + + + + + setSize({ height: Number(e.target.value), width: size.width })} + value={size.height} + /> + + + + + + +
+ {badges.map((badge, i) => ( + setSize(badge.size)} + aria-label={strings.getPageSizeBadgeAriaLabel(badge.name)} + onClickAriaLabel={strings.getPageSizeBadgeOnClickAriaLabel(badge.name)} + > + {badge.name} + + ))} +
+ + +
+ + + {strings.getGlobalCSSLabel()} + + + } + > +
+ setCSS(e.target.value)} + rows={10} + /> + + setWorkpadCSS(css || DEFAULT_WORKPAD_CSS)}> + {strings.getApplyStylesheetButtonLabel()} + + +
+
+
+
+ ); +}; + +WorkpadConfig.propTypes = { + size: PropTypes.object.isRequired, + name: PropTypes.string.isRequired, + css: PropTypes.string, + setSize: PropTypes.func.isRequired, + setName: PropTypes.func.isRequired, + setWorkpadCSS: PropTypes.func.isRequired, +}; diff --git a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/index.ts b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/index.ts index e561607cb101e..0765973915f77 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/index.ts +++ b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/index.ts @@ -14,13 +14,11 @@ import { State, CanvasWorkpadBoundingBox } from '../../../../types'; import { fetchAllRenderables } from '../../../state/actions/elements'; // @ts-ignore Untyped local import { setZoomScale, setFullscreen, selectToplevelNodes } from '../../../state/actions/transient'; -// @ts-ignore Untyped local import { setWriteable, setRefreshInterval, enableAutoplay, setAutoplayInterval, - // @ts-ignore Untyped local } from '../../../state/actions/workpad'; import { getZoomScale, canUserWrite } from '../../../state/selectors/app'; import { @@ -75,7 +73,7 @@ const mapDispatchToProps = (dispatch: Dispatch) => ({ }, doRefresh: () => dispatch(fetchAllRenderables()), setRefreshInterval: (interval: number) => dispatch(setRefreshInterval(interval)), - enableAutoplay: (autoplay: number) => dispatch(enableAutoplay(autoplay)), + enableAutoplay: (autoplay: number) => dispatch(enableAutoplay(!!autoplay)), setAutoplayInterval: (interval: number) => dispatch(setAutoplayInterval(interval)), }); diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/__snapshots__/simple_template.examples.storyshot b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/__snapshots__/simple_template.examples.storyshot index 14466cab1a698..f8583d7cd0dc0 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/__snapshots__/simple_template.examples.storyshot +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/__snapshots__/simple_template.examples.storyshot @@ -169,6 +169,7 @@ exports[`Storyshots arguments/SeriesStyle/components simple: no series 1`] = ` > diff --git a/x-pack/plugins/canvas/public/lib/create_thunk.ts b/x-pack/plugins/canvas/public/lib/create_thunk.ts new file mode 100644 index 0000000000000..cbcaeeccc8b93 --- /dev/null +++ b/x-pack/plugins/canvas/public/lib/create_thunk.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { Dispatch, Action } from 'redux'; +// @ts-ignore untyped dependency +import { createThunk as createThunkFn } from 'redux-thunks/cjs'; +import { State } from '../../types'; + +type CreateThunk = ( + type: string, + fn: ( + params: { type: string; dispatch: Dispatch; getState: () => State }, + ...args: Arguments + ) => void +) => (...args: Arguments) => Action; + +// This declaration exists because redux-thunks is not typed, and has a dependency on +// Canvas State. Therefore, creating a wrapper that strongly-types the function-- and creates +// a single point of replacement, should the need arise-- is a nice workaround. +export const createThunk = createThunkFn as CreateThunk; diff --git a/x-pack/plugins/canvas/public/state/actions/elements.js b/x-pack/plugins/canvas/public/state/actions/elements.js index 47fbc782f90d3..e89e62917da39 100644 --- a/x-pack/plugins/canvas/public/state/actions/elements.js +++ b/x-pack/plugins/canvas/public/state/actions/elements.js @@ -5,10 +5,10 @@ */ import { createAction } from 'redux-actions'; -import { createThunk } from 'redux-thunks/cjs'; import immutable from 'object-path-immutable'; import { get, pick, cloneDeep, without } from 'lodash'; import { toExpression, safeElementFromExpression } from '@kbn/interpreter/common'; +import { createThunk } from '../../lib/create_thunk'; import { getPages, getNodeById, getNodes, getSelectedPageIndex } from '../selectors/workpad'; import { getValue as getResolvedArgsValue } from '../selectors/resolved_args'; import { getDefaultElement } from '../defaults'; diff --git a/x-pack/plugins/canvas/public/state/actions/embeddable.ts b/x-pack/plugins/canvas/public/state/actions/embeddable.ts index e2cf588ec20a9..a153cb7f4354d 100644 --- a/x-pack/plugins/canvas/public/state/actions/embeddable.ts +++ b/x-pack/plugins/canvas/public/state/actions/embeddable.ts @@ -6,8 +6,7 @@ import { Dispatch } from 'redux'; import { createAction } from 'redux-actions'; -// @ts-ignore Untyped -import { createThunk } from 'redux-thunks'; +import { createThunk } from '../../lib/create_thunk'; // @ts-ignore Untyped Local import { fetchRenderable } from './elements'; import { State } from '../../../types'; diff --git a/x-pack/plugins/canvas/public/state/actions/workpad.js b/x-pack/plugins/canvas/public/state/actions/workpad.ts similarity index 54% rename from x-pack/plugins/canvas/public/state/actions/workpad.js rename to x-pack/plugins/canvas/public/state/actions/workpad.ts index 167c156dce998..47df38838f890 100644 --- a/x-pack/plugins/canvas/public/state/actions/workpad.js +++ b/x-pack/plugins/canvas/public/state/actions/workpad.ts @@ -5,26 +5,28 @@ */ import { createAction } from 'redux-actions'; -import { createThunk } from 'redux-thunks/cjs'; import { without, includes } from 'lodash'; +import { createThunk } from '../../lib/create_thunk'; import { getWorkpadColors } from '../selectors/workpad'; +// @ts-ignore import { fetchAllRenderables } from './elements'; +import { CanvasWorkpad } from '../../../types'; -export const sizeWorkpad = createAction('sizeWorkpad'); -export const setName = createAction('setName'); -export const setWriteable = createAction('setWriteable'); -export const setColors = createAction('setColors'); -export const setRefreshInterval = createAction('setRefreshInterval'); -export const setWorkpadCSS = createAction('setWorkpadCSS'); -export const enableAutoplay = createAction('enableAutoplay'); -export const setAutoplayInterval = createAction('setAutoplayInterval'); -export const resetWorkpad = createAction('resetWorkpad'); +export const sizeWorkpad = createAction<{ height: number; width: number }>('sizeWorkpad'); +export const setName = createAction('setName'); +export const setWriteable = createAction('setWriteable'); +export const setColors = createAction('setColors'); +export const setRefreshInterval = createAction('setRefreshInterval'); +export const setWorkpadCSS = createAction('setWorkpadCSS'); +export const enableAutoplay = createAction('enableAutoplay'); +export const setAutoplayInterval = createAction('setAutoplayInterval'); +export const resetWorkpad = createAction('resetWorkpad'); export const initializeWorkpad = createThunk('initializeWorkpad', ({ dispatch }) => { dispatch(fetchAllRenderables()); }); -export const addColor = createThunk('addColor', ({ dispatch, getState }, color) => { +export const addColor = createThunk('addColor', ({ dispatch, getState }, color: string) => { const colors = getWorkpadColors(getState()).slice(0); if (!includes(colors, color)) { colors.push(color); @@ -32,16 +34,20 @@ export const addColor = createThunk('addColor', ({ dispatch, getState }, color) dispatch(setColors(colors)); }); -export const removeColor = createThunk('removeColor', ({ dispatch, getState }, color) => { +export const removeColor = createThunk('removeColor', ({ dispatch, getState }, color: string) => { dispatch(setColors(without(getWorkpadColors(getState()), color))); }); export const setWorkpad = createThunk( 'setWorkpad', - ({ dispatch, type }, workpad, { loadPages = true } = {}) => { + ( + { dispatch, type }, + workpad: CanvasWorkpad, + { loadPages = true }: { loadPages?: boolean } = {} + ) => { dispatch(createAction(type)(workpad)); // set the workpad object in state if (loadPages) { dispatch(initializeWorkpad()); - } // load all the elements on the workpad + } } ); diff --git a/x-pack/plugins/index_management/__jest__/client_integration/helpers/http_requests.ts b/x-pack/plugins/index_management/__jest__/client_integration/helpers/http_requests.ts index da461609f0b83..56d76da522ac2 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/helpers/http_requests.ts +++ b/x-pack/plugins/index_management/__jest__/client_integration/helpers/http_requests.ts @@ -12,7 +12,7 @@ type HttpResponse = Record | any[]; // Register helpers to mock HTTP Requests const registerHttpRequestMockHelpers = (server: SinonFakeServer) => { const setLoadTemplatesResponse = (response: HttpResponse = []) => { - server.respondWith('GET', `${API_BASE_PATH}/index-templates`, [ + server.respondWith('GET', `${API_BASE_PATH}/index_templates`, [ 200, { 'Content-Type': 'application/json' }, JSON.stringify(response), @@ -27,8 +27,16 @@ const registerHttpRequestMockHelpers = (server: SinonFakeServer) => { ]); }; + const setLoadDataStreamsResponse = (response: HttpResponse = []) => { + server.respondWith('GET', `${API_BASE_PATH}/data_streams`, [ + 200, + { 'Content-Type': 'application/json' }, + JSON.stringify(response), + ]); + }; + const setDeleteTemplateResponse = (response: HttpResponse = []) => { - server.respondWith('POST', `${API_BASE_PATH}/delete-index-templates`, [ + server.respondWith('POST', `${API_BASE_PATH}/delete_index_templates`, [ 200, { 'Content-Type': 'application/json' }, JSON.stringify(response), @@ -39,7 +47,7 @@ const registerHttpRequestMockHelpers = (server: SinonFakeServer) => { const status = error ? error.status || 400 : 200; const body = error ? error.body : response; - server.respondWith('GET', `${API_BASE_PATH}/index-templates/:id`, [ + server.respondWith('GET', `${API_BASE_PATH}/index_templates/:id`, [ status, { 'Content-Type': 'application/json' }, JSON.stringify(body), @@ -50,7 +58,7 @@ const registerHttpRequestMockHelpers = (server: SinonFakeServer) => { const status = error ? error.body.status || 400 : 200; const body = error ? JSON.stringify(error.body) : JSON.stringify(response); - server.respondWith('POST', `${API_BASE_PATH}/index-templates`, [ + server.respondWith('POST', `${API_BASE_PATH}/index_templates`, [ status, { 'Content-Type': 'application/json' }, body, @@ -61,7 +69,7 @@ const registerHttpRequestMockHelpers = (server: SinonFakeServer) => { const status = error ? error.status || 400 : 200; const body = error ? JSON.stringify(error.body) : JSON.stringify(response); - server.respondWith('PUT', `${API_BASE_PATH}/index-templates/:name`, [ + server.respondWith('PUT', `${API_BASE_PATH}/index_templates/:name`, [ status, { 'Content-Type': 'application/json' }, body, @@ -71,6 +79,7 @@ const registerHttpRequestMockHelpers = (server: SinonFakeServer) => { return { setLoadTemplatesResponse, setLoadIndicesResponse, + setLoadDataStreamsResponse, setDeleteTemplateResponse, setLoadTemplateResponse, setCreateTemplateResponse, diff --git a/x-pack/plugins/index_management/__jest__/client_integration/helpers/index.ts b/x-pack/plugins/index_management/__jest__/client_integration/helpers/index.ts index 8e7755a65af3c..f581083e28cc6 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/helpers/index.ts +++ b/x-pack/plugins/index_management/__jest__/client_integration/helpers/index.ts @@ -10,44 +10,4 @@ export { nextTick, getRandomString, findTestSubject, TestBed } from '../../../.. export { setupEnvironment, WithAppDependencies, services } from './setup_environment'; -export type TestSubjects = - | 'aliasesTab' - | 'appTitle' - | 'cell' - | 'closeDetailsButton' - | 'createTemplateButton' - | 'createLegacyTemplateButton' - | 'deleteSystemTemplateCallOut' - | 'deleteTemplateButton' - | 'deleteTemplatesConfirmation' - | 'documentationLink' - | 'emptyPrompt' - | 'manageTemplateButton' - | 'mappingsTab' - | 'noAliasesCallout' - | 'noMappingsCallout' - | 'noSettingsCallout' - | 'indicesList' - | 'indicesTab' - | 'indexTableIncludeHiddenIndicesToggle' - | 'indexTableIndexNameLink' - | 'reloadButton' - | 'reloadIndicesButton' - | 'row' - | 'sectionError' - | 'sectionLoading' - | 'settingsTab' - | 'summaryTab' - | 'summaryTitle' - | 'systemTemplatesSwitch' - | 'templateDetails' - | 'templateDetails.manageTemplateButton' - | 'templateDetails.sectionLoading' - | 'templateDetails.tab' - | 'templateDetails.title' - | 'templateList' - | 'templateTable' - | 'templatesTab' - | 'legacyTemplateTable' - | 'viewButton' - | 'filterList.filterItem'; +export { TestSubjects } from './test_subjects'; diff --git a/x-pack/plugins/index_management/__jest__/client_integration/helpers/test_subjects.ts b/x-pack/plugins/index_management/__jest__/client_integration/helpers/test_subjects.ts new file mode 100644 index 0000000000000..4e297118b0fdd --- /dev/null +++ b/x-pack/plugins/index_management/__jest__/client_integration/helpers/test_subjects.ts @@ -0,0 +1,51 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export type TestSubjects = + | 'aliasesTab' + | 'appTitle' + | 'cell' + | 'closeDetailsButton' + | 'createLegacyTemplateButton' + | 'createTemplateButton' + | 'dataStreamsEmptyPromptTemplateLink' + | 'dataStreamTable' + | 'dataStreamTable' + | 'deleteSystemTemplateCallOut' + | 'deleteTemplateButton' + | 'deleteTemplatesConfirmation' + | 'documentationLink' + | 'emptyPrompt' + | 'filterList.filterItem' + | 'indexTable' + | 'indexTableIncludeHiddenIndicesToggle' + | 'indexTableIndexNameLink' + | 'indicesList' + | 'indicesTab' + | 'legacyTemplateTable' + | 'manageTemplateButton' + | 'mappingsTab' + | 'noAliasesCallout' + | 'noMappingsCallout' + | 'noSettingsCallout' + | 'reloadButton' + | 'reloadIndicesButton' + | 'row' + | 'sectionError' + | 'sectionLoading' + | 'settingsTab' + | 'summaryTab' + | 'summaryTitle' + | 'systemTemplatesSwitch' + | 'templateDetails' + | 'templateDetails.manageTemplateButton' + | 'templateDetails.sectionLoading' + | 'templateDetails.tab' + | 'templateDetails.title' + | 'templateList' + | 'templatesTab' + | 'templateTable' + | 'viewButton'; diff --git a/x-pack/plugins/index_management/__jest__/client_integration/home/data_streams_tab.helpers.ts b/x-pack/plugins/index_management/__jest__/client_integration/home/data_streams_tab.helpers.ts new file mode 100644 index 0000000000000..ef6aca44a1754 --- /dev/null +++ b/x-pack/plugins/index_management/__jest__/client_integration/home/data_streams_tab.helpers.ts @@ -0,0 +1,101 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { act } from 'react-dom/test-utils'; + +import { + registerTestBed, + TestBed, + TestBedConfig, + findTestSubject, +} from '../../../../../test_utils'; +import { DataStream } from '../../../common'; +import { IndexManagementHome } from '../../../public/application/sections/home'; // eslint-disable-line @kbn/eslint/no-restricted-paths +import { indexManagementStore } from '../../../public/application/store'; // eslint-disable-line @kbn/eslint/no-restricted-paths +import { WithAppDependencies, services, TestSubjects } from '../helpers'; + +const testBedConfig: TestBedConfig = { + store: () => indexManagementStore(services as any), + memoryRouter: { + initialEntries: [`/indices`], + componentRoutePath: `/:section(indices|data_streams|templates)`, + }, + doMountAsync: true, +}; + +const initTestBed = registerTestBed(WithAppDependencies(IndexManagementHome), testBedConfig); + +export interface DataStreamsTabTestBed extends TestBed { + actions: { + goToDataStreamsList: () => void; + clickEmptyPromptIndexTemplateLink: () => void; + clickReloadButton: () => void; + clickIndicesAt: (index: number) => void; + }; +} + +export const setup = async (): Promise => { + const testBed = await initTestBed(); + + /** + * User Actions + */ + + const goToDataStreamsList = () => { + testBed.find('data_streamsTab').simulate('click'); + }; + + const clickEmptyPromptIndexTemplateLink = async () => { + const { find, component, router } = testBed; + + const templateLink = find('dataStreamsEmptyPromptTemplateLink'); + + await act(async () => { + router.navigateTo(templateLink.props().href!); + }); + + component.update(); + }; + + const clickReloadButton = () => { + const { find } = testBed; + find('reloadButton').simulate('click'); + }; + + const clickIndicesAt = async (index: number) => { + const { component, table, router } = testBed; + const { rows } = table.getMetaData('dataStreamTable'); + const indicesLink = findTestSubject(rows[index].reactWrapper, 'indicesLink'); + + await act(async () => { + router.navigateTo(indicesLink.props().href!); + }); + + component.update(); + }; + + return { + ...testBed, + actions: { + goToDataStreamsList, + clickEmptyPromptIndexTemplateLink, + clickReloadButton, + clickIndicesAt, + }, + }; +}; + +export const createDataStreamPayload = (name: string): DataStream => ({ + name, + timeStampField: '@timestamp', + indices: [ + { + name: 'indexName', + uuid: 'indexId', + }, + ], + generation: 1, +}); diff --git a/x-pack/plugins/index_management/__jest__/client_integration/home/data_streams_tab.test.ts b/x-pack/plugins/index_management/__jest__/client_integration/home/data_streams_tab.test.ts new file mode 100644 index 0000000000000..efe2e2d0c74ae --- /dev/null +++ b/x-pack/plugins/index_management/__jest__/client_integration/home/data_streams_tab.test.ts @@ -0,0 +1,137 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { act } from 'react-dom/test-utils'; + +import { API_BASE_PATH } from '../../../common/constants'; +import { setupEnvironment } from '../helpers'; + +import { DataStreamsTabTestBed, setup, createDataStreamPayload } from './data_streams_tab.helpers'; + +describe('Data Streams tab', () => { + const { server, httpRequestsMockHelpers } = setupEnvironment(); + let testBed: DataStreamsTabTestBed; + + afterAll(() => { + server.restore(); + }); + + beforeEach(async () => { + httpRequestsMockHelpers.setLoadIndicesResponse([ + { + health: '', + status: '', + primary: '', + replica: '', + documents: '', + documents_deleted: '', + size: '', + primary_size: '', + name: 'data-stream-index', + data_stream: 'dataStream1', + }, + { + health: 'green', + status: 'open', + primary: 1, + replica: 1, + documents: 10000, + documents_deleted: 100, + size: '156kb', + primary_size: '156kb', + name: 'non-data-stream-index', + }, + ]); + + await act(async () => { + testBed = await setup(); + }); + }); + + describe('when there are no data streams', () => { + beforeEach(async () => { + const { actions, component } = testBed; + + httpRequestsMockHelpers.setLoadDataStreamsResponse([]); + httpRequestsMockHelpers.setLoadTemplatesResponse({ templates: [], legacyTemplates: [] }); + + await act(async () => { + actions.goToDataStreamsList(); + }); + + component.update(); + }); + + test('displays an empty prompt', async () => { + const { exists } = testBed; + + expect(exists('sectionLoading')).toBe(false); + expect(exists('emptyPrompt')).toBe(true); + }); + + test('goes to index templates tab when "Get started" link is clicked', async () => { + const { actions, exists } = testBed; + + await act(async () => { + actions.clickEmptyPromptIndexTemplateLink(); + }); + + expect(exists('templateList')).toBe(true); + }); + }); + + describe('when there are data streams', () => { + beforeEach(async () => { + const { actions, component } = testBed; + + httpRequestsMockHelpers.setLoadDataStreamsResponse([ + createDataStreamPayload('dataStream1'), + createDataStreamPayload('dataStream2'), + ]); + + await act(async () => { + actions.goToDataStreamsList(); + }); + + component.update(); + }); + + test('lists them in the table', async () => { + const { table } = testBed; + + const { tableCellsValues } = table.getMetaData('dataStreamTable'); + + expect(tableCellsValues).toEqual([ + ['dataStream1', '1', '@timestamp', '1'], + ['dataStream2', '1', '@timestamp', '1'], + ]); + }); + + test('has a button to reload the data streams', async () => { + const { exists, actions } = testBed; + const totalRequests = server.requests.length; + + expect(exists('reloadButton')).toBe(true); + + await act(async () => { + actions.clickReloadButton(); + }); + + expect(server.requests.length).toBe(totalRequests + 1); + expect(server.requests[server.requests.length - 1].url).toBe(`${API_BASE_PATH}/data_streams`); + }); + + test('clicking the indices count navigates to the backing indices', async () => { + const { table, actions } = testBed; + + await actions.clickIndicesAt(0); + + expect(table.getMetaData('indexTable').tableCellsValues).toEqual([ + ['', '', '', '', '', '', '', 'dataStream1'], + ]); + }); + }); +}); diff --git a/x-pack/plugins/index_management/__jest__/client_integration/home/index_templates_tab.test.ts b/x-pack/plugins/index_management/__jest__/client_integration/home/index_templates_tab.test.ts index 8f6a8dddeb195..7c79c7e61174e 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/home/index_templates_tab.test.ts +++ b/x-pack/plugins/index_management/__jest__/client_integration/home/index_templates_tab.test.ts @@ -188,7 +188,7 @@ describe('Index Templates tab', () => { expect(server.requests.length).toBe(totalRequests + 1); expect(server.requests[server.requests.length - 1].url).toBe( - `${API_BASE_PATH}/index-templates` + `${API_BASE_PATH}/index_templates` ); }); @@ -318,7 +318,7 @@ describe('Index Templates tab', () => { const latestRequest = server.requests[server.requests.length - 1]; expect(latestRequest.method).toBe('POST'); - expect(latestRequest.url).toBe(`${API_BASE_PATH}/delete-index-templates`); + expect(latestRequest.url).toBe(`${API_BASE_PATH}/delete_index_templates`); expect(JSON.parse(JSON.parse(latestRequest.requestBody).body)).toEqual({ templates: [{ name: legacyTemplates[0].name, isLegacy }], }); diff --git a/x-pack/plugins/index_management/__jest__/client_integration/home/indices_tab.helpers.ts b/x-pack/plugins/index_management/__jest__/client_integration/home/indices_tab.helpers.ts index e995932dfa00d..f00348aacbf08 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/home/indices_tab.helpers.ts +++ b/x-pack/plugins/index_management/__jest__/client_integration/home/indices_tab.helpers.ts @@ -6,8 +6,13 @@ import { act } from 'react-dom/test-utils'; -import { registerTestBed, TestBed, TestBedConfig } from '../../../../../test_utils'; -import { IndexList } from '../../../public/application/sections/home/index_list'; // eslint-disable-line @kbn/eslint/no-restricted-paths +import { + registerTestBed, + TestBed, + TestBedConfig, + findTestSubject, +} from '../../../../../test_utils'; +import { IndexManagementHome } from '../../../public/application/sections/home'; // eslint-disable-line @kbn/eslint/no-restricted-paths import { indexManagementStore } from '../../../public/application/store'; // eslint-disable-line @kbn/eslint/no-restricted-paths import { WithAppDependencies, services, TestSubjects } from '../helpers'; @@ -15,18 +20,19 @@ const testBedConfig: TestBedConfig = { store: () => indexManagementStore(services as any), memoryRouter: { initialEntries: [`/indices?includeHiddenIndices=true`], - componentRoutePath: `/:section(indices|templates)`, + componentRoutePath: `/:section(indices|data_streams)`, }, doMountAsync: true, }; -const initTestBed = registerTestBed(WithAppDependencies(IndexList), testBedConfig); +const initTestBed = registerTestBed(WithAppDependencies(IndexManagementHome), testBedConfig); export interface IndicesTestBed extends TestBed { actions: { selectIndexDetailsTab: (tab: 'settings' | 'mappings' | 'stats' | 'edit_settings') => void; getIncludeHiddenIndicesToggleStatus: () => boolean; clickIncludeHiddenIndicesToggle: () => void; + clickDataStreamAt: (index: number) => void; }; } @@ -59,12 +65,25 @@ export const setup = async (): Promise => { component.update(); }; + const clickDataStreamAt = async (index: number) => { + const { component, table, router } = testBed; + const { rows } = table.getMetaData('indexTable'); + const dataStreamLink = findTestSubject(rows[index].reactWrapper, 'dataStreamLink'); + + await act(async () => { + router.navigateTo(dataStreamLink.props().href!); + }); + + component.update(); + }; + return { ...testBed, actions: { selectIndexDetailsTab, getIncludeHiddenIndicesToggleStatus, clickIncludeHiddenIndicesToggle, + clickDataStreamAt, }, }; }; diff --git a/x-pack/plugins/index_management/__jest__/client_integration/home/indices_tab.test.ts b/x-pack/plugins/index_management/__jest__/client_integration/home/indices_tab.test.ts index 11c25ffbb590f..c2d955bb4dfce 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/home/indices_tab.test.ts +++ b/x-pack/plugins/index_management/__jest__/client_integration/home/indices_tab.test.ts @@ -9,6 +9,7 @@ import { act } from 'react-dom/test-utils'; import { API_BASE_PATH } from '../../../common/constants'; import { setupEnvironment, nextTick } from '../helpers'; import { IndicesTestBed, setup } from './indices_tab.helpers'; +import { createDataStreamPayload } from './data_streams_tab.helpers'; /** * The below import is required to avoid a console error warn from the "brace" package @@ -52,6 +53,49 @@ describe('', () => { }); }); + describe('data stream column', () => { + beforeEach(async () => { + httpRequestsMockHelpers.setLoadIndicesResponse([ + { + health: '', + status: '', + primary: '', + replica: '', + documents: '', + documents_deleted: '', + size: '', + primary_size: '', + name: 'data-stream-index', + data_stream: 'dataStream1', + }, + ]); + + httpRequestsMockHelpers.setLoadDataStreamsResponse([ + createDataStreamPayload('dataStream1'), + createDataStreamPayload('dataStream2'), + ]); + + testBed = await setup(); + + await act(async () => { + const { component } = testBed; + + await nextTick(); + component.update(); + }); + }); + + test('navigates to the data stream in the Data Streams tab', async () => { + const { table, actions } = testBed; + + await actions.clickDataStreamAt(0); + + expect(table.getMetaData('dataStreamTable').tableCellsValues).toEqual([ + ['dataStream1', '1', '@timestamp', '1'], + ]); + }); + }); + describe('index detail panel with % character in index name', () => { const indexName = 'test%'; beforeEach(async () => { diff --git a/x-pack/plugins/index_management/common/index.ts b/x-pack/plugins/index_management/common/index.ts index 3792e322ae40b..4ad428744deab 100644 --- a/x-pack/plugins/index_management/common/index.ts +++ b/x-pack/plugins/index_management/common/index.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -export { PLUGIN, API_BASE_PATH, CREATE_LEGACY_TEMPLATE_BY_DEFAULT } from './constants'; +export { PLUGIN, API_BASE_PATH, CREATE_LEGACY_TEMPLATE_BY_DEFAULT, BASE_PATH } from './constants'; export { getTemplateParameter } from './lib'; diff --git a/x-pack/plugins/index_management/common/lib/component_template_serialization.test.ts b/x-pack/plugins/index_management/common/lib/component_template_serialization.test.ts new file mode 100644 index 0000000000000..eaa7f24017a2f --- /dev/null +++ b/x-pack/plugins/index_management/common/lib/component_template_serialization.test.ts @@ -0,0 +1,94 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { deserializeComponentTemplate } from './component_template_serialization'; + +describe('deserializeComponentTemplate', () => { + test('deserializes a component template', () => { + expect( + deserializeComponentTemplate( + { + name: 'my_component_template', + component_template: { + version: 1, + _meta: { + serialization: { + id: 10, + class: 'MyComponentTemplate', + }, + description: 'set number of shards to one', + }, + template: { + settings: { + number_of_shards: 1, + }, + mappings: { + _source: { + enabled: false, + }, + properties: { + host_name: { + type: 'keyword', + }, + created_at: { + type: 'date', + format: 'EEE MMM dd HH:mm:ss Z yyyy', + }, + }, + }, + }, + }, + }, + [ + { + name: 'my_index_template', + index_template: { + index_patterns: ['foo'], + template: { + settings: { + number_of_replicas: 2, + }, + }, + composed_of: ['my_component_template'], + }, + }, + ] + ) + ).toEqual({ + name: 'my_component_template', + version: 1, + _meta: { + serialization: { + id: 10, + class: 'MyComponentTemplate', + }, + description: 'set number of shards to one', + }, + template: { + settings: { + number_of_shards: 1, + }, + mappings: { + _source: { + enabled: false, + }, + properties: { + host_name: { + type: 'keyword', + }, + created_at: { + type: 'date', + format: 'EEE MMM dd HH:mm:ss Z yyyy', + }, + }, + }, + }, + _kbnMeta: { + usedBy: ['my_index_template'], + }, + }); + }); +}); diff --git a/x-pack/plugins/index_management/common/lib/component_template_serialization.ts b/x-pack/plugins/index_management/common/lib/component_template_serialization.ts new file mode 100644 index 0000000000000..0db81bf81d300 --- /dev/null +++ b/x-pack/plugins/index_management/common/lib/component_template_serialization.ts @@ -0,0 +1,86 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { + TemplateFromEs, + ComponentTemplateFromEs, + ComponentTemplateDeserialized, + ComponentTemplateListItem, +} from '../types'; + +const hasEntries = (data: object = {}) => Object.entries(data).length > 0; + +/** + * Normalize a list of component templates to a map where each key + * is a component template name, and the value is an array of index templates name using it + * + * @example + * + { + "comp-1": [ + "template-1", + "template-2" + ], + "comp2": [ + "template-1", + "template-2" + ] + } + * + * @param indexTemplatesEs List of component templates + */ + +const getIndexTemplatesToUsedBy = (indexTemplatesEs: TemplateFromEs[]) => { + return indexTemplatesEs.reduce((acc, item) => { + if (item.index_template.composed_of) { + item.index_template.composed_of.forEach((component) => { + acc[component] = acc[component] ? [...acc[component], item.name] : [item.name]; + }); + } + return acc; + }, {} as { [key: string]: string[] }); +}; + +export function deserializeComponentTemplate( + componentTemplateEs: ComponentTemplateFromEs, + indexTemplatesEs: TemplateFromEs[] +) { + const { name, component_template: componentTemplate } = componentTemplateEs; + const { template, _meta, version } = componentTemplate; + + const indexTemplatesToUsedBy = getIndexTemplatesToUsedBy(indexTemplatesEs); + + const deserializedComponentTemplate: ComponentTemplateDeserialized = { + name, + template, + version, + _meta, + _kbnMeta: { + usedBy: indexTemplatesToUsedBy[name] || [], + }, + }; + + return deserializedComponentTemplate; +} + +export function deserializeComponenTemplateList( + componentTemplateEs: ComponentTemplateFromEs, + indexTemplatesEs: TemplateFromEs[] +) { + const { name, component_template: componentTemplate } = componentTemplateEs; + const { template } = componentTemplate; + + const indexTemplatesToUsedBy = getIndexTemplatesToUsedBy(indexTemplatesEs); + + const componentTemplateListItem: ComponentTemplateListItem = { + name, + usedBy: indexTemplatesToUsedBy[name] || [], + hasSettings: hasEntries(template.settings), + hasMappings: hasEntries(template.mappings), + hasAliases: hasEntries(template.aliases), + }; + + return componentTemplateListItem; +} diff --git a/x-pack/plugins/index_management/common/lib/data_stream_serialization.ts b/x-pack/plugins/index_management/common/lib/data_stream_serialization.ts new file mode 100644 index 0000000000000..9d267210a6b31 --- /dev/null +++ b/x-pack/plugins/index_management/common/lib/data_stream_serialization.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DataStream, DataStreamFromEs } from '../types'; + +export function deserializeDataStreamList(dataStreamsFromEs: DataStreamFromEs[]): DataStream[] { + return dataStreamsFromEs.map(({ name, timestamp_field, indices, generation }) => ({ + name, + timeStampField: timestamp_field, + indices: indices.map( + ({ index_name, index_uuid }: { index_name: string; index_uuid: string }) => ({ + name: index_name, + uuid: index_uuid, + }) + ), + generation, + })); +} diff --git a/x-pack/plugins/index_management/common/lib/index.ts b/x-pack/plugins/index_management/common/lib/index.ts index 16eb544c56a08..fce4d8ccc2502 100644 --- a/x-pack/plugins/index_management/common/lib/index.ts +++ b/x-pack/plugins/index_management/common/lib/index.ts @@ -3,6 +3,9 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ + +export { deserializeDataStreamList } from './data_stream_serialization'; + export { deserializeLegacyTemplateList, deserializeTemplateList, @@ -11,3 +14,8 @@ export { } from './template_serialization'; export { getTemplateParameter } from './utils'; + +export { + deserializeComponentTemplate, + deserializeComponenTemplateList, +} from './component_template_serialization'; diff --git a/x-pack/plugins/index_management/common/types/component_templates.ts b/x-pack/plugins/index_management/common/types/component_templates.ts new file mode 100644 index 0000000000000..bc7ebdc2753dd --- /dev/null +++ b/x-pack/plugins/index_management/common/types/component_templates.ts @@ -0,0 +1,39 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { IndexSettings } from './indices'; +import { Aliases } from './aliases'; +import { Mappings } from './mappings'; + +export interface ComponentTemplateSerialized { + template: { + settings?: IndexSettings; + aliases?: Aliases; + mappings?: Mappings; + }; + version?: number; + _meta?: { [key: string]: any }; +} + +export interface ComponentTemplateDeserialized extends ComponentTemplateSerialized { + name: string; + _kbnMeta: { + usedBy: string[]; + }; +} + +export interface ComponentTemplateFromEs { + name: string; + component_template: ComponentTemplateSerialized; +} + +export interface ComponentTemplateListItem { + name: string; + usedBy: string[]; + hasMappings: boolean; + hasAliases: boolean; + hasSettings: boolean; +} diff --git a/x-pack/plugins/index_management/common/types/data_streams.ts b/x-pack/plugins/index_management/common/types/data_streams.ts new file mode 100644 index 0000000000000..5b743296d868b --- /dev/null +++ b/x-pack/plugins/index_management/common/types/data_streams.ts @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export interface DataStreamFromEs { + name: string; + timestamp_field: string; + indices: DataStreamIndexFromEs[]; + generation: number; +} + +export interface DataStreamIndexFromEs { + index_name: string; + index_uuid: string; +} + +export interface DataStream { + name: string; + timeStampField: string; + indices: DataStreamIndex[]; + generation: number; +} + +export interface DataStreamIndex { + name: string; + uuid: string; +} diff --git a/x-pack/plugins/index_management/common/types/index.ts b/x-pack/plugins/index_management/common/types/index.ts index b467f020978a5..c4ba60573d430 100644 --- a/x-pack/plugins/index_management/common/types/index.ts +++ b/x-pack/plugins/index_management/common/types/index.ts @@ -11,3 +11,7 @@ export * from './indices'; export * from './mappings'; export * from './templates'; + +export { DataStreamFromEs, DataStream, DataStreamIndex } from './data_streams'; + +export * from './component_templates'; diff --git a/x-pack/plugins/index_management/common/types/templates.ts b/x-pack/plugins/index_management/common/types/templates.ts index f113aa44d058f..006a2d9dea8f2 100644 --- a/x-pack/plugins/index_management/common/types/templates.ts +++ b/x-pack/plugins/index_management/common/types/templates.ts @@ -49,6 +49,11 @@ export interface TemplateDeserialized { }; } +export interface TemplateFromEs { + name: string; + index_template: TemplateSerialized; +} + /** * Interface for the template list in our UI table * we don't include the mappings, settings and aliases diff --git a/x-pack/plugins/index_management/public/application/app.tsx b/x-pack/plugins/index_management/public/application/app.tsx index 10bbe3ced64da..92197bee30c88 100644 --- a/x-pack/plugins/index_management/public/application/app.tsx +++ b/x-pack/plugins/index_management/public/application/app.tsx @@ -5,10 +5,12 @@ */ import React, { useEffect } from 'react'; + import { Router, Switch, Route, Redirect } from 'react-router-dom'; import { ScopedHistory } from 'kibana/public'; + import { UIM_APP_LOAD } from '../../common/constants'; -import { IndexManagementHome } from './sections/home'; +import { IndexManagementHome, homeSections } from './sections/home'; import { TemplateCreate } from './sections/template_create'; import { TemplateClone } from './sections/template_clone'; import { TemplateEdit } from './sections/template_edit'; @@ -29,10 +31,10 @@ export const App = ({ history }: { history: ScopedHistory }) => { // Export this so we can test it with a different router. export const AppWithoutRouter = () => ( - - - - + + + + ); diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/component_template_list.test.ts b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/component_template_list.test.ts new file mode 100644 index 0000000000000..830cc0ee6a980 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/component_template_list.test.ts @@ -0,0 +1,174 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { act } from 'react-dom/test-utils'; + +import { setupEnvironment, pageHelpers } from './helpers'; +import { ComponentTemplateListTestBed } from './helpers/component_template_list.helpers'; +import { API_BASE_PATH } from '../../../../../../common/constants'; +import { ComponentTemplateListItem } from '../../types'; + +const { setup } = pageHelpers.componentTemplateList; + +jest.mock('ui/i18n', () => { + const I18nContext = ({ children }: any) => children; + return { I18nContext }; +}); + +describe('', () => { + const { server, httpRequestsMockHelpers } = setupEnvironment(); + let testBed: ComponentTemplateListTestBed; + + afterAll(() => { + server.restore(); + }); + + beforeEach(async () => { + await act(async () => { + testBed = await setup(); + }); + + testBed.component.update(); + }); + + describe('With component templates', () => { + const componentTemplate1: ComponentTemplateListItem = { + name: 'test_component_template_1', + hasMappings: true, + hasAliases: true, + hasSettings: true, + usedBy: [], + }; + + const componentTemplate2: ComponentTemplateListItem = { + name: 'test_component_template_2', + hasMappings: true, + hasAliases: true, + hasSettings: true, + usedBy: ['test_index_template_1'], + }; + + const componentTemplates = [componentTemplate1, componentTemplate2]; + + httpRequestsMockHelpers.setLoadComponentTemplatesResponse(componentTemplates); + + test('should render the list view', async () => { + const { table } = testBed; + + // Verify table content + const { tableCellsValues } = table.getMetaData('componentTemplatesTable'); + tableCellsValues.forEach((row, i) => { + const { name, usedBy } = componentTemplates[i]; + const usedByText = usedBy.length === 0 ? 'Not in use' : usedBy.length.toString(); + + expect(row).toEqual(['', name, usedByText, '', '', '', '']); + }); + }); + + test('should reload the component templates data', async () => { + const { component, actions } = testBed; + const totalRequests = server.requests.length; + + await act(async () => { + actions.clickReloadButton(); + }); + + component.update(); + + expect(server.requests.length).toBe(totalRequests + 1); + expect(server.requests[server.requests.length - 1].url).toBe( + `${API_BASE_PATH}/component_templates` + ); + }); + + test('should delete a component template', async () => { + const { actions, component } = testBed; + const { name: componentTemplateName } = componentTemplate1; + + await act(async () => { + actions.clickDeleteActionAt(0); + }); + + // We need to read the document "body" as the modal is added there and not inside + // the component DOM tree. + const modal = document.body.querySelector( + '[data-test-subj="deleteComponentTemplatesConfirmation"]' + ); + const confirmButton: HTMLButtonElement | null = modal!.querySelector( + '[data-test-subj="confirmModalConfirmButton"]' + ); + + expect(modal).not.toBe(null); + expect(modal!.textContent).toContain('Delete component template'); + + httpRequestsMockHelpers.setDeleteComponentTemplateResponse({ + itemsDeleted: [componentTemplateName], + errors: [], + }); + + await act(async () => { + confirmButton!.click(); + }); + + component.update(); + + const deleteRequest = server.requests[server.requests.length - 2]; + + expect(deleteRequest.method).toBe('DELETE'); + expect(deleteRequest.url).toBe( + `${API_BASE_PATH}/component_templates/${componentTemplateName}` + ); + expect(deleteRequest.status).toEqual(200); + }); + }); + + describe('No component templates', () => { + beforeEach(async () => { + httpRequestsMockHelpers.setLoadComponentTemplatesResponse([]); + + await act(async () => { + testBed = await setup(); + }); + + testBed.component.update(); + }); + + test('should display an empty prompt', async () => { + const { exists, find } = testBed; + + expect(exists('sectionLoading')).toBe(false); + expect(exists('emptyList')).toBe(true); + expect(find('emptyList.title').text()).toEqual('Start by creating a component template'); + }); + }); + + describe('Error handling', () => { + beforeEach(async () => { + const error = { + status: 500, + error: 'Internal server error', + message: 'Internal server error', + }; + + httpRequestsMockHelpers.setLoadComponentTemplatesResponse(undefined, { body: error }); + + await act(async () => { + testBed = await setup(); + }); + + testBed.component.update(); + }); + + test('should render an error message if error fetching component templates', async () => { + const { exists, find } = testBed; + + expect(exists('componentTemplatesLoadError')).toBe(true); + expect(find('componentTemplatesLoadError').text()).toContain( + 'Unable to load component templates. Try again.' + ); + }); + }); +}); diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/component_template_list.helpers.ts b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/component_template_list.helpers.ts new file mode 100644 index 0000000000000..8fb4dcff0bcea --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/component_template_list.helpers.ts @@ -0,0 +1,95 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { act } from 'react-dom/test-utils'; + +import { BASE_PATH } from '../../../../../../../common'; +import { + registerTestBed, + TestBed, + TestBedConfig, + findTestSubject, + nextTick, +} from '../../../../../../../../../test_utils'; +import { WithAppDependencies } from './setup_environment'; +import { ComponentTemplateList } from '../../../component_template_list'; + +const testBedConfig: TestBedConfig = { + memoryRouter: { + initialEntries: [`${BASE_PATH}component_templates`], + componentRoutePath: `${BASE_PATH}component_templates`, + }, + doMountAsync: true, +}; + +const initTestBed = registerTestBed(WithAppDependencies(ComponentTemplateList), testBedConfig); + +export type ComponentTemplateListTestBed = TestBed & { + actions: ReturnType; +}; + +const createActions = (testBed: TestBed) => { + const { find } = testBed; + + /** + * User Actions + */ + const clickReloadButton = () => { + find('reloadButton').simulate('click'); + }; + + const clickComponentTemplateAt = async (index: number) => { + const { component, table, router } = testBed; + const { rows } = table.getMetaData('componentTemplatesTable'); + const componentTemplateLink = findTestSubject( + rows[index].reactWrapper, + 'componentTemplateDetailsLink' + ); + + await act(async () => { + const { href } = componentTemplateLink.props(); + router.navigateTo(href!); + await nextTick(); + component.update(); + }); + }; + + const clickDeleteActionAt = (index: number) => { + const { table } = testBed; + + const { rows } = table.getMetaData('componentTemplatesTable'); + const deleteButton = findTestSubject(rows[index].reactWrapper, 'deleteComponentTemplateButton'); + + deleteButton.simulate('click'); + }; + + return { + clickReloadButton, + clickComponentTemplateAt, + clickDeleteActionAt, + }; +}; + +export const setup = async (): Promise => { + const testBed = await initTestBed(); + + return { + ...testBed, + actions: createActions(testBed), + }; +}; + +export type ComponentTemplateTestSubjects = + | 'componentTemplatesTable' + | 'componentTemplateDetails' + | 'componentTemplateDetails.title' + | 'deleteComponentTemplatesConfirmation' + | 'emptyList' + | 'emptyList.title' + | 'sectionLoading' + | 'componentTemplatesLoadError' + | 'deleteComponentTemplateButton' + | 'reloadButton'; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/http_requests.ts b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/http_requests.ts new file mode 100644 index 0000000000000..8473041ee0af3 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/http_requests.ts @@ -0,0 +1,52 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import sinon, { SinonFakeServer } from 'sinon'; +import { API_BASE_PATH } from '../../../../../../../common'; + +// Register helpers to mock HTTP Requests +const registerHttpRequestMockHelpers = (server: SinonFakeServer) => { + const setLoadComponentTemplatesResponse = (response?: any[], error?: any) => { + const status = error ? error.status || 400 : 200; + const body = error ? error.body : response; + + server.respondWith('GET', `${API_BASE_PATH}/component_templates`, [ + status, + { 'Content-Type': 'application/json' }, + JSON.stringify(body), + ]); + }; + + const setDeleteComponentTemplateResponse = (response?: object) => { + server.respondWith('DELETE', `${API_BASE_PATH}/component_templates/:name`, [ + 200, + { 'Content-Type': 'application/json' }, + JSON.stringify(response), + ]); + }; + + return { + setLoadComponentTemplatesResponse, + setDeleteComponentTemplateResponse, + }; +}; + +export const init = () => { + const server = sinon.fakeServer.create(); + server.respondImmediately = true; + + // Define default response for unhandled requests. + // We make requests to APIs which don't impact the component under test, e.g. UI metric telemetry, + // and we can mock them all with a 200 instead of mocking each one individually. + server.respondWith([200, {}, 'DefaultMockedResponse']); + + const httpRequestsMockHelpers = registerHttpRequestMockHelpers(server); + + return { + server, + httpRequestsMockHelpers, + }; +}; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/index.ts b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/index.ts new file mode 100644 index 0000000000000..c1d75b3c2dd9b --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/index.ts @@ -0,0 +1,15 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { setup as componentTemplatesListSetup } from './component_template_list.helpers'; + +export { nextTick, getRandomString, findTestSubject } from '../../../../../../../../../test_utils'; + +export { setupEnvironment } from './setup_environment'; + +export const pageHelpers = { + componentTemplateList: { setup: componentTemplatesListSetup }, +}; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/setup_environment.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/setup_environment.tsx new file mode 100644 index 0000000000000..c0aeb70166b5b --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/setup_environment.tsx @@ -0,0 +1,45 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +/* eslint-disable @kbn/eslint/no-restricted-paths */ +import React from 'react'; +import axios from 'axios'; +import axiosXhrAdapter from 'axios/lib/adapters/xhr'; + +import { HttpSetup } from 'kibana/public'; +import { BASE_PATH, API_BASE_PATH } from '../../../../../../../common/constants'; +import { + notificationServiceMock, + docLinksServiceMock, +} from '../../../../../../../../../../src/core/public/mocks'; + +import { init as initHttpRequests } from './http_requests'; +import { ComponentTemplatesProvider } from '../../../component_templates_context'; + +const mockHttpClient = axios.create({ adapter: axiosXhrAdapter }); + +const appDependencies = { + httpClient: (mockHttpClient as unknown) as HttpSetup, + apiBasePath: API_BASE_PATH, + appBasePath: BASE_PATH, + trackMetric: () => {}, + docLinks: docLinksServiceMock.createStartContract(), + toasts: notificationServiceMock.createSetupContract().toasts, +}; + +export const setupEnvironment = () => { + const { server, httpRequestsMockHelpers } = initHttpRequests(); + + return { + server, + httpRequestsMockHelpers, + }; +}; + +export const WithAppDependencies = (Comp: any) => (props: any) => ( + + + +); diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/component_template_list.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/component_template_list.tsx new file mode 100644 index 0000000000000..41fa608ef538b --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/component_template_list.tsx @@ -0,0 +1,75 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useState, useEffect } from 'react'; +import { FormattedMessage } from '@kbn/i18n/react'; + +import { SectionLoading } from '../shared_imports'; +import { useComponentTemplatesContext } from '../component_templates_context'; +import { UIM_COMPONENT_TEMPLATE_LIST_LOAD } from '../constants'; + +import { EmptyPrompt } from './empty_prompt'; +import { ComponentTable } from './table'; +import { LoadError } from './error'; +import { ComponentTemplatesDeleteModal } from './delete_modal'; + +export const ComponentTemplateList: React.FunctionComponent = () => { + const { api, trackMetric } = useComponentTemplatesContext(); + + const { data, isLoading, error, sendRequest } = api.useLoadComponentTemplates(); + + const [componentTemplatesToDelete, setComponentTemplatesToDelete] = useState([]); + + // Track component loaded + useEffect(() => { + trackMetric('loaded', UIM_COMPONENT_TEMPLATE_LIST_LOAD); + }, [trackMetric]); + + if (data && data.length === 0) { + return ; + } + + let content: React.ReactNode; + + if (isLoading) { + content = ( + + + + ); + } else if (data?.length) { + content = ( + + ); + } else if (error) { + content = ; + } + + return ( +
+ {content} + {componentTemplatesToDelete?.length > 0 ? ( + { + if (deleteResponse?.hasDeletedComponentTemplates) { + // refetch the component templates + sendRequest(); + } + setComponentTemplatesToDelete([]); + }} + componentTemplatesToDelete={componentTemplatesToDelete} + /> + ) : null} +
+ ); +}; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/delete_modal.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/delete_modal.tsx new file mode 100644 index 0000000000000..bf621065842b5 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/delete_modal.tsx @@ -0,0 +1,128 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { EuiConfirmModal, EuiOverlayMask } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; + +import { useComponentTemplatesContext } from '../component_templates_context'; + +export const ComponentTemplatesDeleteModal = ({ + componentTemplatesToDelete, + callback, +}: { + componentTemplatesToDelete: string[]; + callback: (data?: { hasDeletedComponentTemplates: boolean }) => void; +}) => { + const { toasts, api } = useComponentTemplatesContext(); + const numComponentTemplatesToDelete = componentTemplatesToDelete.length; + + const handleDeleteComponentTemplates = () => { + api + .deleteComponentTemplates(componentTemplatesToDelete) + .then(({ data: { itemsDeleted, errors }, error }) => { + const hasDeletedComponentTemplates = itemsDeleted && itemsDeleted.length; + + if (hasDeletedComponentTemplates) { + const successMessage = + itemsDeleted.length === 1 + ? i18n.translate( + 'xpack.idxMgmt.home.componentTemplates.deleteModal.successDeleteSingleNotificationMessageText', + { + defaultMessage: "Deleted component template '{componentTemplateName}'", + values: { componentTemplateName: componentTemplatesToDelete[0] }, + } + ) + : i18n.translate( + 'xpack.idxMgmt.home.componentTemplates.deleteModal.successDeleteMultipleNotificationMessageText', + { + defaultMessage: + 'Deleted {numSuccesses, plural, one {# component template} other {# component templates}}', + values: { numSuccesses: itemsDeleted.length }, + } + ); + + callback({ hasDeletedComponentTemplates }); + toasts.addSuccess(successMessage); + } + + if (error || errors?.length) { + const hasMultipleErrors = + errors?.length > 1 || (error && componentTemplatesToDelete.length > 1); + const errorMessage = hasMultipleErrors + ? i18n.translate( + 'xpack.idxMgmt.home.componentTemplates.deleteModal.multipleErrorsNotificationMessageText', + { + defaultMessage: 'Error deleting {count} component templates', + values: { + count: errors?.length || componentTemplatesToDelete.length, + }, + } + ) + : i18n.translate( + 'xpack.idxMgmt.home.componentTemplates.deleteModal.errorNotificationMessageText', + { + defaultMessage: "Error deleting component template '{name}'", + values: { name: (errors && errors[0].name) || componentTemplatesToDelete[0] }, + } + ); + toasts.addDanger(errorMessage); + } + }); + }; + + const handleOnCancel = () => { + callback(); + }; + + return ( + + + } + onCancel={handleOnCancel} + onConfirm={handleDeleteComponentTemplates} + cancelButtonText={ + + } + confirmButtonText={ + + } + > + <> +

+ +

+ +
    + {componentTemplatesToDelete.map((name) => ( +
  • {name}
  • + ))} +
+ +
+
+ ); +}; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/empty_prompt.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/empty_prompt.tsx new file mode 100644 index 0000000000000..edd9f77cbf635 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/empty_prompt.tsx @@ -0,0 +1,43 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React, { FunctionComponent } from 'react'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { EuiEmptyPrompt, EuiLink } from '@elastic/eui'; + +import { useComponentTemplatesContext } from '../component_templates_context'; + +export const EmptyPrompt: FunctionComponent = () => { + const { documentation } = useComponentTemplatesContext(); + + return ( + + {i18n.translate('xpack.idxMgmt.home.componentTemplates.emptyPromptTitle', { + defaultMessage: 'Start by creating a component template', + })} + + } + body={ +

+ +
+ + {i18n.translate('xpack.idxMgmt.home.componentTemplates.emptyPromptDocumentionLink', { + defaultMessage: 'Learn more', + })} + +

+ } + /> + ); +}; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/error.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/error.tsx new file mode 100644 index 0000000000000..aa37b9ce5767c --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/error.tsx @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React, { FunctionComponent } from 'react'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { EuiLink, EuiCallOut } from '@elastic/eui'; + +export interface Props { + onReloadClick: () => void; +} + +export const LoadError: FunctionComponent = ({ onReloadClick }) => { + return ( + + + + ), + }} + /> + } + /> + ); +}; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout/index.ts b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/index.ts similarity index 79% rename from x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout/index.ts rename to x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/index.ts index 3a25359373aa6..84ee48d14bb8c 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout/index.ts +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/index.ts @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export { CreateAnalyticsFlyout } from './create_analytics_flyout'; +export { ComponentTemplateList } from './component_template_list'; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/table.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/table.tsx new file mode 100644 index 0000000000000..2d9557e64e6e7 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/table.tsx @@ -0,0 +1,205 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React, { FunctionComponent, useState } from 'react'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { + EuiInMemoryTable, + EuiButton, + EuiInMemoryTableProps, + EuiTextColor, + EuiIcon, +} from '@elastic/eui'; + +import { ComponentTemplateListItem } from '../types'; + +export interface Props { + componentTemplates: ComponentTemplateListItem[]; + onReloadClick: () => void; + onDeleteClick: (componentTemplateName: string[]) => void; +} + +export const ComponentTable: FunctionComponent = ({ + componentTemplates, + onReloadClick, + onDeleteClick, +}) => { + const [selection, setSelection] = useState([]); + + const tableProps: EuiInMemoryTableProps = { + itemId: 'name', + isSelectable: true, + 'data-test-subj': 'componentTemplatesTable', + sorting: { sort: { field: 'name', direction: 'asc' } }, + selection: { + onSelectionChange: setSelection, + selectable: ({ usedBy }) => usedBy.length === 0, + selectableMessage: (selectable) => + selectable + ? i18n.translate('xpack.idxMgmt.componentTemplatesList.table.selectionLabel', { + defaultMessage: 'Select this component template', + }) + : i18n.translate('xpack.idxMgmt.componentTemplatesList.table.disabledSelectionLabel', { + defaultMessage: 'Component template is in use and cannot be deleted', + }), + }, + rowProps: () => ({ + 'data-test-subj': 'componentTemplateTableRow', + }), + search: { + toolsLeft: + selection.length > 0 ? ( + onDeleteClick(selection.map(({ name }) => name))} + color="danger" + > + + + ) : undefined, + toolsRight: [ + + {i18n.translate('xpack.idxMgmt.componentTemplatesList.table.reloadButtonLabel', { + defaultMessage: 'Reload', + })} + , + ], + box: { + incremental: true, + }, + filters: [ + { + type: 'field_value_toggle_group', + field: 'usedBy.length', + items: [ + { + value: 1, + name: i18n.translate( + 'xpack.idxMgmt.componentTemplatesList.table.inUseFilterOptionLabel', + { + defaultMessage: 'In use', + } + ), + operator: 'gte', + }, + { + value: 0, + name: i18n.translate( + 'xpack.idxMgmt.componentTemplatesList.table.notInUseFilterOptionLabel', + { + defaultMessage: 'Not in use', + } + ), + operator: 'eq', + }, + ], + }, + ], + }, + pagination: { + initialPageSize: 10, + pageSizeOptions: [10, 20, 50], + }, + columns: [ + { + field: 'name', + name: i18n.translate('xpack.idxMgmt.componentTemplatesList.table.nameColumnTitle', { + defaultMessage: 'Name', + }), + sortable: true, + }, + { + field: 'usedBy', + name: i18n.translate('xpack.idxMgmt.componentTemplatesList.table.isInUseColumnTitle', { + defaultMessage: 'Index templates', + }), + sortable: true, + render: (usedBy: string[]) => { + if (usedBy.length) { + return usedBy.length; + } + + return ( + + + + + + ); + }, + }, + { + field: 'hasMappings', + name: i18n.translate('xpack.idxMgmt.componentTemplatesList.table.mappingsColumnTitle', { + defaultMessage: 'Mappings', + }), + truncateText: true, + sortable: true, + render: (hasMappings: boolean) => (hasMappings ? : null), + }, + { + field: 'hasSettings', + name: i18n.translate('xpack.idxMgmt.componentTemplatesList.table.settingsColumnTitle', { + defaultMessage: 'Settings', + }), + truncateText: true, + sortable: true, + render: (hasSettings: boolean) => (hasSettings ? : null), + }, + { + field: 'hasAliases', + name: i18n.translate('xpack.idxMgmt.componentTemplatesList.table.aliasesColumnTitle', { + defaultMessage: 'Aliases', + }), + truncateText: true, + sortable: true, + render: (hasAliases: boolean) => (hasAliases ? : null), + }, + { + name: ( + + ), + actions: [ + { + 'data-test-subj': 'deleteComponentTemplateButton', + isPrimary: true, + name: i18n.translate('xpack.idxMgmt.componentTemplatesList.table.deleteActionLabel', { + defaultMessage: 'Delete', + }), + description: i18n.translate( + 'xpack.idxMgmt.componentTemplatesList.table.deleteActionDescription', + { defaultMessage: 'Delete this component template' } + ), + type: 'icon', + icon: 'trash', + color: 'danger', + onClick: ({ name }) => onDeleteClick([name]), + enabled: ({ usedBy }) => usedBy.length === 0, + }, + ], + }, + ], + items: componentTemplates ?? [], + }; + + return ; +}; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_templates_context.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_templates_context.tsx new file mode 100644 index 0000000000000..6f5f5bdebd6d0 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_templates_context.tsx @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { createContext, useContext } from 'react'; +import { HttpSetup, DocLinksSetup, NotificationsSetup } from 'src/core/public'; + +import { getApi, getUseRequest, getSendRequest, getDocumentation } from './lib'; + +const ComponentTemplatesContext = createContext(undefined); + +interface Props { + httpClient: HttpSetup; + apiBasePath: string; + appBasePath: string; + trackMetric: (type: 'loaded' | 'click' | 'count', eventName: string) => void; + docLinks: DocLinksSetup; + toasts: NotificationsSetup['toasts']; +} + +interface Context { + api: ReturnType; + documentation: ReturnType; + trackMetric: (type: 'loaded' | 'click' | 'count', eventName: string) => void; + toasts: NotificationsSetup['toasts']; + appBasePath: string; +} + +export const ComponentTemplatesProvider = ({ + children, + value, +}: { + value: Props; + children: React.ReactNode; +}) => { + const { httpClient, apiBasePath, trackMetric, docLinks, toasts, appBasePath } = value; + + const useRequest = getUseRequest(httpClient); + const sendRequest = getSendRequest(httpClient); + + const api = getApi(useRequest, sendRequest, apiBasePath, trackMetric); + const documentation = getDocumentation(docLinks); + + return ( + + {children} + + ); +}; + +export const useComponentTemplatesContext = () => { + const ctx = useContext(ComponentTemplatesContext); + if (!ctx) { + throw new Error( + '"useComponentTemplatesContext" can only be called inside of ComponentTemplatesProvider!' + ); + } + return ctx; +}; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/constants.ts b/x-pack/plugins/index_management/public/application/components/component_templates/constants.ts new file mode 100644 index 0000000000000..3e763119fa9fb --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/component_templates/constants.ts @@ -0,0 +1,10 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +// ui metric constants +export const UIM_COMPONENT_TEMPLATE_LIST_LOAD = 'component_template_list_load'; +export const UIM_COMPONENT_TEMPLATE_DELETE = 'component_template_delete'; +export const UIM_COMPONENT_TEMPLATE_DELETE_MANY = 'component_template_delete_many'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/create_rules_bulk_schema.ts b/x-pack/plugins/index_management/public/application/components/component_templates/index.ts similarity index 59% rename from x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/create_rules_bulk_schema.ts rename to x-pack/plugins/index_management/public/application/components/component_templates/index.ts index bcc4475f2d9f0..e0219ec71787f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/create_rules_bulk_schema.ts +++ b/x-pack/plugins/index_management/public/application/components/component_templates/index.ts @@ -4,8 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import Joi from 'joi'; +export { ComponentTemplatesProvider } from './component_templates_context'; -import { createRulesSchema } from './create_rules_schema'; +export { ComponentTemplateList } from './component_template_list'; -export const createRulesBulkSchema = Joi.array().items(createRulesSchema); +export * from './types'; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/lib/api.ts b/x-pack/plugins/index_management/public/application/components/component_templates/lib/api.ts new file mode 100644 index 0000000000000..351e83c6c0cb5 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/component_templates/lib/api.ts @@ -0,0 +1,44 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ComponentTemplateListItem } from '../types'; +import { UseRequestHook, SendRequestHook } from './request'; +import { UIM_COMPONENT_TEMPLATE_DELETE_MANY, UIM_COMPONENT_TEMPLATE_DELETE } from '../constants'; + +export const getApi = ( + useRequest: UseRequestHook, + sendRequest: SendRequestHook, + apiBasePath: string, + trackMetric: (type: 'loaded' | 'click' | 'count', eventName: string) => void +) => { + function useLoadComponentTemplates() { + return useRequest({ + path: `${apiBasePath}/component_templates`, + method: 'get', + }); + } + + function deleteComponentTemplates(names: string[]) { + const result = sendRequest({ + path: `${apiBasePath}/component_templates/${names + .map((name) => encodeURIComponent(name)) + .join(',')}`, + method: 'delete', + }); + + trackMetric( + 'count', + names.length > 1 ? UIM_COMPONENT_TEMPLATE_DELETE_MANY : UIM_COMPONENT_TEMPLATE_DELETE + ); + + return result; + } + + return { + useLoadComponentTemplates, + deleteComponentTemplates, + }; +}; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/lib/documentation.ts b/x-pack/plugins/index_management/public/application/components/component_templates/lib/documentation.ts new file mode 100644 index 0000000000000..dc27dadf0b807 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/component_templates/lib/documentation.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DocLinksSetup } from 'src/core/public'; + +export const getDocumentation = ({ ELASTIC_WEBSITE_URL, DOC_LINK_VERSION }: DocLinksSetup) => { + const docsBase = `${ELASTIC_WEBSITE_URL}guide/en`; + const esDocsBase = `${docsBase}/elasticsearch/reference/${DOC_LINK_VERSION}`; + + return { + componentTemplates: `${esDocsBase}/indices-component-template.html`, + }; +}; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/lib/index.ts b/x-pack/plugins/index_management/public/application/components/component_templates/lib/index.ts new file mode 100644 index 0000000000000..9a91312f83294 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/component_templates/lib/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; + * you may not use this file except in compliance with the Elastic License. + */ + +export * from './api'; + +export * from './request'; + +export * from './documentation'; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/lib/request.ts b/x-pack/plugins/index_management/public/application/components/component_templates/lib/request.ts new file mode 100644 index 0000000000000..97ffa4d875ecb --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/component_templates/lib/request.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { HttpSetup } from 'src/core/public'; + +import { + UseRequestConfig, + UseRequestResponse, + SendRequestConfig, + SendRequestResponse, + sendRequest as _sendRequest, + useRequest as _useRequest, +} from '../shared_imports'; + +export type UseRequestHook = (config: UseRequestConfig) => UseRequestResponse; +export type SendRequestHook = (config: SendRequestConfig) => Promise; + +export const getUseRequest = (httpClient: HttpSetup): UseRequestHook => ( + config: UseRequestConfig +) => { + return _useRequest(httpClient, config); +}; + +export const getSendRequest = (httpClient: HttpSetup): SendRequestHook => ( + config: SendRequestConfig +) => { + return _sendRequest(httpClient, config); +}; diff --git a/x-pack/plugins/infra/public/routers/index.ts b/x-pack/plugins/index_management/public/application/components/component_templates/shared_imports.ts similarity index 54% rename from x-pack/plugins/infra/public/routers/index.ts rename to x-pack/plugins/index_management/public/application/components/component_templates/shared_imports.ts index 71ab2613d8dc1..863b00b353c49 100644 --- a/x-pack/plugins/infra/public/routers/index.ts +++ b/x-pack/plugins/index_management/public/application/components/component_templates/shared_imports.ts @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { History } from 'history'; -export * from './logs_router'; -export * from './metrics_router'; - -interface RouterProps { - history: History; -} - -export type AppRouter = React.FC; +export { + UseRequestConfig, + UseRequestResponse, + SendRequestConfig, + SendRequestResponse, + sendRequest, + useRequest, + SectionLoading, +} from '../../../../../../../src/plugins/es_ui_shared/public'; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/types.ts b/x-pack/plugins/index_management/public/application/components/component_templates/types.ts new file mode 100644 index 0000000000000..0aab3b6b0a94a --- /dev/null +++ b/x-pack/plugins/index_management/public/application/components/component_templates/types.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +// Ideally, we shouldn't depend on anything in index management that is +// outside of the components_templates directory +// We could consider creating shared types or duplicating the types here if +// the component_templates app were to move outside of index management +import { + ComponentTemplateSerialized, + ComponentTemplateDeserialized, + ComponentTemplateListItem, +} from '../../../../common'; + +export { ComponentTemplateSerialized, ComponentTemplateDeserialized, ComponentTemplateListItem }; diff --git a/x-pack/plugins/index_management/public/application/components/index.ts b/x-pack/plugins/index_management/public/application/components/index.ts index e6d836c0d0501..7ec25ed5583b7 100644 --- a/x-pack/plugins/index_management/public/application/components/index.ts +++ b/x-pack/plugins/index_management/public/application/components/index.ts @@ -11,3 +11,4 @@ export { PageErrorForbidden } from './page_error'; export { TemplateDeleteModal } from './template_delete_modal'; export { TemplateForm } from './template_form'; export * from './mappings_editor'; +export * from './component_templates'; diff --git a/x-pack/plugins/index_management/public/application/index.tsx b/x-pack/plugins/index_management/public/application/index.tsx index 8da556cc81fcc..5d1096c9ee24e 100644 --- a/x-pack/plugins/index_management/public/application/index.tsx +++ b/x-pack/plugins/index_management/public/application/index.tsx @@ -10,9 +10,12 @@ import { render, unmountComponentAtNode } from 'react-dom'; import { CoreStart } from '../../../../../src/core/public'; +import { API_BASE_PATH, BASE_PATH } from '../../common'; + import { AppContextProvider, AppDependencies } from './app_context'; import { App } from './app'; import { indexManagementStore } from './store'; +import { ComponentTemplatesProvider } from './components'; export const renderApp = ( elem: HTMLElement | null, @@ -22,15 +25,26 @@ export const renderApp = ( return () => undefined; } - const { i18n } = core; + const { i18n, docLinks, notifications } = core; const { Context: I18nContext } = i18n; const { services, history } = dependencies; + const componentTemplateProviderValues = { + httpClient: services.httpService.httpClient, + apiBasePath: API_BASE_PATH, + appBasePath: BASE_PATH, + trackMetric: services.uiMetricService.trackMetric.bind(services.uiMetricService), + docLinks, + toasts: notifications.toasts, + }; + render( - + + + , diff --git a/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_detail_panel/data_stream_detail_panel.tsx b/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_detail_panel/data_stream_detail_panel.tsx new file mode 100644 index 0000000000000..a6c8b83a05f98 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_detail_panel/data_stream_detail_panel.tsx @@ -0,0 +1,104 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { Fragment } from 'react'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { + EuiFlyout, + EuiFlyoutHeader, + EuiTitle, + EuiFlyoutBody, + EuiFlyoutFooter, + EuiFlexGroup, + EuiFlexItem, + EuiButtonEmpty, +} from '@elastic/eui'; + +import { SectionLoading, SectionError, Error } from '../../../../components'; +import { useLoadDataStream } from '../../../../services/api'; + +interface Props { + dataStreamName: string; + onClose: () => void; +} + +/** + * NOTE: This currently isn't in use by data_stream_list.tsx because it doesn't contain any + * information that doesn't already exist in the table. We'll use it once we add additional + * info, e.g. storage size, docs count. + */ +export const DataStreamDetailPanel: React.FunctionComponent = ({ + dataStreamName, + onClose, +}) => { + const { error, data: dataStream, isLoading } = useLoadDataStream(dataStreamName); + + let content; + + if (isLoading) { + content = ( + + + + ); + } else if (error) { + content = ( + + } + error={error as Error} + data-test-subj="sectionError" + /> + ); + } else if (dataStream) { + content = {JSON.stringify(dataStream)}; + } + + return ( + + + +

+ {dataStreamName} +

+
+
+ + {content} + + + + + + + + + + +
+ ); +}; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout_wrapper/index.ts b/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_detail_panel/index.ts similarity index 74% rename from x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout_wrapper/index.ts rename to x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_detail_panel/index.ts index c8e7a958f6d42..3f45267c032ed 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout_wrapper/index.ts +++ b/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_detail_panel/index.ts @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export { CreateAnalyticsFlyoutWrapper } from './create_analytics_flyout_wrapper'; +export { DataStreamDetailPanel } from './data_stream_detail_panel'; diff --git a/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_list.tsx b/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_list.tsx new file mode 100644 index 0000000000000..951c4a0d7f3c3 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_list.tsx @@ -0,0 +1,127 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { RouteComponentProps } from 'react-router-dom'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { i18n } from '@kbn/i18n'; +import { EuiTitle, EuiText, EuiSpacer, EuiEmptyPrompt, EuiLink } from '@elastic/eui'; +import { ScopedHistory } from 'kibana/public'; + +import { reactRouterNavigate } from '../../../../shared_imports'; +import { SectionError, SectionLoading, Error } from '../../../components'; +import { useLoadDataStreams } from '../../../services/api'; +import { DataStreamTable } from './data_stream_table'; + +interface MatchParams { + dataStreamName?: string; +} + +export const DataStreamList: React.FunctionComponent> = ({ + match: { + params: { dataStreamName }, + }, + history, +}) => { + const { error, isLoading, data: dataStreams, sendRequest: reload } = useLoadDataStreams(); + + let content; + + if (isLoading) { + content = ( + + + + ); + } else if (error) { + content = ( + + } + error={error as Error} + /> + ); + } else if (Array.isArray(dataStreams) && dataStreams.length === 0) { + content = ( + + + + } + body={ +

+ + {i18n.translate('xpack.idxMgmt.dataStreamList.emptyPrompt.getStartedLink', { + defaultMessage: 'composable index template', + })} + + ), + }} + /> +

+ } + data-test-subj="emptyPrompt" + /> + ); + } else if (Array.isArray(dataStreams) && dataStreams.length > 0) { + content = ( + <> + {/* TODO: Add a switch for toggling on data streams created by Ingest Manager */} + + + + + + + + + + + {/* TODO: Implement this once we have something to put in here, e.g. storage size, docs count */} + {/* dataStreamName && ( + { + history.push('/data_streams'); + }} + /> + )*/} + + ); + } + + return
{content}
; +}; diff --git a/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_table/data_stream_table.tsx b/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_table/data_stream_table.tsx new file mode 100644 index 0000000000000..54b215e561b46 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_table/data_stream_table.tsx @@ -0,0 +1,139 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { EuiInMemoryTable, EuiBasicTableColumn, EuiButton, EuiLink } from '@elastic/eui'; +import { ScopedHistory } from 'kibana/public'; + +import { DataStream } from '../../../../../../common/types'; +import { reactRouterNavigate } from '../../../../../shared_imports'; +import { encodePathForReactRouter } from '../../../../services/routing'; + +interface Props { + dataStreams?: DataStream[]; + reload: () => {}; + history: ScopedHistory; + filters?: string; +} + +export const DataStreamTable: React.FunctionComponent = ({ + dataStreams, + reload, + history, + filters, +}) => { + const columns: Array> = [ + { + field: 'name', + name: i18n.translate('xpack.idxMgmt.dataStreamList.table.nameColumnTitle', { + defaultMessage: 'Name', + }), + truncateText: true, + sortable: true, + // TODO: Render as a link to open the detail panel + }, + { + field: 'indices', + name: i18n.translate('xpack.idxMgmt.dataStreamList.table.indicesColumnTitle', { + defaultMessage: 'Indices', + }), + truncateText: true, + sortable: true, + render: (indices: DataStream['indices'], dataStream) => ( + + {indices.length} + + ), + }, + { + field: 'timeStampField', + name: i18n.translate('xpack.idxMgmt.dataStreamList.table.timeStampFieldColumnTitle', { + defaultMessage: 'Timestamp field', + }), + truncateText: true, + sortable: true, + }, + { + field: 'generation', + name: i18n.translate('xpack.idxMgmt.dataStreamList.table.generationFieldColumnTitle', { + defaultMessage: 'Generation', + }), + truncateText: true, + sortable: true, + }, + ]; + + const pagination = { + initialPageSize: 20, + pageSizeOptions: [10, 20, 50], + }; + + const sorting = { + sort: { + field: 'name', + direction: 'asc', + }, + } as const; + + const searchConfig = { + query: filters, + box: { + incremental: true, + }, + toolsLeft: undefined /* TODO: Actions menu */, + toolsRight: [ + + + , + ], + }; + + return ( + <> + ({ + 'data-test-subj': 'row', + })} + cellProps={() => ({ + 'data-test-subj': 'cell', + })} + data-test-subj="dataStreamTable" + message={ + + } + /> + + ); +}; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/index.ts b/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_table/index.ts similarity index 79% rename from x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/index.ts rename to x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_table/index.ts index 20b96a3668e4b..3922ca5c1d50c 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/index.ts +++ b/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_table/index.ts @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export { CreateAnalyticsForm } from './create_analytics_form'; +export { DataStreamTable } from './data_stream_table'; diff --git a/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/index.ts b/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/index.ts new file mode 100644 index 0000000000000..e2f588cc2a0fb --- /dev/null +++ b/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/index.ts @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ + +export { DataStreamList } from './data_stream_list'; diff --git a/x-pack/plugins/index_management/public/application/sections/home/home.tsx b/x-pack/plugins/index_management/public/application/sections/home/home.tsx index 9d4331d742a25..51deaf42cc72c 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/home.tsx +++ b/x-pack/plugins/index_management/public/application/sections/home/home.tsx @@ -19,11 +19,25 @@ import { EuiTitle, } from '@elastic/eui'; import { documentationService } from '../../services/documentation'; +import { DataStreamList } from './data_stream_list'; import { IndexList } from './index_list'; import { TemplateList } from './template_list'; +import { ComponentTemplateList } from '../../components/component_templates'; import { breadcrumbService } from '../../services/breadcrumbs'; -type Section = 'indices' | 'templates'; +export enum Section { + Indices = 'indices', + DataStreams = 'data_streams', + IndexTemplates = 'templates', + ComponentTemplates = 'component_templates', +} + +export const homeSections = [ + Section.Indices, + Section.DataStreams, + Section.IndexTemplates, + Section.ComponentTemplates, +]; interface MatchParams { section: Section; @@ -37,11 +51,20 @@ export const IndexManagementHome: React.FunctionComponent { const tabs = [ { - id: 'indices' as Section, + id: Section.Indices, name: , }, { - id: 'templates' as Section, + id: Section.DataStreams, + name: ( + + ), + }, + { + id: Section.IndexTemplates, name: ( ), }, + { + id: Section.ComponentTemplates, + name: ( + + ), + }, ]; const onSectionChange = (newSection: Section) => { @@ -106,13 +138,19 @@ export const IndexManagementHome: React.FunctionComponent - - + + + + diff --git a/x-pack/plugins/index_management/public/application/sections/home/index.ts b/x-pack/plugins/index_management/public/application/sections/home/index.ts index 3a29ef4e58555..b53910748aedb 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index.ts +++ b/x-pack/plugins/index_management/public/application/sections/home/index.ts @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export { IndexManagementHome } from './home'; +export { IndexManagementHome, Section, homeSections } from './home'; diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/detail_panel.container.d.ts b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/detail_panel.container.d.ts new file mode 100644 index 0000000000000..6f37b4dc486a7 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/detail_panel.container.d.ts @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ + +export declare function DetailPanel(props: any): any; diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/index.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/index.ts similarity index 100% rename from x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/index.js rename to x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/index.ts diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_list.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_list.tsx similarity index 71% rename from x-pack/plugins/index_management/public/application/sections/home/index_list/index_list.js rename to x-pack/plugins/index_management/public/application/sections/home/index_list/index_list.tsx index df5ca7f837d10..f81221238c536 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_list.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_list.tsx @@ -5,14 +5,16 @@ */ import React from 'react'; +import { RouteComponentProps } from 'react-router-dom'; + import { DetailPanel } from './detail_panel'; import { IndexTable } from './index_table'; -export function IndexList() { +export const IndexList: React.FunctionComponent = ({ history }) => { return (
- +
); -} +}; diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index.ts similarity index 100% rename from x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index.js rename to x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index.ts diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.container.d.ts b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.container.d.ts new file mode 100644 index 0000000000000..35ddfc4813617 --- /dev/null +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.container.d.ts @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ + +export declare function IndexTable(props: any): any; diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.js index f33d486520a29..c3acff087146a 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.js @@ -37,8 +37,10 @@ import { } from '@elastic/eui'; import { UIM_SHOW_DETAILS_CLICK } from '../../../../../../common/constants'; +import { reactRouterNavigate } from '../../../../../shared_imports'; import { REFRESH_RATE_INDEX_LIST } from '../../../../constants'; import { healthToColor } from '../../../../services'; +import { encodePathForReactRouter } from '../../../../services/routing'; import { AppContextConsumer } from '../../../../app_context'; import { renderBadges } from '../../../../lib/render_badges'; import { NoMatch, PageErrorForbidden } from '../../../../components'; @@ -117,6 +119,7 @@ export class IndexTable extends Component { } } } + componentWillUnmount() { clearInterval(this.interval); } @@ -146,11 +149,14 @@ export class IndexTable extends Component { const newIsSortAscending = sortField === column ? !isSortAscending : true; sortChanged(column, newIsSortAscending); }; + renderFilterError() { const { filterError } = this.state; + if (!filterError) { return; } + return ( <> @@ -169,6 +175,7 @@ export class IndexTable extends Component { ); } + onFilterChanged = ({ query, error }) => { if (error) { this.setState({ filterError: error }); @@ -177,6 +184,7 @@ export class IndexTable extends Component { this.setState({ filterError: null }); } }; + getFilters = (extensionsService) => { const { allIndices } = this.props; return extensionsService.filters.reduce((accum, filterExtension) => { @@ -184,6 +192,7 @@ export class IndexTable extends Component { return [...accum, ...filtersToAdd]; }, []); }; + toggleAll = () => { const allSelected = this.areAllItemsSelected(); if (allSelected) { @@ -243,7 +252,8 @@ export class IndexTable extends Component { } buildRowCell(fieldName, value, index, appServices) { - const { openDetailPanel, filterChanged } = this.props; + const { openDetailPanel, filterChanged, history } = this.props; + if (fieldName === 'health') { return {value}; } else if (fieldName === 'name') { @@ -261,7 +271,19 @@ export class IndexTable extends Component { {renderBadges(index, filterChanged, appServices.extensionsService)} ); + } else if (fieldName === 'data_stream') { + return ( + + {value} + + ); } + return value; } @@ -480,12 +502,14 @@ export class IndexTable extends Component { + {(indicesLoading && allIndices.length === 0) || indicesError ? null : ( {extensionsService.toggles.map((toggle) => { return this.renderToggleControl(toggle); })} + + + {this.renderBanners(extensionsService)} + {indicesError && this.renderError()} + {atLeastOneItemSelected ? ( @@ -523,6 +551,7 @@ export class IndexTable extends Component { /> ) : null} + {(indicesLoading && allIndices.length === 0) || indicesError ? null : ( @@ -572,11 +601,14 @@ export class IndexTable extends Component { )} + {this.renderFilterError()} + + {indices.length > 0 ? (
- + + {this.buildHeader()} + {this.buildRows(services)}
) : ( emptyState )} + + {indices.length > 0 ? this.renderPager() : null} ); diff --git a/x-pack/plugins/index_management/public/application/sections/home/template_list/legacy_templates/template_details/template_details.tsx b/x-pack/plugins/index_management/public/application/sections/home/template_list/legacy_templates/template_details/template_details.tsx index ec2956973d4f6..807229fb36267 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/template_list/legacy_templates/template_details/template_details.tsx +++ b/x-pack/plugins/index_management/public/application/sections/home/template_list/legacy_templates/template_details/template_details.tsx @@ -38,7 +38,7 @@ import { Error, } from '../../../../../components'; import { useLoadIndexTemplate } from '../../../../../services/api'; -import { decodePath } from '../../../../../services/routing'; +import { decodePathFromReactRouter } from '../../../../../services/routing'; import { SendRequestResponse } from '../../../../../../shared_imports'; import { useServices } from '../../../../../app_context'; import { TabSummary, TabMappings, TabSettings, TabAliases } from '../../template_details/tabs'; @@ -107,7 +107,7 @@ export const LegacyTemplateDetails: React.FunctionComponent = ({ reload, }) => { const { uiMetricService } = useServices(); - const decodedTemplateName = decodePath(templateName); + const decodedTemplateName = decodePathFromReactRouter(templateName); const { error, data: templateDetails, isLoading } = useLoadIndexTemplate( decodedTemplateName, isLegacy diff --git a/x-pack/plugins/index_management/public/application/sections/home/template_list/legacy_templates/template_table/template_table.tsx b/x-pack/plugins/index_management/public/application/sections/home/template_list/legacy_templates/template_table/template_table.tsx index 92fedd5d68f00..edce05018ce39 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/template_list/legacy_templates/template_table/template_table.tsx +++ b/x-pack/plugins/index_management/public/application/sections/home/template_list/legacy_templates/template_table/template_table.tsx @@ -9,12 +9,12 @@ import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { EuiInMemoryTable, EuiIcon, EuiButton, EuiLink, EuiBasicTableColumn } from '@elastic/eui'; import { ScopedHistory } from 'kibana/public'; -import { reactRouterNavigate } from '../../../../../../../../../../src/plugins/kibana_react/public'; +import { SendRequestResponse, reactRouterNavigate } from '../../../../../../shared_imports'; import { TemplateListItem } from '../../../../../../../common'; import { UIM_TEMPLATE_SHOW_DETAILS_CLICK } from '../../../../../../../common/constants'; import { TemplateDeleteModal } from '../../../../../components'; +import { encodePathForReactRouter } from '../../../../../services/routing'; import { useServices } from '../../../../../app_context'; -import { SendRequestResponse } from '../../../../../../shared_imports'; interface Props { templates: TemplateListItem[]; @@ -52,7 +52,7 @@ export const LegacyTemplateTable: React.FunctionComponent = ({ {...reactRouterNavigate( history, { - pathname: `/templates/${encodeURIComponent(encodeURIComponent(name))}`, + pathname: `/templates/${encodePathForReactRouter(name)}`, search: `legacy=${Boolean(item._kbnMeta.isLegacy)}`, }, () => uiMetricService.trackMetric('click', UIM_TEMPLATE_SHOW_DETAILS_CLICK) diff --git a/x-pack/plugins/index_management/public/application/sections/template_clone/template_clone.tsx b/x-pack/plugins/index_management/public/application/sections/template_clone/template_clone.tsx index 8bdd230f89952..82835c56a3877 100644 --- a/x-pack/plugins/index_management/public/application/sections/template_clone/template_clone.tsx +++ b/x-pack/plugins/index_management/public/application/sections/template_clone/template_clone.tsx @@ -11,7 +11,7 @@ import { EuiPageBody, EuiPageContent, EuiSpacer, EuiTitle } from '@elastic/eui'; import { TemplateDeserialized } from '../../../../common'; import { TemplateForm, SectionLoading, SectionError, Error } from '../../components'; import { breadcrumbService } from '../../services/breadcrumbs'; -import { decodePath, getTemplateDetailsLink } from '../../services/routing'; +import { decodePathFromReactRouter, getTemplateDetailsLink } from '../../services/routing'; import { saveTemplate, useLoadIndexTemplate } from '../../services/api'; import { getIsLegacyFromQueryParams } from '../../lib/index_templates'; @@ -26,7 +26,7 @@ export const TemplateClone: React.FunctionComponent { - const decodedTemplateName = decodePath(name); + const decodedTemplateName = decodePathFromReactRouter(name); const isLegacy = getIsLegacyFromQueryParams(location); const [isSaving, setIsSaving] = useState(false); diff --git a/x-pack/plugins/index_management/public/application/sections/template_edit/template_edit.tsx b/x-pack/plugins/index_management/public/application/sections/template_edit/template_edit.tsx index d3e539989bc96..7cacb5ee97a60 100644 --- a/x-pack/plugins/index_management/public/application/sections/template_edit/template_edit.tsx +++ b/x-pack/plugins/index_management/public/application/sections/template_edit/template_edit.tsx @@ -11,7 +11,7 @@ import { EuiPageBody, EuiPageContent, EuiTitle, EuiSpacer, EuiCallOut } from '@e import { TemplateDeserialized } from '../../../../common'; import { breadcrumbService } from '../../services/breadcrumbs'; import { useLoadIndexTemplate, updateTemplate } from '../../services/api'; -import { decodePath, getTemplateDetailsLink } from '../../services/routing'; +import { decodePathFromReactRouter, getTemplateDetailsLink } from '../../services/routing'; import { SectionLoading, SectionError, TemplateForm, Error } from '../../components'; import { getIsLegacyFromQueryParams } from '../../lib/index_templates'; @@ -26,7 +26,7 @@ export const TemplateEdit: React.FunctionComponent { - const decodedTemplateName = decodePath(name); + const decodedTemplateName = decodePathFromReactRouter(name); const isLegacy = getIsLegacyFromQueryParams(location); const [isSaving, setIsSaving] = useState(false); diff --git a/x-pack/plugins/index_management/public/application/services/api.ts b/x-pack/plugins/index_management/public/application/services/api.ts index 3961942b83ea3..5ad84395d24c2 100644 --- a/x-pack/plugins/index_management/public/application/services/api.ts +++ b/x-pack/plugins/index_management/public/application/services/api.ts @@ -31,14 +31,12 @@ import { UIM_TEMPLATE_UPDATE, UIM_TEMPLATE_CLONE, } from '../../../common/constants'; - +import { TemplateDeserialized, TemplateListItem, DataStream } from '../../../common'; +import { IndexMgmtMetricsType } from '../../types'; import { TAB_SETTINGS, TAB_MAPPING, TAB_STATS } from '../constants'; - import { useRequest, sendRequest } from './use_request'; import { httpService } from './http'; import { UiMetricService } from './ui_metric'; -import { TemplateDeserialized, TemplateListItem } from '../../../common'; -import { IndexMgmtMetricsType } from '../../types'; // Temporary hack to provide the uiMetricService instance to this file. // TODO: Refactor and export an ApiService instance through the app dependencies context @@ -48,6 +46,21 @@ export const setUiMetricService = (_uiMetricService: UiMetricService({ + path: `${API_BASE_PATH}/data_streams`, + method: 'get', + }); +} + +// TODO: Implement this API endpoint once we have content to surface in the detail panel. +export function useLoadDataStream(name: string) { + return useRequest({ + path: `${API_BASE_PATH}/data_stream/${encodeURIComponent(name)}`, + method: 'get', + }); +} + export async function loadIndices() { const response = await httpService.httpClient.get(`${API_BASE_PATH}/indices`); return response.data ? response.data : response; @@ -211,14 +224,14 @@ export async function loadIndexData(type: string, indexName: string) { export function useLoadIndexTemplates() { return useRequest<{ templates: TemplateListItem[]; legacyTemplates: TemplateListItem[] }>({ - path: `${API_BASE_PATH}/index-templates`, + path: `${API_BASE_PATH}/index_templates`, method: 'get', }); } export async function deleteTemplates(templates: Array<{ name: string; isLegacy?: boolean }>) { const result = sendRequest({ - path: `${API_BASE_PATH}/delete-index-templates`, + path: `${API_BASE_PATH}/delete_index_templates`, method: 'post', body: { templates }, }); @@ -232,7 +245,7 @@ export async function deleteTemplates(templates: Array<{ name: string; isLegacy? export function useLoadIndexTemplate(name: TemplateDeserialized['name'], isLegacy?: boolean) { return useRequest({ - path: `${API_BASE_PATH}/index-templates/${encodeURIComponent(name)}`, + path: `${API_BASE_PATH}/index_templates/${encodeURIComponent(name)}`, method: 'get', query: { legacy: isLegacy, @@ -242,7 +255,7 @@ export function useLoadIndexTemplate(name: TemplateDeserialized['name'], isLegac export async function saveTemplate(template: TemplateDeserialized, isClone?: boolean) { const result = await sendRequest({ - path: `${API_BASE_PATH}/index-templates`, + path: `${API_BASE_PATH}/index_templates`, method: 'post', body: JSON.stringify(template), }); @@ -257,7 +270,7 @@ export async function saveTemplate(template: TemplateDeserialized, isClone?: boo export async function updateTemplate(template: TemplateDeserialized) { const { name } = template; const result = await sendRequest({ - path: `${API_BASE_PATH}/index-templates/${encodeURIComponent(name)}`, + path: `${API_BASE_PATH}/index_templates/${encodeURIComponent(name)}`, method: 'put', body: JSON.stringify(template), }); diff --git a/x-pack/plugins/index_management/public/application/services/routing.ts b/x-pack/plugins/index_management/public/application/services/routing.ts index a999c58f5bb42..2a895196189d0 100644 --- a/x-pack/plugins/index_management/public/application/services/routing.ts +++ b/x-pack/plugins/index_management/public/application/services/routing.ts @@ -6,10 +6,8 @@ export const getTemplateListLink = () => `/templates`; -// Need to add some additonal encoding/decoding logic to work with React Router -// For background, see: https://github.com/ReactTraining/history/issues/505 export const getTemplateDetailsLink = (name: string, isLegacy?: boolean, withHash = false) => { - const baseUrl = `/templates/${encodeURIComponent(encodeURIComponent(name))}`; + const baseUrl = `/templates/${encodePathForReactRouter(name)}`; let url = withHash ? `#${baseUrl}` : baseUrl; if (isLegacy) { url = `${url}?legacy=${isLegacy}`; @@ -18,18 +16,14 @@ export const getTemplateDetailsLink = (name: string, isLegacy?: boolean, withHas }; export const getTemplateEditLink = (name: string, isLegacy?: boolean) => { - return encodeURI( - `/edit_template/${encodeURIComponent(encodeURIComponent(name))}?legacy=${isLegacy === true}` - ); + return encodeURI(`/edit_template/${encodePathForReactRouter(name)}?legacy=${isLegacy === true}`); }; export const getTemplateCloneLink = (name: string, isLegacy?: boolean) => { - return encodeURI( - `/clone_template/${encodeURIComponent(encodeURIComponent(name))}?legacy=${isLegacy === true}` - ); + return encodeURI(`/clone_template/${encodePathForReactRouter(name)}?legacy=${isLegacy === true}`); }; -export const decodePath = (pathname: string): string => { +export const decodePathFromReactRouter = (pathname: string): string => { let decodedPath; try { decodedPath = decodeURI(pathname); @@ -39,3 +33,8 @@ export const decodePath = (pathname: string): string => { } return decodeURIComponent(decodedPath); }; + +// Need to add some additonal encoding/decoding logic to work with React Router +// For background, see: https://github.com/ReactTraining/history/issues/505 +export const encodePathForReactRouter = (pathname: string): string => + encodeURIComponent(encodeURIComponent(pathname)); diff --git a/x-pack/plugins/index_management/public/shared_imports.ts b/x-pack/plugins/index_management/public/shared_imports.ts index 8942367261511..afd5a5cf650e1 100644 --- a/x-pack/plugins/index_management/public/shared_imports.ts +++ b/x-pack/plugins/index_management/public/shared_imports.ts @@ -31,3 +31,5 @@ export { export { getFormRow, Field } from '../../../../src/plugins/es_ui_shared/static/forms/components'; export { isJSON } from '../../../../src/plugins/es_ui_shared/static/validators/string'; + +export { reactRouterNavigate } from '../../../../src/plugins/kibana_react/public'; diff --git a/x-pack/plugins/index_management/server/client/elasticsearch.ts b/x-pack/plugins/index_management/server/client/elasticsearch.ts index 65bd5411a249b..6b1bf47512b21 100644 --- a/x-pack/plugins/index_management/server/client/elasticsearch.ts +++ b/x-pack/plugins/index_management/server/client/elasticsearch.ts @@ -10,6 +10,47 @@ export const elasticsearchJsPlugin = (Client: any, config: any, components: any) Client.prototype.dataManagement = components.clientAction.namespaceFactory(); const dataManagement = Client.prototype.dataManagement.prototype; + // Data streams + dataManagement.getDataStreams = ca({ + urls: [ + { + fmt: '/_data_stream', + }, + ], + method: 'GET', + }); + + // We don't allow the user to create a data stream in the UI or API. We're just adding this here + // to enable the API integration tests. + dataManagement.createDataStream = ca({ + urls: [ + { + fmt: '/_data_stream/<%=name%>', + req: { + name: { + type: 'string', + }, + }, + }, + ], + method: 'PUT', + }); + + dataManagement.deleteDataStream = ca({ + urls: [ + { + fmt: '/_data_stream/<%=name%>', + req: { + name: { + type: 'string', + }, + }, + }, + ], + method: 'DELETE', + }); + + // Component templates dataManagement.getComponentTemplates = ca({ urls: [ { @@ -60,4 +101,43 @@ export const elasticsearchJsPlugin = (Client: any, config: any, components: any) ], method: 'DELETE', }); + + // Composable index templates + dataManagement.getComposableIndexTemplates = ca({ + urls: [ + { + fmt: '/_index_template', + }, + ], + method: 'GET', + }); + + dataManagement.saveComposableIndexTemplate = ca({ + urls: [ + { + fmt: '/_index_template/<%=name%>', + req: { + name: { + type: 'string', + }, + }, + }, + ], + needBody: true, + method: 'PUT', + }); + + dataManagement.deleteComposableIndexTemplate = ca({ + urls: [ + { + fmt: '/_index_template/<%=name%>', + req: { + name: { + type: 'string', + }, + }, + }, + ], + method: 'DELETE', + }); }; diff --git a/x-pack/plugins/index_management/server/routes/api/component_templates/get.ts b/x-pack/plugins/index_management/server/routes/api/component_templates/get.ts index 87aa64421624e..f6f8e7d63d370 100644 --- a/x-pack/plugins/index_management/server/routes/api/component_templates/get.ts +++ b/x-pack/plugins/index_management/server/routes/api/component_templates/get.ts @@ -5,6 +5,11 @@ */ import { schema } from '@kbn/config-schema'; +import { + deserializeComponentTemplate, + deserializeComponenTemplateList, +} from '../../../../common/lib'; +import { ComponentTemplateFromEs } from '../../../../common'; import { RouteDependencies } from '../../../types'; import { addBasePath } from '../index'; @@ -20,9 +25,25 @@ export function registerGetAllRoute({ router, license, lib: { isEsError } }: Rou const { callAsCurrentUser } = ctx.dataManagement!.client; try { - const response = await callAsCurrentUser('dataManagement.getComponentTemplates'); + const { + component_templates: componentTemplates, + }: { component_templates: ComponentTemplateFromEs[] } = await callAsCurrentUser( + 'dataManagement.getComponentTemplates' + ); + + const { index_templates: indexTemplates } = await callAsCurrentUser( + 'dataManagement.getComposableIndexTemplates' + ); + + const body = componentTemplates.map((componentTemplate) => { + const deserializedComponentTemplateListItem = deserializeComponenTemplateList( + componentTemplate, + indexTemplates + ); + return deserializedComponentTemplateListItem; + }); - return res.ok({ body: response.component_templates }); + return res.ok({ body }); } catch (error) { if (isEsError(error)) { return res.customError({ @@ -56,11 +77,12 @@ export function registerGetAllRoute({ router, license, lib: { isEsError } }: Rou } ); + const { index_templates: indexTemplates } = await callAsCurrentUser( + 'dataManagement.getComposableIndexTemplates' + ); + return res.ok({ - body: { - ...componentTemplates[0], - name, - }, + body: deserializeComponentTemplate(componentTemplates[0], indexTemplates), }); } catch (error) { if (isEsError(error)) { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/update_rules_bulk_schema.ts b/x-pack/plugins/index_management/server/routes/api/data_streams/index.ts similarity index 51% rename from x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/update_rules_bulk_schema.ts rename to x-pack/plugins/index_management/server/routes/api/data_streams/index.ts index 123ec2d5b7e15..56c514e30f242 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/update_rules_bulk_schema.ts +++ b/x-pack/plugins/index_management/server/routes/api/data_streams/index.ts @@ -4,8 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -import Joi from 'joi'; +import { RouteDependencies } from '../../../types'; -import { updateRulesSchema } from './update_rules_schema'; +import { registerGetAllRoute } from './register_get_route'; -export const updateRulesBulkSchema = Joi.array().items(updateRulesSchema); +export function registerDataStreamRoutes(dependencies: RouteDependencies) { + registerGetAllRoute(dependencies); +} diff --git a/x-pack/plugins/index_management/server/routes/api/data_streams/register_get_route.ts b/x-pack/plugins/index_management/server/routes/api/data_streams/register_get_route.ts new file mode 100644 index 0000000000000..9128556130bf4 --- /dev/null +++ b/x-pack/plugins/index_management/server/routes/api/data_streams/register_get_route.ts @@ -0,0 +1,34 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { deserializeDataStreamList } from '../../../../common/lib'; +import { RouteDependencies } from '../../../types'; +import { addBasePath } from '../index'; + +export function registerGetAllRoute({ router, license, lib: { isEsError } }: RouteDependencies) { + router.get( + { path: addBasePath('/data_streams'), validate: false }, + license.guardApiRoute(async (ctx, req, res) => { + const { callAsCurrentUser } = ctx.dataManagement!.client; + + try { + const dataStreams = await callAsCurrentUser('dataManagement.getDataStreams'); + const body = deserializeDataStreamList(dataStreams); + + return res.ok({ body }); + } catch (error) { + if (isEsError(error)) { + return res.customError({ + statusCode: error.statusCode, + body: error, + }); + } + + return res.internalError({ body: error }); + } + }) + ); +} diff --git a/x-pack/plugins/index_management/server/routes/api/templates/register_create_route.ts b/x-pack/plugins/index_management/server/routes/api/templates/register_create_route.ts index 26e74847e3e05..e0d92b3800785 100644 --- a/x-pack/plugins/index_management/server/routes/api/templates/register_create_route.ts +++ b/x-pack/plugins/index_management/server/routes/api/templates/register_create_route.ts @@ -16,7 +16,7 @@ const bodySchema = templateSchema; export function registerCreateRoute({ router, license, lib }: RouteDependencies) { router.post( - { path: addBasePath('/index-templates'), validate: { body: bodySchema } }, + { path: addBasePath('/index_templates'), validate: { body: bodySchema } }, license.guardApiRoute(async (ctx, req, res) => { const { callAsCurrentUser } = ctx.core.elasticsearch.legacy.client; const template = req.body as TemplateDeserialized; diff --git a/x-pack/plugins/index_management/server/routes/api/templates/register_delete_route.ts b/x-pack/plugins/index_management/server/routes/api/templates/register_delete_route.ts index b5cc00ad6d8cc..1527af12a92a4 100644 --- a/x-pack/plugins/index_management/server/routes/api/templates/register_delete_route.ts +++ b/x-pack/plugins/index_management/server/routes/api/templates/register_delete_route.ts @@ -24,7 +24,7 @@ const bodySchema = schema.object({ export function registerDeleteRoute({ router, license }: RouteDependencies) { router.post( { - path: addBasePath('/delete-index-templates'), + path: addBasePath('/delete_index_templates'), validate: { body: bodySchema }, }, license.guardApiRoute(async (ctx, req, res) => { diff --git a/x-pack/plugins/index_management/server/routes/api/templates/register_get_routes.ts b/x-pack/plugins/index_management/server/routes/api/templates/register_get_routes.ts index 12ec005258a62..ae5f7802a8408 100644 --- a/x-pack/plugins/index_management/server/routes/api/templates/register_get_routes.ts +++ b/x-pack/plugins/index_management/server/routes/api/templates/register_get_routes.ts @@ -16,7 +16,7 @@ import { addBasePath } from '../index'; export function registerGetAllRoute({ router, license }: RouteDependencies) { router.get( - { path: addBasePath('/index-templates'), validate: false }, + { path: addBasePath('/index_templates'), validate: false }, license.guardApiRoute(async (ctx, req, res) => { const { callAsCurrentUser } = ctx.core.elasticsearch.legacy.client; const managedTemplatePrefix = await getManagedTemplatePrefix(callAsCurrentUser); @@ -55,7 +55,7 @@ const querySchema = schema.object({ export function registerGetOneRoute({ router, license, lib }: RouteDependencies) { router.get( { - path: addBasePath('/index-templates/{name}'), + path: addBasePath('/index_templates/{name}'), validate: { params: paramsSchema, query: querySchema }, }, license.guardApiRoute(async (ctx, req, res) => { diff --git a/x-pack/plugins/index_management/server/routes/api/templates/register_update_route.ts b/x-pack/plugins/index_management/server/routes/api/templates/register_update_route.ts index 5b2a0d8722e46..7e9c3174d0591 100644 --- a/x-pack/plugins/index_management/server/routes/api/templates/register_update_route.ts +++ b/x-pack/plugins/index_management/server/routes/api/templates/register_update_route.ts @@ -19,7 +19,7 @@ const paramsSchema = schema.object({ export function registerUpdateRoute({ router, license, lib }: RouteDependencies) { router.put( { - path: addBasePath('/index-templates/{name}'), + path: addBasePath('/index_templates/{name}'), validate: { body: bodySchema, params: paramsSchema }, }, license.guardApiRoute(async (ctx, req, res) => { diff --git a/x-pack/plugins/index_management/server/routes/index.ts b/x-pack/plugins/index_management/server/routes/index.ts index 1e5aaf8087624..202e6919f7b13 100644 --- a/x-pack/plugins/index_management/server/routes/index.ts +++ b/x-pack/plugins/index_management/server/routes/index.ts @@ -6,6 +6,7 @@ import { RouteDependencies } from '../types'; +import { registerDataStreamRoutes } from './api/data_streams'; import { registerIndicesRoutes } from './api/indices'; import { registerTemplateRoutes } from './api/templates'; import { registerMappingRoute } from './api/mapping'; @@ -15,6 +16,7 @@ import { registerComponentTemplateRoutes } from './api/component_templates'; export class ApiRoutes { setup(dependencies: RouteDependencies) { + registerDataStreamRoutes(dependencies); registerIndicesRoutes(dependencies); registerTemplateRoutes(dependencies); registerSettingsRoutes(dependencies); diff --git a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression.tsx b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression.tsx index 7a71bb68bc54f..d5d61733e8717 100644 --- a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression.tsx +++ b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression.tsx @@ -384,3 +384,7 @@ export const Expressions: React.FC = (props) => { ); }; + +// required for dynamic import +// eslint-disable-next-line import/no-default-export +export default Expressions; diff --git a/x-pack/plugins/infra/public/alerting/metric_threshold/components/validation.tsx b/x-pack/plugins/infra/public/alerting/metric_threshold/components/validation.tsx index 2d9524ca158c8..da342f0a45420 100644 --- a/x-pack/plugins/infra/public/alerting/metric_threshold/components/validation.tsx +++ b/x-pack/plugins/infra/public/alerting/metric_threshold/components/validation.tsx @@ -5,7 +5,6 @@ */ import { i18n } from '@kbn/i18n'; -import { isNumber } from 'lodash'; import { MetricExpressionParams, Comparator, @@ -106,3 +105,5 @@ export function validateMetricThreshold({ return validationResult; } + +const isNumber = (value: unknown): value is number => typeof value === 'number'; diff --git a/x-pack/plugins/infra/public/alerting/metric_threshold/index.ts b/x-pack/plugins/infra/public/alerting/metric_threshold/index.ts index a40cb1eaec50c..6a999a86c99d1 100644 --- a/x-pack/plugins/infra/public/alerting/metric_threshold/index.ts +++ b/x-pack/plugins/infra/public/alerting/metric_threshold/index.ts @@ -4,9 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ import { i18n } from '@kbn/i18n'; +import React from 'react'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { AlertTypeModel } from '../../../../triggers_actions_ui/public/types'; -import { Expressions } from './components/expression'; import { validateMetricThreshold } from './components/validation'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { METRIC_THRESHOLD_ALERT_TYPE_ID } from '../../../server/lib/alerting/metric_threshold/types'; @@ -18,7 +18,7 @@ export function createMetricThresholdAlertType(): AlertTypeModel { defaultMessage: 'Metric threshold', }), iconClass: 'bell', - alertParamsExpression: Expressions, + alertParamsExpression: React.lazy(() => import('./components/expression')), validate: validateMetricThreshold, defaultActionMessage: i18n.translate( 'xpack.infra.metrics.alerting.threshold.defaultActionMessage', diff --git a/x-pack/plugins/infra/public/apps/common_providers.tsx b/x-pack/plugins/infra/public/apps/common_providers.tsx new file mode 100644 index 0000000000000..facb0f1539a10 --- /dev/null +++ b/x-pack/plugins/infra/public/apps/common_providers.tsx @@ -0,0 +1,47 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { CoreStart } from 'kibana/public'; +import { ApolloClient } from 'apollo-client'; +import { + useUiSetting$, + KibanaContextProvider, +} from '../../../../../src/plugins/kibana_react/public'; +import { TriggersActionsProvider } from '../utils/triggers_actions_context'; +import { ClientPluginDeps } from '../types'; +import { TriggersAndActionsUIPublicPluginStart } from '../../../triggers_actions_ui/public'; +import { ApolloClientContext } from '../utils/apollo_context'; +import { EuiThemeProvider } from '../../../observability/public'; +import { NavigationWarningPromptProvider } from '../utils/navigation_warning_prompt'; + +export const CommonInfraProviders: React.FC<{ + apolloClient: ApolloClient<{}>; + triggersActionsUI: TriggersAndActionsUIPublicPluginStart; +}> = ({ apolloClient, children, triggersActionsUI }) => { + const [darkMode] = useUiSetting$('theme:darkMode'); + + return ( + + + + {children} + + + + ); +}; + +export const CoreProviders: React.FC<{ + core: CoreStart; + plugins: ClientPluginDeps; +}> = ({ children, core, plugins }) => { + return ( + + {children} + + ); +}; diff --git a/x-pack/plugins/infra/public/apps/common_styles.ts b/x-pack/plugins/infra/public/apps/common_styles.ts new file mode 100644 index 0000000000000..546b83a69035c --- /dev/null +++ b/x-pack/plugins/infra/public/apps/common_styles.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; + * you may not use this file except in compliance with the Elastic License. + */ + +export const CONTAINER_CLASSNAME = 'infra-container-element'; + +export const prepareMountElement = (element: HTMLElement) => { + // Ensure the element we're handed from application mounting is assigned a class + // for our index.scss styles to apply to. + element.classList.add(CONTAINER_CLASSNAME); +}; diff --git a/x-pack/plugins/infra/public/apps/legacy_app.tsx b/x-pack/plugins/infra/public/apps/legacy_app.tsx new file mode 100644 index 0000000000000..195f252c6b60f --- /dev/null +++ b/x-pack/plugins/infra/public/apps/legacy_app.tsx @@ -0,0 +1,98 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EuiErrorBoundary } from '@elastic/eui'; +import { createBrowserHistory, History } from 'history'; +import { AppMountParameters } from 'kibana/public'; +import React from 'react'; +import ReactDOM from 'react-dom'; +import { Route, RouteProps, Router, Switch } from 'react-router-dom'; +import url from 'url'; + +// This exists purely to facilitate legacy app/infra URL redirects. +// It will be removed in 8.0.0. +export async function renderApp({ element }: AppMountParameters) { + const history = createBrowserHistory(); + + ReactDOM.render(, element); + + return () => { + ReactDOM.unmountComponentAtNode(element); + }; +} + +const LegacyApp: React.FunctionComponent<{ history: History }> = ({ history }) => { + return ( + + + + { + if (!location) { + return null; + } + + let nextPath = ''; + let nextBasePath = ''; + let nextSearch; + + if ( + location.hash.indexOf('#infrastructure') > -1 || + location.hash.indexOf('#/infrastructure') > -1 + ) { + nextPath = location.hash.replace( + new RegExp( + '#infrastructure/|#/infrastructure/|#/infrastructure|#infrastructure', + 'g' + ), + '' + ); + nextBasePath = location.pathname.replace('app/infra', 'app/metrics'); + } else if ( + location.hash.indexOf('#logs') > -1 || + location.hash.indexOf('#/logs') > -1 + ) { + nextPath = location.hash.replace( + new RegExp('#logs/|#/logs/|#/logs|#logs', 'g'), + '' + ); + nextBasePath = location.pathname.replace('app/infra', 'app/logs'); + } else { + // This covers /app/infra and /app/infra/home (both of which used to render + // the metrics inventory page) + nextPath = 'inventory'; + nextBasePath = location.pathname.replace('app/infra', 'app/metrics'); + nextSearch = undefined; + } + + // app/infra#infrastructure/metrics/:type/:node was changed to app/metrics/detail/:type/:node, this + // accounts for that edge case + nextPath = nextPath.replace('metrics/', 'detail/'); + + // Query parameters (location.search) will arrive as part of location.hash and not location.search + const nextPathParts = nextPath.split('?'); + nextPath = nextPathParts[0]; + nextSearch = nextPathParts[1] ? nextPathParts[1] : undefined; + + let nextUrl = url.format({ + pathname: `${nextBasePath}/${nextPath}`, + hash: undefined, + search: nextSearch, + }); + + nextUrl = nextUrl.replace('//', '/'); + + window.location.href = nextUrl; + + return null; + }} + /> + + + + ); +}; diff --git a/x-pack/plugins/infra/public/apps/logs_app.tsx b/x-pack/plugins/infra/public/apps/logs_app.tsx new file mode 100644 index 0000000000000..e0251522bb24c --- /dev/null +++ b/x-pack/plugins/infra/public/apps/logs_app.tsx @@ -0,0 +1,66 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ApolloClient } from 'apollo-client'; +import { History } from 'history'; +import { CoreStart } from 'kibana/public'; +import React from 'react'; +import ReactDOM from 'react-dom'; +import { Route, Router, Switch } from 'react-router-dom'; +import { AppMountParameters } from '../../../../../src/core/public'; +import '../index.scss'; +import { NotFoundPage } from '../pages/404'; +import { LinkToLogsPage } from '../pages/link_to/link_to_logs'; +import { LogsPage } from '../pages/logs'; +import { ClientPluginDeps } from '../types'; +import { createApolloClient } from '../utils/apollo_client'; +import { CommonInfraProviders, CoreProviders } from './common_providers'; +import { prepareMountElement } from './common_styles'; + +export const renderApp = ( + core: CoreStart, + plugins: ClientPluginDeps, + { element, history }: AppMountParameters +) => { + const apolloClient = createApolloClient(core.http.fetch); + + prepareMountElement(element); + + ReactDOM.render( + , + element + ); + + return () => { + ReactDOM.unmountComponentAtNode(element); + }; +}; + +const LogsApp: React.FC<{ + apolloClient: ApolloClient<{}>; + core: CoreStart; + history: History; + plugins: ClientPluginDeps; +}> = ({ apolloClient, core, history, plugins }) => { + const uiCapabilities = core.application.capabilities; + + return ( + + + + + + {uiCapabilities?.logs?.show && } + + + + + + ); +}; diff --git a/x-pack/plugins/infra/public/apps/metrics_app.tsx b/x-pack/plugins/infra/public/apps/metrics_app.tsx new file mode 100644 index 0000000000000..8713abe0510a6 --- /dev/null +++ b/x-pack/plugins/infra/public/apps/metrics_app.tsx @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ApolloClient } from 'apollo-client'; +import { History } from 'history'; +import { CoreStart } from 'kibana/public'; +import React from 'react'; +import ReactDOM from 'react-dom'; +import { Route, Router, Switch } from 'react-router-dom'; +import { AppMountParameters } from '../../../../../src/core/public'; +import '../index.scss'; +import { NotFoundPage } from '../pages/404'; +import { LinkToMetricsPage } from '../pages/link_to/link_to_metrics'; +import { InfrastructurePage } from '../pages/metrics'; +import { MetricDetail } from '../pages/metrics/metric_detail'; +import { ClientPluginDeps } from '../types'; +import { createApolloClient } from '../utils/apollo_client'; +import { RedirectWithQueryParams } from '../utils/redirect_with_query_params'; +import { CommonInfraProviders, CoreProviders } from './common_providers'; +import { prepareMountElement } from './common_styles'; + +export const renderApp = ( + core: CoreStart, + plugins: ClientPluginDeps, + { element, history }: AppMountParameters +) => { + const apolloClient = createApolloClient(core.http.fetch); + + prepareMountElement(element); + + ReactDOM.render( + , + element + ); + + return () => { + ReactDOM.unmountComponentAtNode(element); + }; +}; + +const MetricsApp: React.FC<{ + apolloClient: ApolloClient<{}>; + core: CoreStart; + history: History; + plugins: ClientPluginDeps; +}> = ({ apolloClient, core, history, plugins }) => { + const uiCapabilities = core.application.capabilities; + + return ( + + + + + + {uiCapabilities?.infrastructure?.show && ( + + )} + {uiCapabilities?.infrastructure?.show && ( + + )} + {uiCapabilities?.infrastructure?.show && ( + + )} + {uiCapabilities?.infrastructure?.show && ( + + )} + {uiCapabilities?.infrastructure?.show && ( + + )} + + + + + + ); +}; diff --git a/x-pack/plugins/infra/public/apps/start_app.tsx b/x-pack/plugins/infra/public/apps/start_app.tsx deleted file mode 100644 index 4c213700b62e6..0000000000000 --- a/x-pack/plugins/infra/public/apps/start_app.tsx +++ /dev/null @@ -1,80 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import ReactDOM from 'react-dom'; -import { ApolloProvider } from 'react-apollo'; -import { CoreStart, AppMountParameters } from 'kibana/public'; - -// TODO use theme provided from parentApp when kibana supports it -import { EuiErrorBoundary } from '@elastic/eui'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { EuiThemeProvider } from '../../../observability/public/typings/eui_styled_components'; -import { InfraFrontendLibs } from '../lib/lib'; -import { ApolloClientContext } from '../utils/apollo_context'; -import { HistoryContext } from '../utils/history_context'; -import { - useUiSetting$, - KibanaContextProvider, -} from '../../../../../src/plugins/kibana_react/public'; -import { AppRouter } from '../routers'; -import { TriggersAndActionsUIPublicPluginSetup } from '../../../triggers_actions_ui/public'; -import { TriggersActionsProvider } from '../utils/triggers_actions_context'; -import '../index.scss'; -import { NavigationWarningPromptProvider } from '../utils/navigation_warning_prompt'; - -export const CONTAINER_CLASSNAME = 'infra-container-element'; - -export async function startApp( - libs: InfraFrontendLibs, - core: CoreStart, - plugins: object, - params: AppMountParameters, - Router: AppRouter, - triggersActionsUI: TriggersAndActionsUIPublicPluginSetup -) { - const { element, history } = params; - - const InfraPluginRoot: React.FunctionComponent = () => { - const [darkMode] = useUiSetting$('theme:darkMode'); - - return ( - - - - - - - - - - - - - - - - - - ); - }; - - const App: React.FunctionComponent = () => ( - - - - ); - - // Ensure the element we're handed from application mounting is assigned a class - // for our index.scss styles to apply to. - element.className += ` ${CONTAINER_CLASSNAME}`; - - ReactDOM.render(, element); - - return () => { - ReactDOM.unmountComponentAtNode(element); - }; -} diff --git a/x-pack/plugins/infra/public/apps/start_legacy_app.tsx b/x-pack/plugins/infra/public/apps/start_legacy_app.tsx deleted file mode 100644 index 6e5960ceb2081..0000000000000 --- a/x-pack/plugins/infra/public/apps/start_legacy_app.tsx +++ /dev/null @@ -1,100 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { createBrowserHistory } from 'history'; -import React from 'react'; -import url from 'url'; -import ReactDOM from 'react-dom'; -import { AppMountParameters } from 'kibana/public'; -import { Route, Router, Switch, RouteProps } from 'react-router-dom'; -// TODO use theme provided from parentApp when kibana supports it -import { EuiErrorBoundary } from '@elastic/eui'; - -// This exists purely to facilitate legacy app/infra URL redirects. -// It will be removed in 8.0.0. -export async function startLegacyApp(params: AppMountParameters) { - const { element } = params; - const history = createBrowserHistory(); - - const App: React.FunctionComponent = () => { - return ( - - - - { - if (!location) { - return null; - } - - let nextPath = ''; - let nextBasePath = ''; - let nextSearch; - - if ( - location.hash.indexOf('#infrastructure') > -1 || - location.hash.indexOf('#/infrastructure') > -1 - ) { - nextPath = location.hash.replace( - new RegExp( - '#infrastructure/|#/infrastructure/|#/infrastructure|#infrastructure', - 'g' - ), - '' - ); - nextBasePath = location.pathname.replace('app/infra', 'app/metrics'); - } else if ( - location.hash.indexOf('#logs') > -1 || - location.hash.indexOf('#/logs') > -1 - ) { - nextPath = location.hash.replace( - new RegExp('#logs/|#/logs/|#/logs|#logs', 'g'), - '' - ); - nextBasePath = location.pathname.replace('app/infra', 'app/logs'); - } else { - // This covers /app/infra and /app/infra/home (both of which used to render - // the metrics inventory page) - nextPath = 'inventory'; - nextBasePath = location.pathname.replace('app/infra', 'app/metrics'); - nextSearch = undefined; - } - - // app/inra#infrastructure/metrics/:type/:node was changed to app/metrics/detail/:type/:node, this - // accounts for that edge case - nextPath = nextPath.replace('metrics/', 'detail/'); - - // Query parameters (location.search) will arrive as part of location.hash and not location.search - const nextPathParts = nextPath.split('?'); - nextPath = nextPathParts[0]; - nextSearch = nextPathParts[1] ? nextPathParts[1] : undefined; - - let nextUrl = url.format({ - pathname: `${nextBasePath}/${nextPath}`, - hash: undefined, - search: nextSearch, - }); - - nextUrl = nextUrl.replace('//', '/'); - - window.location.href = nextUrl; - - return null; - }} - /> - - - - ); - }; - - ReactDOM.render(, element); - - return () => { - ReactDOM.unmountComponentAtNode(element); - }; -} diff --git a/x-pack/plugins/infra/public/components/alerting/inventory/expression.tsx b/x-pack/plugins/infra/public/components/alerting/inventory/expression.tsx index 074464fb55414..ce14897991e60 100644 --- a/x-pack/plugins/infra/public/components/alerting/inventory/expression.tsx +++ b/x-pack/plugins/infra/public/components/alerting/inventory/expression.tsx @@ -336,6 +336,10 @@ export const Expressions: React.FC = (props) => { ); }; +// required for dynamic import +// eslint-disable-next-line import/no-default-export +export default Expressions; + interface ExpressionRowProps { nodeType: InventoryItemType; expressionId: number; diff --git a/x-pack/plugins/infra/public/components/alerting/inventory/metric_inventory_threshold_alert_type.ts b/x-pack/plugins/infra/public/components/alerting/inventory/metric_inventory_threshold_alert_type.ts index 9ede2d2a47727..0cb564ec2194e 100644 --- a/x-pack/plugins/infra/public/components/alerting/inventory/metric_inventory_threshold_alert_type.ts +++ b/x-pack/plugins/infra/public/components/alerting/inventory/metric_inventory_threshold_alert_type.ts @@ -4,9 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ import { i18n } from '@kbn/i18n'; +import React from 'react'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { AlertTypeModel } from '../../../../../triggers_actions_ui/public/types'; -import { Expressions } from './expression'; import { validateMetricThreshold } from './validation'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { METRIC_INVENTORY_THRESHOLD_ALERT_TYPE_ID } from '../../../../server/lib/alerting/inventory_metric_threshold/types'; @@ -18,7 +18,7 @@ export function getInventoryMetricAlertType(): AlertTypeModel { defaultMessage: 'Inventory', }), iconClass: 'bell', - alertParamsExpression: Expressions, + alertParamsExpression: React.lazy(() => import('./expression')), validate: validateMetricThreshold, defaultActionMessage: i18n.translate( 'xpack.infra.metrics.alerting.inventory.threshold.defaultActionMessage', diff --git a/x-pack/plugins/infra/public/components/alerting/inventory/validation.tsx b/x-pack/plugins/infra/public/components/alerting/inventory/validation.tsx index 441adeec988c7..47ecd3c527fad 100644 --- a/x-pack/plugins/infra/public/components/alerting/inventory/validation.tsx +++ b/x-pack/plugins/infra/public/components/alerting/inventory/validation.tsx @@ -6,8 +6,6 @@ import { i18n } from '@kbn/i18n'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { isNumber } from 'lodash'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths import { MetricExpressionParams } from '../../../../server/lib/alerting/metric_threshold/types'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { ValidationResult } from '../../../../../triggers_actions_ui/public/types'; @@ -95,3 +93,5 @@ export function validateMetricThreshold({ return validationResult; } + +const isNumber = (value: unknown): value is number => typeof value === 'number'; diff --git a/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/editor.tsx b/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/editor.tsx index 609f99805fe9c..a3a48d477425b 100644 --- a/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/editor.tsx +++ b/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/editor.tsx @@ -236,3 +236,7 @@ export const Editor: React.FC = (props) => { ); }; + +// required for dynamic import +// eslint-disable-next-line import/no-default-export +export default Editor; diff --git a/x-pack/plugins/infra/public/components/alerting/logs/log_threshold_alert_type.ts b/x-pack/plugins/infra/public/components/alerting/logs/log_threshold_alert_type.ts index 9bba8bd804f80..4c7811f0d9666 100644 --- a/x-pack/plugins/infra/public/components/alerting/logs/log_threshold_alert_type.ts +++ b/x-pack/plugins/infra/public/components/alerting/logs/log_threshold_alert_type.ts @@ -4,10 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ import { i18n } from '@kbn/i18n'; +import React from 'react'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { AlertTypeModel } from '../../../../../triggers_actions_ui/public/types'; import { LOG_DOCUMENT_COUNT_ALERT_TYPE_ID } from '../../../../common/alerting/logs/types'; -import { ExpressionEditor } from './expression_editor'; import { validateExpression } from './validation'; export function getAlertType(): AlertTypeModel { @@ -17,7 +17,7 @@ export function getAlertType(): AlertTypeModel { defaultMessage: 'Log threshold', }), iconClass: 'bell', - alertParamsExpression: ExpressionEditor, + alertParamsExpression: React.lazy(() => import('./expression_editor/editor')), validate: validateExpression, defaultActionMessage: i18n.translate( 'xpack.infra.logs.alerting.threshold.defaultActionMessage', diff --git a/x-pack/plugins/infra/public/compose_libs.ts b/x-pack/plugins/infra/public/compose_libs.ts deleted file mode 100644 index f2060983e95eb..0000000000000 --- a/x-pack/plugins/infra/public/compose_libs.ts +++ /dev/null @@ -1,99 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory'; -import ApolloClient from 'apollo-client'; -import { ApolloLink } from 'apollo-link'; -import { createHttpLink } from 'apollo-link-http'; -import { withClientState } from 'apollo-link-state'; -import { CoreStart, HttpFetchOptions } from 'src/core/public'; -import { InfraFrontendLibs } from './lib/lib'; -import introspectionQueryResultData from './graphql/introspection.json'; -import { InfraKibanaObservableApiAdapter } from './lib/adapters/observable_api/kibana_observable_api'; - -export function composeLibs(core: CoreStart) { - const cache = new InMemoryCache({ - addTypename: false, - fragmentMatcher: new IntrospectionFragmentMatcher({ - introspectionQueryResultData, - }), - }); - - const observableApi = new InfraKibanaObservableApiAdapter({ - basePath: core.http.basePath.get(), - }); - - const wrappedFetch = (path: string, options: HttpFetchOptions) => { - return new Promise(async (resolve, reject) => { - // core.http.fetch isn't 100% compatible with the Fetch API and will - // throw Errors on 401s. This top level try / catch handles those scenarios. - try { - core.http - .fetch(path, { - ...options, - // Set headers to undefined due to this bug: https://github.com/apollographql/apollo-link/issues/249, - // Apollo will try to set a "content-type" header which will conflict with the "Content-Type" header that - // core.http.fetch correctly sets. - headers: undefined, - asResponse: true, - }) - .then((res) => { - if (!res.response) { - return reject(); - } - // core.http.fetch will parse the Response and set a body before handing it back. As such .text() / .json() - // will have already been called on the Response instance. However, Apollo will also want to call - // .text() / .json() on the instance, as it expects the raw Response instance, rather than core's wrapper. - // .text() / .json() can only be called once, and an Error will be thrown if those methods are accessed again. - // This hacks around that by setting up a new .text() method that will restringify the JSON response we already have. - // This does result in an extra stringify / parse cycle, which isn't ideal, but as we only have a few endpoints left using - // GraphQL this shouldn't create excessive overhead. - // Ref: https://github.com/apollographql/apollo-link/blob/master/packages/apollo-link-http/src/httpLink.ts#L134 - // and - // https://github.com/apollographql/apollo-link/blob/master/packages/apollo-link-http-common/src/index.ts#L125 - return resolve({ - ...res.response, - text: () => { - return new Promise(async (resolveText, rejectText) => { - if (res.body) { - return resolveText(JSON.stringify(res.body)); - } else { - return rejectText(); - } - }); - }, - }); - }); - } catch (error) { - reject(error); - } - }); - }; - - const HttpLink = createHttpLink({ - fetch: wrappedFetch, - uri: `/api/infra/graphql`, - }); - - const graphQLOptions = { - cache, - link: ApolloLink.from([ - withClientState({ - cache, - resolvers: {}, - }), - HttpLink, - ]), - }; - - const apolloClient = new ApolloClient(graphQLOptions); - - const libs: InfraFrontendLibs = { - apolloClient, - observableApi, - }; - return libs; -} diff --git a/x-pack/plugins/infra/public/containers/with_state_from_location.tsx b/x-pack/plugins/infra/public/containers/with_state_from_location.tsx deleted file mode 100644 index 2a9676046d451..0000000000000 --- a/x-pack/plugins/infra/public/containers/with_state_from_location.tsx +++ /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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { parse, stringify } from 'query-string'; -import { Location } from 'history'; -import { omit } from 'lodash'; -import React from 'react'; -import { RouteComponentProps, withRouter } from 'react-router-dom'; -// eslint-disable-next-line @typescript-eslint/camelcase -import { decode_object, encode_object } from 'rison-node'; -import { Omit } from '../lib/lib'; - -interface AnyObject { - [key: string]: any; -} - -interface WithStateFromLocationOptions { - mapLocationToState: (location: Location) => StateInLocation; - mapStateToLocation: (state: StateInLocation, location: Location) => Location; -} - -type InjectedPropsFromLocation = Partial & { - pushStateInLocation?: (state: StateInLocation) => void; - replaceStateInLocation?: (state: StateInLocation) => void; -}; - -export const withStateFromLocation = ({ - mapLocationToState, - mapStateToLocation, -}: WithStateFromLocationOptions) => < - WrappedComponentProps extends InjectedPropsFromLocation ->( - WrappedComponent: React.ComponentType -) => { - const wrappedName = WrappedComponent.displayName || WrappedComponent.name; - - return withRouter( - class WithStateFromLocation extends React.PureComponent< - RouteComponentProps<{}> & - Omit> - > { - public static displayName = `WithStateFromLocation(${wrappedName})`; - - public render() { - const { location } = this.props; - const otherProps = omit(this.props, ['location', 'history', 'match', 'staticContext']); - - const stateFromLocation = mapLocationToState(location); - - return ( - // @ts-ignore - - ); - } - - private pushStateInLocation = (state: StateInLocation) => { - const { history, location } = this.props; - - const newLocation = mapStateToLocation(state, this.props.location); - - if (newLocation !== location) { - history.push(newLocation); - } - }; - - private replaceStateInLocation = (state: StateInLocation) => { - const { history, location } = this.props; - - const newLocation = mapStateToLocation(state, this.props.location); - - if (newLocation !== location) { - history.replace(newLocation); - } - }; - } - ); -}; - -const decodeRisonAppState = (queryValues: { _a?: string }): AnyObject => { - try { - return queryValues && queryValues._a ? decode_object(queryValues._a) : {}; - } catch (error) { - if (error instanceof Error && error.message.startsWith('rison decoder error')) { - return {}; - } - throw error; - } -}; - -const encodeRisonAppState = (state: AnyObject) => ({ - _a: encode_object(state), -}); - -export const mapRisonAppLocationToState = ( - mapState: (risonAppState: AnyObject) => State = (state: AnyObject) => state as State -) => (location: Location): State => { - const queryValues = parse(location.search.substring(1), { sort: false }); - const decodedState = decodeRisonAppState(queryValues); - return mapState(decodedState); -}; - -export const mapStateToRisonAppLocation = ( - mapState: (state: State) => AnyObject = (state: State) => state -) => (state: State, location: Location): Location => { - const previousQueryValues = parse(location.search.substring(1), { sort: false }); - const previousState = decodeRisonAppState(previousQueryValues); - - const encodedState = encodeRisonAppState({ - ...previousState, - ...mapState(state), - }); - const newQueryValues = stringify( - { - ...previousQueryValues, - ...encodedState, - }, - { sort: false } - ); - return { - ...location, - search: `?${newQueryValues}`, - }; -}; diff --git a/x-pack/plugins/infra/public/graphql/log_entries.gql_query.ts b/x-pack/plugins/infra/public/graphql/log_entries.gql_query.ts deleted file mode 100644 index 41ff3c293a713..0000000000000 --- a/x-pack/plugins/infra/public/graphql/log_entries.gql_query.ts +++ /dev/null @@ -1,44 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import gql from 'graphql-tag'; - -import { sharedFragments } from '../../common/graphql/shared'; - -export const logEntriesQuery = gql` - query LogEntries( - $sourceId: ID = "default" - $timeKey: InfraTimeKeyInput! - $countBefore: Int = 0 - $countAfter: Int = 0 - $filterQuery: String - ) { - source(id: $sourceId) { - id - logEntriesAround( - key: $timeKey - countBefore: $countBefore - countAfter: $countAfter - filterQuery: $filterQuery - ) { - start { - ...InfraTimeKeyFields - } - end { - ...InfraTimeKeyFields - } - hasMoreBefore - hasMoreAfter - entries { - ...InfraLogEntryFields - } - } - } - } - - ${sharedFragments.InfraTimeKey} - ${sharedFragments.InfraLogEntryFields} -`; diff --git a/x-pack/plugins/infra/public/hooks/use_link_props.test.tsx b/x-pack/plugins/infra/public/hooks/use_link_props.test.tsx index f9cfaf71036f6..d93cc44c45623 100644 --- a/x-pack/plugins/infra/public/hooks/use_link_props.test.tsx +++ b/x-pack/plugins/infra/public/hooks/use_link_props.test.tsx @@ -4,15 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ -import { encode } from 'rison-node'; -import { createMemoryHistory } from 'history'; import { renderHook } from '@testing-library/react-hooks'; +import { createMemoryHistory } from 'history'; import React from 'react'; -import { KibanaContextProvider } from '../../../../../src/plugins/kibana_react/public'; -import { HistoryContext } from '../utils/history_context'; +import { Router } from 'react-router-dom'; +import { encode } from 'rison-node'; import { coreMock } from 'src/core/public/mocks'; -import { useLinkProps, LinkDescriptor } from './use_link_props'; import { ScopedHistory } from '../../../../../src/core/public'; +import { KibanaContextProvider } from '../../../../../src/plugins/kibana_react/public'; +import { LinkDescriptor, useLinkProps } from './use_link_props'; const PREFIX = '/test-basepath/s/test-space/app/'; @@ -30,9 +30,9 @@ const scopedHistory = new ScopedHistory(history, `${PREFIX}${INTERNAL_APP}`); const ProviderWrapper: React.FC = ({ children }) => { return ( - + {children}; - + ); }; diff --git a/x-pack/plugins/infra/public/index.ts b/x-pack/plugins/infra/public/index.ts index 1dfdf827f203b..8f2d37fa1daa9 100644 --- a/x-pack/plugins/infra/public/index.ts +++ b/x-pack/plugins/infra/public/index.ts @@ -4,8 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { PluginInitializerContext, PluginInitializer } from 'kibana/public'; -import { Plugin, ClientSetup, ClientStart, ClientPluginsSetup, ClientPluginsStart } from './plugin'; +import { PluginInitializer, PluginInitializerContext } from 'kibana/public'; +import { ClientSetup, ClientStart, Plugin } from './plugin'; +import { ClientPluginsSetup, ClientPluginsStart } from './types'; export const plugin: PluginInitializer< ClientSetup, diff --git a/x-pack/plugins/infra/public/lib/adapters/observable_api/kibana_observable_api.ts b/x-pack/plugins/infra/public/lib/adapters/observable_api/kibana_observable_api.ts deleted file mode 100644 index 9ae21d96886f3..0000000000000 --- a/x-pack/plugins/infra/public/lib/adapters/observable_api/kibana_observable_api.ts +++ /dev/null @@ -1,45 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { ajax } from 'rxjs/ajax'; -import { map } from 'rxjs/operators'; - -import { - InfraObservableApi, - InfraObservableApiPostParams, - InfraObservableApiResponse, -} from '../../lib'; - -export class InfraKibanaObservableApiAdapter implements InfraObservableApi { - private basePath: string; - private defaultHeaders: { - [headerName: string]: boolean | string; - }; - - constructor({ basePath }: { basePath: string }) { - this.basePath = basePath; - this.defaultHeaders = { - 'kbn-xsrf': true, - }; - } - - public post = ({ - url, - body, - }: InfraObservableApiPostParams): InfraObservableApiResponse => - ajax({ - body: body ? JSON.stringify(body) : undefined, - headers: { - ...this.defaultHeaders, - 'Content-Type': 'application/json', - }, - method: 'POST', - responseType: 'json', - timeout: 30000, - url: `${this.basePath}/api/${url}`, - withCredentials: true, - }).pipe(map(({ response, status }) => ({ response, status }))); -} diff --git a/x-pack/plugins/infra/public/lib/lib.ts b/x-pack/plugins/infra/public/lib/lib.ts index d1ca62b747a24..93f7ef644f795 100644 --- a/x-pack/plugins/infra/public/lib/lib.ts +++ b/x-pack/plugins/infra/public/lib/lib.ts @@ -4,102 +4,18 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IModule, IScope } from 'angular'; -import { NormalizedCacheObject } from 'apollo-cache-inmemory'; -import ApolloClient from 'apollo-client'; -import { AxiosRequestConfig } from 'axios'; -import React from 'react'; -import { Observable } from 'rxjs'; -import * as rt from 'io-ts'; import { i18n } from '@kbn/i18n'; -import { SourceQuery } from '../graphql/types'; +import * as rt from 'io-ts'; import { - SnapshotMetricInput, - SnapshotGroupBy, InfraTimerangeInput, + SnapshotGroupBy, + SnapshotMetricInput, SnapshotNodeMetric, SnapshotNodePath, } from '../../common/http_api/snapshot_api'; +import { SourceQuery } from '../graphql/types'; import { WaffleSortOption } from '../pages/metrics/inventory_view/hooks/use_waffle_options'; -export interface InfraFrontendLibs { - apolloClient: InfraApolloClient; - observableApi: InfraObservableApi; -} - -export type InfraTimezoneProvider = () => string; - -export type InfraApolloClient = ApolloClient; - -export interface InfraFrameworkAdapter { - // Insstance vars - appState?: object; - kbnVersion?: string; - timezone?: string; - - // Methods - setUISettings(key: string, value: any): void; - render(component: React.ReactElement): void; - renderBreadcrumbs(component: React.ReactElement): void; -} - -export type InfraFramworkAdapterConstructable = new ( - uiModule: IModule, - timezoneProvider: InfraTimezoneProvider -) => InfraFrameworkAdapter; - -// TODO: replace AxiosRequestConfig with something more defined -export type InfraRequestConfig = AxiosRequestConfig; - -export interface InfraApiAdapter { - get(url: string, config?: InfraRequestConfig | undefined): Promise; - post(url: string, data?: any, config?: AxiosRequestConfig | undefined): Promise; - delete(url: string, config?: InfraRequestConfig | undefined): Promise; - put(url: string, data?: any, config?: InfraRequestConfig | undefined): Promise; -} - -export interface InfraObservableApiPostParams { - url: string; - body?: RequestBody; -} - -export type InfraObservableApiResponse = Observable<{ - status: number; - response: BodyType; -}>; - -export interface InfraObservableApi { - post( - params: InfraObservableApiPostParams - ): InfraObservableApiResponse; -} - -export interface InfraUiKibanaAdapterScope extends IScope { - breadcrumbs: any[]; - topNavMenu: any[]; -} - -export interface InfraKibanaUIConfig { - get(key: string): any; - set(key: string, value: any): Promise; -} - -export interface InfraKibanaAdapterServiceRefs { - config: InfraKibanaUIConfig; - rootScope: IScope; -} - -export type InfraBufferedKibanaServiceCall = (serviceRefs: ServiceRefs) => void; - -export interface InfraField { - name: string; - type: string; - searchable: boolean; - aggregatable: boolean; -} - -export type InfraWaffleData = InfraWaffleMapGroup[]; - export interface InfraWaffleMapNode { pathId: string; id: string; @@ -221,8 +137,6 @@ export interface InfraOptions { wafflemap: InfraWaffleMapOptions; } -export type Omit = Pick>; - export interface InfraWaffleMapBounds { min: number; max: number; diff --git a/x-pack/plugins/infra/public/pages/link_to/redirect_to_node_logs.test.tsx b/x-pack/plugins/infra/public/pages/link_to/redirect_to_node_logs.test.tsx index 1394fc48107ef..e62b29974674a 100644 --- a/x-pack/plugins/infra/public/pages/link_to/redirect_to_node_logs.test.tsx +++ b/x-pack/plugins/infra/public/pages/link_to/redirect_to_node_logs.test.tsx @@ -35,7 +35,7 @@ describe('RedirectToNodeLogs component', () => { expect(component).toMatchInlineSnapshot(` `); }); @@ -47,7 +47,7 @@ describe('RedirectToNodeLogs component', () => { expect(component).toMatchInlineSnapshot(` `); }); @@ -59,7 +59,7 @@ describe('RedirectToNodeLogs component', () => { expect(component).toMatchInlineSnapshot(` `); }); @@ -73,7 +73,7 @@ describe('RedirectToNodeLogs component', () => { expect(component).toMatchInlineSnapshot(` `); }); @@ -89,7 +89,7 @@ describe('RedirectToNodeLogs component', () => { expect(component).toMatchInlineSnapshot(` `); }); @@ -103,7 +103,7 @@ describe('RedirectToNodeLogs component', () => { expect(component).toMatchInlineSnapshot(` `); }); diff --git a/x-pack/plugins/infra/public/pages/link_to/redirect_to_node_logs.tsx b/x-pack/plugins/infra/public/pages/link_to/redirect_to_node_logs.tsx index d9aaa2da7bbc8..10320ebbe7609 100644 --- a/x-pack/plugins/infra/public/pages/link_to/redirect_to_node_logs.tsx +++ b/x-pack/plugins/infra/public/pages/link_to/redirect_to_node_logs.tsx @@ -71,7 +71,7 @@ export const RedirectToNodeLogs = ({ replaceSourceIdInQueryString(sourceId) )(''); - return ; + return ; }; export const getNodeLogsUrl = ({ diff --git a/x-pack/plugins/infra/public/pages/logs/page_content.tsx b/x-pack/plugins/infra/public/pages/logs/page_content.tsx index 2974939a83215..14c53557ba2c7 100644 --- a/x-pack/plugins/infra/public/pages/logs/page_content.tsx +++ b/x-pack/plugins/infra/public/pages/logs/page_content.tsx @@ -96,6 +96,7 @@ export const LogsPageContent: React.FunctionComponent = () => { + ); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/table_view.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/table_view.tsx index 3b68ad314f7df..764eeb154d346 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/table_view.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/table_view.tsx @@ -15,7 +15,7 @@ import { fieldToName } from '../lib/field_to_display_name'; import { NodeContextMenu } from './waffle/node_context_menu'; import { InventoryItemType } from '../../../../../common/inventory_models/types'; import { SnapshotNode, SnapshotNodePath } from '../../../../../common/http_api/snapshot_api'; -import { CONTAINER_CLASSNAME } from '../../../../apps/start_app'; +import { CONTAINER_CLASSNAME } from '../../../../apps/common_styles'; interface Props { nodes: SnapshotNode[]; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_time.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_time.ts index 91cf405dcc759..9a1fbee421294 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_time.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_time.ts @@ -26,7 +26,9 @@ export const useWaffleTime = () => { const [state, setState] = useState(urlState); - useEffect(() => setUrlState(state), [setUrlState, state]); + useEffect(() => { + setUrlState(state); + }, [setUrlState, state]); const { currentTime, isAutoReloading } = urlState; diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/hooks/metrics_time.test.tsx b/x-pack/plugins/infra/public/pages/metrics/metric_detail/hooks/metrics_time.test.tsx index 17fcc05406470..d2076ad6df502 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/hooks/metrics_time.test.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/hooks/metrics_time.test.tsx @@ -4,14 +4,20 @@ * you may not use this file except in compliance with the Elastic License. */ +import { createMemoryHistory } from 'history'; +import React from 'react'; +import { Router } from 'react-router-dom'; import { mountHook } from 'test_utils/enzyme_helpers'; - +import { ScopedHistory } from '../../../../../../../../src/core/public'; import { useMetricsTime } from './use_metrics_time'; describe('useMetricsTime hook', () => { describe('timeRange state', () => { it('has a default value', () => { - const { getLastHookValue } = mountHook(() => useMetricsTime().timeRange); + const { getLastHookValue } = mountHook( + () => useMetricsTime().timeRange, + createProviderWrapper() + ); const hookValue = getLastHookValue(); expect(hookValue).toHaveProperty('from'); expect(hookValue).toHaveProperty('to'); @@ -19,7 +25,7 @@ describe('useMetricsTime hook', () => { }); it('can be updated', () => { - const { act, getLastHookValue } = mountHook(() => useMetricsTime()); + const { act, getLastHookValue } = mountHook(() => useMetricsTime(), createProviderWrapper()); const timeRange = { from: 'now-15m', @@ -37,12 +43,15 @@ describe('useMetricsTime hook', () => { describe('AutoReloading state', () => { it('has a default value', () => { - const { getLastHookValue } = mountHook(() => useMetricsTime().isAutoReloading); + const { getLastHookValue } = mountHook( + () => useMetricsTime().isAutoReloading, + createProviderWrapper() + ); expect(getLastHookValue()).toBe(false); }); it('can be updated', () => { - const { act, getLastHookValue } = mountHook(() => useMetricsTime()); + const { act, getLastHookValue } = mountHook(() => useMetricsTime(), createProviderWrapper()); act(({ setAutoReload }) => { setAutoReload(true); @@ -52,3 +61,17 @@ describe('useMetricsTime hook', () => { }); }); }); + +const createProviderWrapper = () => { + const INITIAL_URL = '/test-basepath/s/test-space/app/metrics'; + const history = createMemoryHistory(); + + history.push(INITIAL_URL); + const scopedHistory = new ScopedHistory(history, INITIAL_URL); + + const ProviderWrapper: React.FC = ({ children }) => { + return {children}; + }; + + return ProviderWrapper; +}; diff --git a/x-pack/plugins/infra/public/plugin.ts b/x-pack/plugins/infra/public/plugin.ts index deae78e22c6a1..b3765db43335a 100644 --- a/x-pack/plugins/infra/public/plugin.ts +++ b/x-pack/plugins/infra/public/plugin.ts @@ -4,54 +4,29 @@ * you may not use this file except in compliance with the Elastic License. */ import { i18n } from '@kbn/i18n'; -import { merge } from 'lodash'; import { - Plugin as PluginClass, + AppMountParameters, CoreSetup, CoreStart, + Plugin as PluginClass, PluginInitializerContext, - AppMountParameters, } from 'kibana/public'; import { DEFAULT_APP_CATEGORIES } from '../../../../src/core/public'; +import { createMetricThresholdAlertType } from './alerting/metric_threshold'; +import { getInventoryMetricAlertType } from './components/alerting/inventory/metric_inventory_threshold_alert_type'; +import { getAlertType as getLogsAlertType } from './components/alerting/logs/log_threshold_alert_type'; import { registerStartSingleton } from './legacy_singletons'; import { registerFeatures } from './register_feature'; -import { HomePublicPluginSetup } from '../../../../src/plugins/home/public'; -import { DataPublicPluginSetup, DataPublicPluginStart } from '../../../../src/plugins/data/public'; -import { UsageCollectionSetup } from '../../../../src/plugins/usage_collection/public'; -import { DataEnhancedSetup, DataEnhancedStart } from '../../data_enhanced/public'; - -import { TriggersAndActionsUIPublicPluginSetup } from '../../../plugins/triggers_actions_ui/public'; -import { getAlertType as getLogsAlertType } from './components/alerting/logs/log_threshold_alert_type'; -import { getInventoryMetricAlertType } from './components/alerting/inventory/metric_inventory_threshold_alert_type'; -import { createMetricThresholdAlertType } from './alerting/metric_threshold'; +import { ClientPluginsSetup, ClientPluginsStart } from './types'; export type ClientSetup = void; export type ClientStart = void; -export interface ClientPluginsSetup { - home: HomePublicPluginSetup; - data: DataPublicPluginSetup; - usageCollection: UsageCollectionSetup; - dataEnhanced: DataEnhancedSetup; - triggers_actions_ui: TriggersAndActionsUIPublicPluginSetup; -} - -export interface ClientPluginsStart { - data: DataPublicPluginStart; - dataEnhanced: DataEnhancedStart; -} - -export type InfraPlugins = ClientPluginsSetup & ClientPluginsStart; - -const getMergedPlugins = (setup: ClientPluginsSetup, start: ClientPluginsStart): InfraPlugins => { - return merge({}, setup, start); -}; - export class Plugin implements PluginClass { - constructor(context: PluginInitializerContext) {} + constructor(_context: PluginInitializerContext) {} - setup(core: CoreSetup, pluginsSetup: ClientPluginsSetup) { + setup(core: CoreSetup, pluginsSetup: ClientPluginsSetup) { registerFeatures(pluginsSetup.home); pluginsSetup.triggers_actions_ui.alertTypeRegistry.register(getInventoryMetricAlertType()); @@ -69,16 +44,18 @@ export class Plugin category: DEFAULT_APP_CATEGORIES.observability, mount: async (params: AppMountParameters) => { const [coreStart, pluginsStart] = await core.getStartServices(); - const plugins = getMergedPlugins(pluginsSetup, pluginsStart as ClientPluginsStart); - const { startApp, composeLibs, LogsRouter } = await this.downloadAssets(); + const { renderApp } = await import('./apps/logs_app'); - return startApp( - composeLibs(coreStart), + return renderApp( coreStart, - plugins, - params, - LogsRouter, - pluginsSetup.triggers_actions_ui + { + data: pluginsStart.data, + dataEnhanced: pluginsSetup.dataEnhanced, + home: pluginsSetup.home, + triggers_actions_ui: pluginsStart.triggers_actions_ui, + usageCollection: pluginsSetup.usageCollection, + }, + params ); }, }); @@ -94,16 +71,18 @@ export class Plugin category: DEFAULT_APP_CATEGORIES.observability, mount: async (params: AppMountParameters) => { const [coreStart, pluginsStart] = await core.getStartServices(); - const plugins = getMergedPlugins(pluginsSetup, pluginsStart as ClientPluginsStart); - const { startApp, composeLibs, MetricsRouter } = await this.downloadAssets(); + const { renderApp } = await import('./apps/metrics_app'); - return startApp( - composeLibs(coreStart), + return renderApp( coreStart, - plugins, - params, - MetricsRouter, - pluginsSetup.triggers_actions_ui + { + data: pluginsStart.data, + dataEnhanced: pluginsSetup.dataEnhanced, + home: pluginsSetup.home, + triggers_actions_ui: pluginsStart.triggers_actions_ui, + usageCollection: pluginsSetup.usageCollection, + }, + params ); }, }); @@ -116,28 +95,14 @@ export class Plugin title: 'infra', navLinkStatus: 3, mount: async (params: AppMountParameters) => { - const { startLegacyApp } = await import('./apps/start_legacy_app'); - return startLegacyApp(params); + const { renderApp } = await import('./apps/legacy_app'); + + return renderApp(params); }, }); } - start(core: CoreStart, plugins: ClientPluginsStart) { + start(core: CoreStart, _plugins: ClientPluginsStart) { registerStartSingleton(core); } - - private async downloadAssets() { - const [{ startApp }, { composeLibs }, { LogsRouter, MetricsRouter }] = await Promise.all([ - import('./apps/start_app'), - import('./compose_libs'), - import('./routers'), - ]); - - return { - startApp, - composeLibs, - LogsRouter, - MetricsRouter, - }; - } } diff --git a/x-pack/plugins/infra/public/routers/logs_router.tsx b/x-pack/plugins/infra/public/routers/logs_router.tsx deleted file mode 100644 index 8258f087b5872..0000000000000 --- a/x-pack/plugins/infra/public/routers/logs_router.tsx +++ /dev/null @@ -1,31 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import { Route, Router, Switch } from 'react-router-dom'; - -import { NotFoundPage } from '../pages/404'; -import { LinkToLogsPage } from '../pages/link_to'; -import { LogsPage } from '../pages/logs'; -import { RedirectWithQueryParams } from '../utils/redirect_with_query_params'; -import { useKibana } from '../../../../../src/plugins/kibana_react/public'; -import { AppRouter } from './index'; - -export const LogsRouter: AppRouter = ({ history }) => { - const uiCapabilities = useKibana().services.application?.capabilities; - return ( - - - - {uiCapabilities?.logs?.show && ( - - )} - {uiCapabilities?.logs?.show && } - - - - ); -}; diff --git a/x-pack/plugins/infra/public/routers/metrics_router.tsx b/x-pack/plugins/infra/public/routers/metrics_router.tsx deleted file mode 100644 index 0e427150a46cc..0000000000000 --- a/x-pack/plugins/infra/public/routers/metrics_router.tsx +++ /dev/null @@ -1,41 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import { Route, Router, Switch } from 'react-router-dom'; - -import { NotFoundPage } from '../pages/404'; -import { InfrastructurePage } from '../pages/metrics'; -import { MetricDetail } from '../pages/metrics/metric_detail'; -import { RedirectWithQueryParams } from '../utils/redirect_with_query_params'; -import { useKibana } from '../../../../../src/plugins/kibana_react/public'; -import { AppRouter } from './index'; -import { LinkToMetricsPage } from '../pages/link_to'; - -export const MetricsRouter: AppRouter = ({ history }) => { - const uiCapabilities = useKibana().services.application?.capabilities; - return ( - - - - {uiCapabilities?.infrastructure?.show && ( - - )} - {uiCapabilities?.infrastructure?.show && ( - - )} - {uiCapabilities?.infrastructure?.show && ( - - )} - {uiCapabilities?.infrastructure?.show && ( - - )} - {uiCapabilities?.infrastructure?.show && } - - - - ); -}; diff --git a/x-pack/plugins/infra/public/types.ts b/x-pack/plugins/infra/public/types.ts new file mode 100644 index 0000000000000..8181da3301c92 --- /dev/null +++ b/x-pack/plugins/infra/public/types.ts @@ -0,0 +1,25 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DataPublicPluginStart } from '../../../../src/plugins/data/public'; +import { HomePublicPluginSetup } from '../../../../src/plugins/home/public'; +import { UsageCollectionSetup } from '../../../../src/plugins/usage_collection/public'; +import { TriggersAndActionsUIPublicPluginSetup } from '../../../plugins/triggers_actions_ui/public'; +import { DataEnhancedSetup } from '../../data_enhanced/public'; + +export interface ClientPluginsSetup { + dataEnhanced: DataEnhancedSetup; + home: HomePublicPluginSetup; + triggers_actions_ui: TriggersAndActionsUIPublicPluginSetup; + usageCollection: UsageCollectionSetup; +} + +export interface ClientPluginsStart { + data: DataPublicPluginStart; + triggers_actions_ui: TriggersAndActionsUIPublicPluginSetup; +} + +export type ClientPluginDeps = ClientPluginsSetup & ClientPluginsStart; diff --git a/x-pack/plugins/infra/public/utils/apollo_client.ts b/x-pack/plugins/infra/public/utils/apollo_client.ts new file mode 100644 index 0000000000000..3c69ef4c98fac --- /dev/null +++ b/x-pack/plugins/infra/public/utils/apollo_client.ts @@ -0,0 +1,85 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory'; +import ApolloClient from 'apollo-client'; +import { ApolloLink } from 'apollo-link'; +import { createHttpLink } from 'apollo-link-http'; +import { withClientState } from 'apollo-link-state'; +import { HttpFetchOptions, HttpHandler } from 'src/core/public'; +import introspectionQueryResultData from '../graphql/introspection.json'; + +export const createApolloClient = (fetch: HttpHandler) => { + const cache = new InMemoryCache({ + addTypename: false, + fragmentMatcher: new IntrospectionFragmentMatcher({ + introspectionQueryResultData, + }), + }); + + const wrappedFetch = (path: string, options: HttpFetchOptions) => { + return new Promise(async (resolve, reject) => { + // core.http.fetch isn't 100% compatible with the Fetch API and will + // throw Errors on 401s. This top level try / catch handles those scenarios. + try { + fetch(path, { + ...options, + // Set headers to undefined due to this bug: https://github.com/apollographql/apollo-link/issues/249, + // Apollo will try to set a "content-type" header which will conflict with the "Content-Type" header that + // core.http.fetch correctly sets. + headers: undefined, + asResponse: true, + }).then((res) => { + if (!res.response) { + return reject(); + } + // core.http.fetch will parse the Response and set a body before handing it back. As such .text() / .json() + // will have already been called on the Response instance. However, Apollo will also want to call + // .text() / .json() on the instance, as it expects the raw Response instance, rather than core's wrapper. + // .text() / .json() can only be called once, and an Error will be thrown if those methods are accessed again. + // This hacks around that by setting up a new .text() method that will restringify the JSON response we already have. + // This does result in an extra stringify / parse cycle, which isn't ideal, but as we only have a few endpoints left using + // GraphQL this shouldn't create excessive overhead. + // Ref: https://github.com/apollographql/apollo-link/blob/master/packages/apollo-link-http/src/httpLink.ts#L134 + // and + // https://github.com/apollographql/apollo-link/blob/master/packages/apollo-link-http-common/src/index.ts#L125 + return resolve({ + ...res.response, + text: () => { + return new Promise(async (resolveText, rejectText) => { + if (res.body) { + return resolveText(JSON.stringify(res.body)); + } else { + return rejectText(); + } + }); + }, + }); + }); + } catch (error) { + reject(error); + } + }); + }; + + const HttpLink = createHttpLink({ + fetch: wrappedFetch, + uri: `/api/infra/graphql`, + }); + + const graphQLOptions = { + cache, + link: ApolloLink.from([ + withClientState({ + cache, + resolvers: {}, + }), + HttpLink, + ]), + }; + + return new ApolloClient(graphQLOptions); +}; diff --git a/x-pack/plugins/infra/public/utils/triggers_actions_context.tsx b/x-pack/plugins/infra/public/utils/triggers_actions_context.tsx index 1cff3663280fd..6b51714893a6d 100644 --- a/x-pack/plugins/infra/public/utils/triggers_actions_context.tsx +++ b/x-pack/plugins/infra/public/utils/triggers_actions_context.tsx @@ -5,10 +5,10 @@ */ import * as React from 'react'; -import { TriggersAndActionsUIPublicPluginSetup } from '../../../triggers_actions_ui/public'; +import { TriggersAndActionsUIPublicPluginStart } from '../../../triggers_actions_ui/public'; interface ContextProps { - triggersActionsUI: TriggersAndActionsUIPublicPluginSetup | null; + triggersActionsUI: TriggersAndActionsUIPublicPluginStart | null; } export const TriggerActionsContext = React.createContext({ @@ -16,7 +16,7 @@ export const TriggerActionsContext = React.createContext({ }); interface Props { - triggersActionsUI: TriggersAndActionsUIPublicPluginSetup; + triggersActionsUI: TriggersAndActionsUIPublicPluginStart; } export const TriggersActionsProvider: React.FC = (props) => { diff --git a/x-pack/plugins/infra/public/utils/use_url_state.ts b/x-pack/plugins/infra/public/utils/use_url_state.ts index 7a63b48fa9a1a..ab0ca1311194f 100644 --- a/x-pack/plugins/infra/public/utils/use_url_state.ts +++ b/x-pack/plugins/infra/public/utils/use_url_state.ts @@ -8,10 +8,9 @@ import { parse, stringify } from 'query-string'; import { Location } from 'history'; import { useCallback, useEffect, useMemo, useState } from 'react'; import { decode, encode, RisonValue } from 'rison-node'; +import { useHistory } from 'react-router-dom'; import { url } from '../../../../../src/plugins/kibana_utils/public'; -import { useHistory } from './history_context'; - export const useUrlState = ({ defaultState, decodeUrlState, diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts index a282a742d614c..00a1d97dec811 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts @@ -5,6 +5,7 @@ */ import { mapValues, first } from 'lodash'; import { i18n } from '@kbn/i18n'; +import moment from 'moment'; import { InfraDatabaseSearchResponse } from '../../adapters/framework/adapter_types'; import { createAfterKeyHandler } from '../../../utils/create_afterkey_handler'; import { getAllCompositeData } from '../../../utils/get_all_composite_data'; @@ -336,6 +337,7 @@ export const createMetricThresholdExecutor = (libs: InfraBackendLibs, alertId: s group, alertState: stateToAlertMessage[nextState], reason, + timestamp: moment().toISOString(), value: mapToConditionsLookup(alertResults, (result) => result[group].currentValue), threshold: mapToConditionsLookup(criteria, (c) => c.threshold), metric: mapToConditionsLookup(criteria, (c) => c.metric), diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/register_metric_threshold_alert_type.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/register_metric_threshold_alert_type.ts index 2c98a568d16de..02d9ca3e5f0c9 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/register_metric_threshold_alert_type.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/register_metric_threshold_alert_type.ts @@ -55,6 +55,13 @@ export function registerMetricThresholdAlertType(libs: InfraBackendLibs) { } ); + const timestampActionVariableDescription = i18n.translate( + 'xpack.infra.metrics.alerting.threshold.alerting.timestampDescription', + { + defaultMessage: 'A timestamp of when the alert was detected.', + } + ); + const valueActionVariableDescription = i18n.translate( 'xpack.infra.metrics.alerting.threshold.alerting.valueActionVariableDescription', { @@ -106,6 +113,7 @@ export function registerMetricThresholdAlertType(libs: InfraBackendLibs) { { name: 'group', description: groupActionVariableDescription }, { name: 'alertState', description: alertStateActionVariableDescription }, { name: 'reason', description: reasonActionVariableDescription }, + { name: 'timestamp', description: timestampActionVariableDescription }, { name: 'value', description: valueActionVariableDescription }, { name: 'metric', description: metricActionVariableDescription }, { name: 'threshold', description: thresholdActionVariableDescription }, diff --git a/x-pack/plugins/ingest_manager/common/openapi/spec_oas3.json b/x-pack/plugins/ingest_manager/common/openapi/spec_oas3.json new file mode 100644 index 0000000000000..f0ed3ed9a0364 --- /dev/null +++ b/x-pack/plugins/ingest_manager/common/openapi/spec_oas3.json @@ -0,0 +1,4397 @@ +{ + "openapi": "3.0.0", + "info": { + "title": "Ingest Manager", + "version": "0.2", + "contact": { + "name": "Ingest Team" + }, + "license": { + "name": "Elastic" + } + }, + "servers": [ + { + "url": "http://localhost:5601/api/ingest_manager", + "description": "local" + } + ], + "paths": { + "/agent_configs": { + "get": { + "summary": "Agent Config - List", + "tags": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AgentConfig" + } + }, + "total": { + "type": "number" + }, + "page": { + "type": "number" + }, + "perPage": { + "type": "number" + }, + "success": { + "type": "boolean" + } + }, + "required": [ + "items", + "total", + "page", + "perPage", + "success" + ] + }, + "examples": { + "success": { + "value": { + "items": [ + { + "id": "82da1fc0-8fbf-11ea-b2ce-01c4a6127154", + "name": "Default config", + "namespace": "default", + "description": "Default agent configuration created by Kibana", + "status": "active", + "datasources": [ + "8a5679b0-8fbf-11ea-b2ce-01c4a6127154" + ], + "is_default": true, + "monitoring_enabled": [ + "logs", + "metrics" + ], + "revision": 2, + "updated_on": "2020-05-06T17:32:21.905Z", + "updated_by": "system", + "agents": 0 + } + ], + "total": 1, + "page": 1, + "perPage": 50, + "success": true + } + } + } + } + } + } + }, + "operationId": "agent-config-list", + "parameters": [ + { + "$ref": "#/components/parameters/pageSizeParam" + }, + { + "$ref": "#/components/parameters/pageIndexParam" + }, + { + "$ref": "#/components/parameters/kueryParam" + } + ], + "description": "" + }, + "post": { + "summary": "Agent Config - Create", + "tags": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "item": { + "$ref": "#/components/schemas/AgentConfig" + }, + "success": { + "type": "boolean" + } + } + } + } + } + } + }, + "operationId": "post-agent_configs", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NewAgentConfig" + } + } + } + }, + "security": [], + "parameters": [ + { + "$ref": "#/components/parameters/xsrfHeader" + } + ] + } + }, + "/agent_configs/{agentConfigId}": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "name": "agentConfigId", + "in": "path", + "required": true + } + ], + "get": { + "summary": "Agent Config - Info", + "tags": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "item": { + "$ref": "#/components/schemas/AgentConfig" + }, + "success": { + "type": "boolean" + } + }, + "required": [ + "item", + "success" + ] + }, + "examples": { + "success": { + "value": { + "item": { + "id": "82da1fc0-8fbf-11ea-b2ce-01c4a6127154", + "name": "Default config", + "namespace": "default", + "description": "Default agent configuration created by Kibana", + "status": "active", + "datasources": [ + { + "id": "8a5679b0-8fbf-11ea-b2ce-01c4a6127154", + "name": "system-1", + "namespace": "default", + "package": { + "name": "system", + "title": "System", + "version": "0.0.3" + }, + "enabled": true, + "config_id": "82da1fc0-8fbf-11ea-b2ce-01c4a6127154", + "output_id": "08adc51c-69f3-4294-80e2-24527c6ff73d", + "inputs": [ + { + "type": "logs", + "enabled": true, + "streams": [ + { + "id": "logs-system.auth", + "enabled": true, + "dataset": "system.auth", + "vars": { + "paths": { + "value": [ + "/var/log/auth.log*", + "/var/log/secure*" + ], + "type": "text" + } + }, + "agent_stream": { + "paths": [ + "/var/log/auth.log*", + "/var/log/secure*" + ], + "exclude_files": [ + ".gz$" + ], + "multiline": { + "pattern": "^\\s", + "match": "after" + }, + "processors": [ + { + "add_locale": null + }, + { + "add_fields": { + "target": "", + "fields": { + "ecs.version": "1.5.0" + } + } + } + ] + } + }, + { + "id": "logs-system.syslog", + "enabled": true, + "dataset": "system.syslog", + "vars": { + "paths": { + "value": [ + "/var/log/messages*", + "/var/log/syslog*" + ], + "type": "text" + } + }, + "agent_stream": { + "paths": [ + "/var/log/messages*", + "/var/log/syslog*" + ], + "exclude_files": [ + ".gz$" + ], + "multiline": { + "pattern": "^\\s", + "match": "after" + }, + "processors": [ + { + "add_locale": null + }, + { + "add_fields": { + "target": "", + "fields": { + "ecs.version": "1.5.0" + } + } + } + ] + } + } + ] + }, + { + "type": "system/metrics", + "enabled": true, + "streams": [ + { + "id": "system/metrics-system.core", + "enabled": true, + "dataset": "system.core", + "vars": { + "core.metrics": { + "value": [ + "percentages" + ], + "type": "text" + } + }, + "agent_stream": { + "metricsets": [ + "core" + ], + "core.metrics": "percentages" + } + }, + { + "id": "system/metrics-system.cpu", + "enabled": true, + "dataset": "system.cpu", + "vars": { + "core.metrics": { + "value": [ + "percentages" + ], + "type": "text" + }, + "cpu.metrics": { + "value": [ + "percentages", + "normalized_percentages" + ], + "type": "text" + }, + "period": { + "value": "10s", + "type": "text" + }, + "process.include_top_n.by_cpu": { + "value": 5, + "type": "integer" + }, + "process.include_top_n.by_memory": { + "value": 5, + "type": "integer" + }, + "processes": { + "value": [ + ".*" + ], + "type": "text" + } + }, + "agent_stream": { + "metricsets": [ + "cpu" + ], + "core.metrics": "percentages", + "cpu.metrics": "percentages,normalized_percentages", + "period": "10s", + "process.include_top_n.by_cpu": 5, + "process.include_top_n.by_memory": 5, + "processes": ".*" + } + }, + { + "id": "system/metrics-system.diskio", + "enabled": true, + "dataset": "system.diskio", + "agent_stream": { + "metricsets": [ + "diskio" + ] + } + }, + { + "id": "system/metrics-system.entropy", + "enabled": true, + "dataset": "system.entropy", + "agent_stream": { + "metricsets": [ + "entropy" + ] + } + }, + { + "id": "system/metrics-system.filesystem", + "enabled": true, + "dataset": "system.filesystem", + "vars": { + "period": { + "value": "1m", + "type": "text" + }, + "processors": { + "value": "- drop_event.when.regexp:\n system.filesystem.mount_point: ^/(sys|cgroup|proc|dev|etc|host|lib|snap)($|/)\n", + "type": "yaml" + } + }, + "agent_stream": { + "metricsets": [ + "filesystem" + ], + "period": "1m", + "processors": [ + { + "drop_event.when.regexp": { + "system.filesystem.mount_point": "^/(sys|cgroup|proc|dev|etc|host|lib|snap)($|/)" + } + } + ] + } + }, + { + "id": "system/metrics-system.fsstat", + "enabled": true, + "dataset": "system.fsstat", + "vars": { + "period": { + "value": "1m", + "type": "text" + }, + "processors": { + "value": "- drop_event.when.regexp:\n system.filesystem.mount_point: ^/(sys|cgroup|proc|dev|etc|host|lib|snap)($|/)\n", + "type": "yaml" + } + }, + "agent_stream": { + "metricsets": [ + "fsstat" + ], + "period": "1m", + "processors": [ + { + "drop_event.when.regexp": { + "system.filesystem.mount_point": "^/(sys|cgroup|proc|dev|etc|host|lib|snap)($|/)" + } + } + ] + } + }, + { + "id": "system/metrics-system.load", + "enabled": true, + "dataset": "system.load", + "vars": { + "core.metrics": { + "value": [ + "percentages" + ], + "type": "text" + }, + "cpu.metrics": { + "value": [ + "percentages", + "normalized_percentages" + ], + "type": "text" + }, + "period": { + "value": "10s", + "type": "text" + }, + "process.include_top_n.by_cpu": { + "value": 5, + "type": "integer" + }, + "process.include_top_n.by_memory": { + "value": 5, + "type": "integer" + }, + "processes": { + "value": [ + ".*" + ], + "type": "text" + } + }, + "agent_stream": { + "metricsets": [ + "load" + ], + "core.metrics": "percentages", + "cpu.metrics": "percentages,normalized_percentages", + "period": "10s", + "process.include_top_n.by_cpu": 5, + "process.include_top_n.by_memory": 5, + "processes": ".*" + } + }, + { + "id": "system/metrics-system.memory", + "enabled": true, + "dataset": "system.memory", + "vars": { + "core.metrics": { + "value": [ + "percentages" + ], + "type": "text" + }, + "cpu.metrics": { + "value": [ + "percentages", + "normalized_percentages" + ], + "type": "text" + }, + "period": { + "value": "10s", + "type": "text" + }, + "process.include_top_n.by_cpu": { + "value": 5, + "type": "integer" + }, + "process.include_top_n.by_memory": { + "value": 5, + "type": "integer" + }, + "processes": { + "value": [ + ".*" + ], + "type": "text" + } + }, + "agent_stream": { + "metricsets": [ + "memory" + ], + "core.metrics": "percentages", + "cpu.metrics": "percentages,normalized_percentages", + "period": "10s", + "process.include_top_n.by_cpu": 5, + "process.include_top_n.by_memory": 5, + "processes": ".*" + } + }, + { + "id": "system/metrics-system.network", + "enabled": true, + "dataset": "system.network", + "vars": { + "core.metrics": { + "value": [ + "percentages" + ], + "type": "text" + }, + "cpu.metrics": { + "value": [ + "percentages", + "normalized_percentages" + ], + "type": "text" + }, + "period": { + "value": "10s", + "type": "text" + }, + "process.include_top_n.by_cpu": { + "value": 5, + "type": "integer" + }, + "process.include_top_n.by_memory": { + "value": 5, + "type": "integer" + }, + "processes": { + "value": [ + ".*" + ], + "type": "text" + } + }, + "agent_stream": { + "metricsets": [ + "network" + ], + "core.metrics": "percentages", + "cpu.metrics": "percentages,normalized_percentages", + "period": "10s", + "process.include_top_n.by_cpu": 5, + "process.include_top_n.by_memory": 5, + "processes": ".*" + } + }, + { + "id": "system/metrics-system.network_summary", + "enabled": true, + "dataset": "system.network_summary", + "agent_stream": { + "metricsets": [ + "network_summary" + ] + } + }, + { + "id": "system/metrics-system.process", + "enabled": true, + "dataset": "system.process", + "vars": { + "core.metrics": { + "value": [ + "percentages" + ], + "type": "text" + }, + "cpu.metrics": { + "value": [ + "percentages", + "normalized_percentages" + ], + "type": "text" + }, + "period": { + "value": "10s", + "type": "text" + }, + "process.include_top_n.by_cpu": { + "value": 5, + "type": "integer" + }, + "process.include_top_n.by_memory": { + "value": 5, + "type": "integer" + }, + "processes": { + "value": [ + ".*" + ], + "type": "text" + } + }, + "agent_stream": { + "metricsets": [ + "process" + ], + "core.metrics": "percentages", + "cpu.metrics": "percentages,normalized_percentages", + "period": "10s", + "process.include_top_n.by_cpu": 5, + "process.include_top_n.by_memory": 5, + "processes": ".*" + } + }, + { + "id": "system/metrics-system.process_summary", + "enabled": true, + "dataset": "system.process_summary", + "vars": { + "core.metrics": { + "value": [ + "percentages" + ], + "type": "text" + }, + "cpu.metrics": { + "value": [ + "percentages", + "normalized_percentages" + ], + "type": "text" + }, + "period": { + "value": "10s", + "type": "text" + }, + "process.include_top_n.by_cpu": { + "value": 5, + "type": "integer" + }, + "process.include_top_n.by_memory": { + "value": 5, + "type": "integer" + }, + "processes": { + "value": [ + ".*" + ], + "type": "text" + } + }, + "agent_stream": { + "metricsets": [ + "process_summary" + ], + "core.metrics": "percentages", + "cpu.metrics": "percentages,normalized_percentages", + "period": "10s", + "process.include_top_n.by_cpu": 5, + "process.include_top_n.by_memory": 5, + "processes": ".*" + } + }, + { + "id": "system/metrics-system.raid", + "enabled": true, + "dataset": "system.raid", + "agent_stream": { + "metricsets": [ + "raid" + ] + } + }, + { + "id": "system/metrics-system.service", + "enabled": true, + "dataset": "system.service", + "agent_stream": { + "metricsets": [ + "service" + ] + } + }, + { + "id": "system/metrics-system.socket", + "enabled": true, + "dataset": "system.socket", + "agent_stream": { + "metricsets": [ + "socket" + ] + } + }, + { + "id": "system/metrics-system.socket_summary", + "enabled": true, + "dataset": "system.socket_summary", + "vars": { + "core.metrics": { + "value": [ + "percentages" + ], + "type": "text" + }, + "cpu.metrics": { + "value": [ + "percentages", + "normalized_percentages" + ], + "type": "text" + }, + "period": { + "value": "10s", + "type": "text" + }, + "process.include_top_n.by_cpu": { + "value": 5, + "type": "integer" + }, + "process.include_top_n.by_memory": { + "value": 5, + "type": "integer" + }, + "processes": { + "value": [ + ".*" + ], + "type": "text" + } + }, + "agent_stream": { + "metricsets": [ + "socket_summary" + ], + "core.metrics": "percentages", + "cpu.metrics": "percentages,normalized_percentages", + "period": "10s", + "process.include_top_n.by_cpu": 5, + "process.include_top_n.by_memory": 5, + "processes": ".*" + } + }, + { + "id": "system/metrics-system.uptime", + "enabled": true, + "dataset": "system.uptime", + "vars": { + "core.metrics": { + "value": [ + "percentages" + ], + "type": "text" + }, + "cpu.metrics": { + "value": [ + "percentages", + "normalized_percentages" + ], + "type": "text" + }, + "period": { + "value": "10s", + "type": "text" + }, + "processes": { + "value": [ + ".*" + ], + "type": "text" + } + }, + "agent_stream": { + "metricsets": [ + "uptime" + ], + "core.metrics": "percentages", + "cpu.metrics": "percentages,normalized_percentages", + "period": "10s", + "processes": ".*" + } + }, + { + "id": "system/metrics-system.users", + "enabled": true, + "dataset": "system.users", + "agent_stream": { + "metricsets": [ + "users" + ] + } + } + ] + } + ], + "revision": 1 + } + ], + "is_default": true, + "monitoring_enabled": [ + "logs", + "metrics" + ], + "revision": 2, + "updated_on": "2020-05-06T17:32:21.905Z", + "updated_by": "system" + }, + "success": true + } + } + } + } + } + } + }, + "operationId": "agent-config-info", + "description": "Get one agent config", + "parameters": [] + }, + "put": { + "summary": "Agent Config - Update", + "tags": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "item": { + "$ref": "#/components/schemas/AgentConfig" + }, + "success": { + "type": "boolean" + } + }, + "required": [ + "item", + "success" + ] + }, + "examples": { + "example-1": { + "value": { + "item": { + "id": "0b7130d0-5a37-11ea-ac2c-25e9ab4ecb2a", + "name": "UPDATED name", + "description": "UPDATED description", + "namespace": "UPDATED namespace", + "updated_on": "Fri Feb 28 2020 16:22:31 GMT-0500 (Eastern Standard Time)", + "updated_by": "elastic", + "datasources": [] + }, + "success": true + } + } + } + } + } + } + }, + "operationId": "put-agent_configs-agentConfigId", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NewAgentConfig" + }, + "examples": { + "example-1": { + "value": { + "name": "UPDATED name", + "description": "UPDATED description", + "namespace": "UPDATED namespace" + } + } + } + } + } + }, + "parameters": [ + { + "$ref": "#/components/parameters/xsrfHeader" + } + ] + } + }, + "/agent_configs/delete": { + "post": { + "summary": "Agent Config - Delete", + "operationId": "post-agent_config-delete", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "success": { + "type": "boolean" + } + }, + "required": [ + "id", + "success" + ] + } + }, + "examples": { + "success": { + "value": [ + { + "id": "df7d2540-5a47-11ea-80da-89b5a66da347", + "success": true + } + ] + }, + "fail": { + "value": [ + { + "id": "df7d2540-5a47-11ea-80da-89b5a66da347", + "success": false + } + ] + } + } + } + } + } + }, + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "agentConfigIds": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "examples": { + "example-1": { + "value": { + "agentConfigIds": [ + "df7d2540-5a47-11ea-80da-89b5a66da347" + ] + } + } + } + } + } + }, + "parameters": [ + { + "$ref": "#/components/parameters/xsrfHeader" + } + ] + }, + "parameters": [] + }, + "/datasources": { + "get": { + "summary": "Datasources - List", + "tags": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Datasource" + } + }, + "total": { + "type": "number" + }, + "page": { + "type": "number" + }, + "perPage": { + "type": "number" + }, + "success": { + "type": "boolean" + } + }, + "required": [ + "items", + "success" + ] + }, + "examples": { + "example-1": { + "value": { + "items": [ + { + "id": "5d273cf0-5a44-11ea-80da-89b5a66da347", + "use_output": "default", + "inputs": [ + { + "type": "docker/metrics", + "streams": [ + { + "metricset": "status", + "dataset": "docker.status" + } + ] + }, + { + "type": "logs", + "streams": [ + { + "paths": [ + "/var/log/hello1.log", + "/var/log/hello2.log" + ] + } + ] + } + ] + }, + { + "id": "66490980-5a44-11ea-80da-89b5a66da347", + "namespace": "testing", + "use_output": "default", + "inputs": [ + { + "type": "apache/metrics", + "streams": [ + { + "enabled": true, + "metricset": "info" + } + ] + } + ] + }, + { + "id": "df1ccae0-5a49-11ea-94a6-81affd263f47", + "enabled": true, + "title": "This is a nice title for human", + "package": { + "name": "epm/nginx", + "version": "1.7.0" + }, + "namespace": "prod", + "use_output": "long_term_storage", + "inputs": [ + { + "type": "logs", + "streams": [ + { + "enabled": true, + "dataset": "nginx.acccess", + "paths": [ + "/var/log/nginx/access.log" + ] + }, + { + "enabled": true, + "dataset": "nginx.error", + "paths": [ + "/var/log/nginx/error.log" + ] + } + ] + }, + { + "type": "nginx/metrics", + "streams": [ + { + "id": "id string", + "enabled": true, + "dataset": "nginx.stub_status", + "metricset": "stub_status" + } + ] + } + ] + }, + { + "id": "f96a09d0-5a49-11ea-94a6-81affd263f47", + "enabled": true, + "title": "This is a nice title for human", + "package": { + "name": "epm/nginx", + "version": "1.7.0" + }, + "namespace": "prod", + "use_output": "long_term_storage", + "inputs": [ + { + "type": "logs", + "streams": [ + { + "enabled": true, + "dataset": "nginx.acccess", + "paths": [ + "/var/log/nginx/access.log" + ] + }, + { + "enabled": true, + "dataset": "nginx.error", + "paths": [ + "/var/log/nginx/error.log" + ] + } + ] + }, + { + "type": "nginx/metrics", + "streams": [ + { + "id": "id string", + "enabled": true, + "dataset": "nginx.stub_status", + "metricset": "stub_status" + } + ] + } + ] + }, + { + "id": "9ca403a0-5a66-11ea-9468-c911a41ab4f5", + "enabled": true, + "title": "This is a nice title for human", + "package": { + "name": "epm/nginx", + "version": "1.7.0" + }, + "namespace": "prod", + "use_output": "long_term_storage", + "inputs": [ + { + "type": "logs", + "streams": [ + { + "enabled": true, + "dataset": "nginx.acccess", + "paths": [ + "/var/log/nginx/access.log" + ] + }, + { + "enabled": true, + "dataset": "nginx.error", + "paths": [ + "/var/log/nginx/error.log" + ] + } + ] + }, + { + "type": "nginx/metrics", + "streams": [ + { + "id": "id string", + "enabled": true, + "dataset": "nginx.stub_status", + "metricset": "stub_status" + } + ] + } + ] + }, + { + "id": "27925980-5a44-11ea-80da-89b5a66da347", + "enabled": true, + "title": "UPDATED title for human", + "package": { + "name": "epm/nginx", + "version": "1.7.0" + }, + "namespace": "prod", + "use_output": "long_term_storage", + "inputs": [ + { + "streams": [ + { + "paths": [ + "/var/log/nginx/access.log" + ], + "dataset": "nginx.acccess", + "enabled": true + }, + { + "paths": [ + "/var/log/nginx/error.log" + ], + "dataset": "nginx.error", + "enabled": true + } + ], + "type": "logs" + }, + { + "streams": [ + { + "metricset": "stub_status", + "id": "id string", + "dataset": "nginx.stub_status", + "enabled": true + } + ], + "type": "nginx/metrics" + } + ] + } + ], + "total": 6, + "page": 1, + "perPage": 20, + "success": true + } + } + } + } + } + } + }, + "operationId": "get-datasources", + "security": [], + "parameters": [] + }, + "parameters": [], + "post": { + "summary": "Datasources - Create", + "operationId": "post-datasources", + "responses": { + "200": { + "description": "OK" + } + }, + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NewDatasource" + }, + "examples": { + "example-1": { + "value": { + "enabled": true, + "title": "This is a nice title for human", + "package": { + "name": "epm/nginx", + "version": "1.7.0" + }, + "namespace": "prod", + "use_output": "long_term_storage", + "inputs": [ + { + "type": "logs", + "streams": [ + { + "enabled": true, + "dataset": "nginx.acccess", + "paths": [ + "/var/log/nginx/access.log" + ] + }, + { + "enabled": true, + "dataset": "nginx.error", + "paths": [ + "/var/log/nginx/error.log" + ] + } + ] + }, + { + "type": "nginx/metrics", + "streams": [ + { + "id": "id string", + "enabled": true, + "dataset": "nginx.stub_status", + "metricset": "stub_status" + } + ] + } + ] + } + } + } + } + } + }, + "parameters": [ + { + "$ref": "#/components/parameters/xsrfHeader" + } + ] + } + }, + "/datasources/{datasourceId}": { + "get": { + "summary": "Datasources - Info", + "tags": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "item": { + "$ref": "#/components/schemas/Datasource" + }, + "success": { + "type": "boolean" + } + }, + "required": [ + "item", + "success" + ] + } + } + } + } + }, + "operationId": "get-datasources-datasourceId" + }, + "parameters": [ + { + "schema": { + "type": "string" + }, + "name": "datasourceId", + "in": "path", + "required": true + } + ], + "put": { + "summary": "Datasources - Update", + "operationId": "put-datasources-datasourceId", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "item": { + "$ref": "#/components/schemas/Datasource" + }, + "sucess": { + "type": "boolean" + } + }, + "required": [ + "item", + "sucess" + ] + } + } + } + } + }, + "parameters": [ + { + "$ref": "#/components/parameters/xsrfHeader" + } + ] + } + }, + "/fleet/setup": { + "get": { + "summary": "Fleet setup - Info", + "tags": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "isInitialized": { + "type": "boolean" + } + }, + "required": [ + "isInitialized" + ] + }, + "examples": { + "success": { + "value": { + "isInitialized": true + } + }, + "failure": { + "value": { + "isInitialized": false + } + } + } + } + } + } + }, + "operationId": "get-fleet-setup", + "security": [ + { + "basicAuth": [] + } + ] + }, + "post": { + "summary": "Fleet setup - Create", + "operationId": "post-fleet-setup", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "isInitialized": { + "type": "boolean" + } + }, + "required": [ + "isInitialized" + ] + }, + "examples": { + "success": { + "value": { + "isInitialized": true + } + } + } + } + } + } + }, + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "admin_username": { + "type": "string" + }, + "admin_password": { + "type": "string" + } + }, + "required": [ + "admin_username", + "admin_password" + ] + } + } + } + }, + "parameters": [ + { + "$ref": "#/components/parameters/xsrfHeader" + } + ] + } + }, + "/epm/packages/{pkgkey}": { + "get": { + "summary": "EPM - Packages - Info", + "tags": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "allOf": [ + { + "properties": { + "response": { + "$ref": "#/components/schemas/PackageInfo" + }, + "success": { + "type": "boolean" + } + } + }, + { + "properties": { + "status": { + "type": "string", + "enum": [ + "installed", + "not_installed" + ] + }, + "savedObject": { + "type": "string" + } + }, + "required": [ + "status", + "savedObject" + ] + } + ] + }, + "examples": { + "example-1": { + "value": { + "response": { + "name": "coredns", + "title": "CoreDNS", + "version": "1.0.1", + "readme": "/package/coredns-1.0.1/docs/README.md", + "description": "CoreDNS logs and metrics integration.\nThe CoreDNS integrations allows to gather logs and metrics from the CoreDNS DNS server to get better insights.\n", + "type": "integration", + "categories": [ + "logs", + "metrics" + ], + "requirement": { + "kibana": { + "versions": ">6.7.0" + } + }, + "icons": [ + { + "src": "/package/coredns-1.0.1/img/icon.png", + "size": "1800x1800" + }, + { + "src": "/package/coredns-1.0.1/img/icon.svg", + "size": "255x144", + "type": "image/svg+xml" + } + ], + "assets": { + "kibana": { + "dashboard": [ + { + "pkgkey": "coredns-1.0.1", + "service": "kibana", + "type": "dashboard", + "file": "53aa1f70-443e-11e9-8548-ab7fbe04f038.json", + "path": "coredns-1.0.1/kibana/dashboard/53aa1f70-443e-11e9-8548-ab7fbe04f038.json" + }, + { + "pkgkey": "coredns-1.0.1", + "service": "kibana", + "type": "dashboard", + "file": "Metricbeat-CoreDNS-Dashboard-ecs.json", + "path": "coredns-1.0.1/kibana/dashboard/Metricbeat-CoreDNS-Dashboard-ecs.json" + } + ], + "visualization": [ + { + "pkgkey": "coredns-1.0.1", + "service": "kibana", + "type": "visualization", + "file": "277fc650-67a9-11e9-a534-715561d0bf42.json", + "path": "coredns-1.0.1/kibana/visualization/277fc650-67a9-11e9-a534-715561d0bf42.json" + }, + { + "pkgkey": "coredns-1.0.1", + "service": "kibana", + "type": "visualization", + "file": "27da53f0-53d5-11e9-b466-9be470bbd327-ecs.json", + "path": "coredns-1.0.1/kibana/visualization/27da53f0-53d5-11e9-b466-9be470bbd327-ecs.json" + }, + { + "pkgkey": "coredns-1.0.1", + "service": "kibana", + "type": "visualization", + "file": "36e08510-53c4-11e9-b466-9be470bbd327-ecs.json", + "path": "coredns-1.0.1/kibana/visualization/36e08510-53c4-11e9-b466-9be470bbd327-ecs.json" + }, + { + "pkgkey": "coredns-1.0.1", + "service": "kibana", + "type": "visualization", + "file": "3ad75810-4429-11e9-8548-ab7fbe04f038.json", + "path": "coredns-1.0.1/kibana/visualization/3ad75810-4429-11e9-8548-ab7fbe04f038.json" + }, + { + "pkgkey": "coredns-1.0.1", + "service": "kibana", + "type": "visualization", + "file": "4804eaa0-7315-11e9-b0d0-414c3011ddbb.json", + "path": "coredns-1.0.1/kibana/visualization/4804eaa0-7315-11e9-b0d0-414c3011ddbb.json" + }, + { + "pkgkey": "coredns-1.0.1", + "service": "kibana", + "type": "visualization", + "file": "57c74300-7308-11e9-b0d0-414c3011ddbb.json", + "path": "coredns-1.0.1/kibana/visualization/57c74300-7308-11e9-b0d0-414c3011ddbb.json" + }, + { + "pkgkey": "coredns-1.0.1", + "service": "kibana", + "type": "visualization", + "file": "75743f70-443c-11e9-8548-ab7fbe04f038.json", + "path": "coredns-1.0.1/kibana/visualization/75743f70-443c-11e9-8548-ab7fbe04f038.json" + }, + { + "pkgkey": "coredns-1.0.1", + "service": "kibana", + "type": "visualization", + "file": "86177430-728d-11e9-b0d0-414c3011ddbb.json", + "path": "coredns-1.0.1/kibana/visualization/86177430-728d-11e9-b0d0-414c3011ddbb.json" + }, + { + "pkgkey": "coredns-1.0.1", + "service": "kibana", + "type": "visualization", + "file": "9dc640e0-4432-11e9-8548-ab7fbe04f038.json", + "path": "coredns-1.0.1/kibana/visualization/9dc640e0-4432-11e9-8548-ab7fbe04f038.json" + }, + { + "pkgkey": "coredns-1.0.1", + "service": "kibana", + "type": "visualization", + "file": "a19df590-53c4-11e9-b466-9be470bbd327-ecs.json", + "path": "coredns-1.0.1/kibana/visualization/a19df590-53c4-11e9-b466-9be470bbd327-ecs.json" + }, + { + "pkgkey": "coredns-1.0.1", + "service": "kibana", + "type": "visualization", + "file": "a58345f0-7298-11e9-b0d0-414c3011ddbb.json", + "path": "coredns-1.0.1/kibana/visualization/a58345f0-7298-11e9-b0d0-414c3011ddbb.json" + }, + { + "pkgkey": "coredns-1.0.1", + "service": "kibana", + "type": "visualization", + "file": "cfde7fb0-443d-11e9-8548-ab7fbe04f038.json", + "path": "coredns-1.0.1/kibana/visualization/cfde7fb0-443d-11e9-8548-ab7fbe04f038.json" + } + ] + } + }, + "format_version": "1.0.0", + "datasets": [ + { + "title": "CoreDNS logs", + "name": "log", + "release": "ga", + "type": "logs", + "ingest_pipeline": "pipeline-entry", + "vars": [ + { + "default": [ + "/var/log/coredns.log" + ], + "name": "paths", + "type": "textarea" + }, + { + "default": [ + "coredns" + ], + "name": "tags", + "type": "text" + } + ], + "package": "coredns" + }, + { + "title": "CoreDNS stats metrics", + "name": "stats", + "release": "ga", + "type": "metrics", + "vars": [ + { + "default": [ + "http://localhost:9153" + ], + "description": "CoreDNS hosts", + "name": "hosts", + "required": true + }, + { + "default": "10s", + "description": "Collection period. Valid values: 10s, 5m, 2h", + "name": "period" + }, + { + "name": "username", + "type": "text" + }, + { + "name": "password", + "type": "password" + } + ], + "package": "coredns" + } + ], + "download": "/epr/coredns/coredns-1.0.1.tar.gz", + "path": "/package/coredns-1.0.1", + "status": "installed", + "savedObject": { + "id": "coredns-1.0.1", + "type": "epm-package", + "updated_at": "2020-02-27T16:25:43.652Z", + "version": "WzU2LDFd", + "attributes": { + "installed": [ + { + "id": "53aa1f70-443e-11e9-8548-ab7fbe04f038", + "type": "dashboard" + }, + { + "id": "Metricbeat-CoreDNS-Dashboard-ecs", + "type": "dashboard" + }, + { + "id": "75743f70-443c-11e9-8548-ab7fbe04f038", + "type": "visualization" + }, + { + "id": "36e08510-53c4-11e9-b466-9be470bbd327-ecs", + "type": "visualization" + }, + { + "id": "277fc650-67a9-11e9-a534-715561d0bf42", + "type": "visualization" + }, + { + "id": "cfde7fb0-443d-11e9-8548-ab7fbe04f038", + "type": "visualization" + }, + { + "id": "a19df590-53c4-11e9-b466-9be470bbd327-ecs", + "type": "visualization" + }, + { + "id": "a58345f0-7298-11e9-b0d0-414c3011ddbb", + "type": "visualization" + }, + { + "id": "9dc640e0-4432-11e9-8548-ab7fbe04f038", + "type": "visualization" + }, + { + "id": "3ad75810-4429-11e9-8548-ab7fbe04f038", + "type": "visualization" + }, + { + "id": "57c74300-7308-11e9-b0d0-414c3011ddbb", + "type": "visualization" + }, + { + "id": "27da53f0-53d5-11e9-b466-9be470bbd327-ecs", + "type": "visualization" + }, + { + "id": "86177430-728d-11e9-b0d0-414c3011ddbb", + "type": "visualization" + }, + { + "id": "4804eaa0-7315-11e9-b0d0-414c3011ddbb", + "type": "visualization" + }, + { + "id": "logs-log-1.0.1-pipeline-plaintext", + "type": "ingest-pipeline" + }, + { + "id": "logs-log-1.0.1-pipeline-json", + "type": "ingest-pipeline" + }, + { + "id": "logs-log-1.0.1", + "type": "ingest-pipeline" + }, + { + "id": "logs-log", + "type": "index-template" + }, + { + "id": "metrics-stats", + "type": "index-template" + } + ] + }, + "references": [] + } + }, + "success": true + } + } + } + } + } + } + }, + "operationId": "get-epm-package-pkgkey", + "security": [ + { + "basicAuth": [] + } + ] + }, + "parameters": [ + { + "schema": { + "type": "string" + }, + "name": "pkgkey", + "in": "path", + "required": true + } + ], + "post": { + "summary": "EPM - Packages - Install", + "tags": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "response": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "required": [ + "id", + "type" + ] + } + }, + "success": { + "type": "boolean" + } + }, + "required": [ + "response", + "success" + ] + } + } + } + } + }, + "operationId": "post-epm-install-pkgkey", + "description": "", + "parameters": [ + { + "$ref": "#/components/parameters/xsrfHeader" + } + ] + }, + "delete": { + "summary": "EPM - Packages - Delete", + "tags": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "response": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "required": [ + "id", + "type" + ] + } + }, + "success": { + "type": "boolean" + } + }, + "required": [ + "response", + "success" + ] + } + } + } + } + }, + "operationId": "post-epm-delete-pkgkey", + "parameters": [ + { + "$ref": "#/components/parameters/xsrfHeader" + } + ] + } + }, + "/epm/packages": { + "get": { + "summary": "EPM - Packages - List", + "tags": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SearchResult" + } + }, + "examples": { + "success": { + "value": { + "response": [ + { + "description": "aws Integration", + "download": "/epr/aws/aws-0.0.3.tar.gz", + "icons": [ + { + "src": "/package/aws/0.0.3/img/logo_aws.svg", + "title": "logo aws", + "size": "32x32", + "type": "image/svg+xml" + } + ], + "name": "aws", + "path": "/package/aws/0.0.3", + "title": "aws", + "type": "integration", + "version": "0.0.3", + "status": "not_installed" + }, + { + "description": "This is the Elastic Endpoint package.", + "download": "/epr/endpoint/endpoint-0.1.0.tar.gz", + "icons": [ + { + "src": "/package/endpoint/0.1.0/img/logo-endpoint-64-color.svg", + "size": "16x16", + "type": "image/svg+xml" + } + ], + "name": "endpoint", + "path": "/package/endpoint/0.1.0", + "title": "Elastic Endpoint", + "type": "solution", + "version": "0.1.0", + "status": "installed", + "savedObject": { + "type": "epm-packages", + "id": "endpoint", + "attributes": { + "installed": [ + { + "id": "826759f0-7074-11ea-9bc8-6b38f4d29a16", + "type": "dashboard" + }, + { + "id": "55387750-729c-11ea-9bc8-6b38f4d29a16", + "type": "visualization" + }, + { + "id": "92b1edc0-706a-11ea-9bc8-6b38f4d29a16", + "type": "visualization" + }, + { + "id": "1cfceda0-728b-11ea-9bc8-6b38f4d29a16", + "type": "visualization" + }, + { + "id": "1e525190-7074-11ea-9bc8-6b38f4d29a16", + "type": "visualization" + }, + { + "id": "a3a3bd10-706b-11ea-9bc8-6b38f4d29a16", + "type": "map" + }, + { + "id": "events-endpoint", + "type": "index-template" + }, + { + "id": "metrics-endpoint", + "type": "index-template" + } + ], + "es_index_patterns": { + "events": "events-endpoint-*", + "metadata": "metrics-endpoint-*" + }, + "name": "endpoint", + "version": "0.1.0", + "internal": false, + "removable": false + }, + "references": [], + "updated_at": "2020-05-15T20:08:11.739Z", + "version": "WzEwOCwxXQ==" + } + }, + { + "description": "The log package should be used to create data sources for all type of logs for which an package doesn't exist yet.\n", + "download": "/epr/log/log-0.9.0.tar.gz", + "icons": [ + { + "src": "/package/log/0.9.0/img/icon.svg", + "type": "image/svg+xml" + } + ], + "name": "log", + "path": "/package/log/0.9.0", + "title": "Log Package", + "type": "integration", + "version": "0.9.0", + "status": "not_installed" + }, + { + "description": "This integration contains pretty long documentation.\nIt is used to show the different visualisations inside a documentation to test how we handle it.\nThe integration does not contain any assets except the documentation page.\n", + "download": "/epr/longdocs/longdocs-1.0.4.tar.gz", + "icons": [ + { + "src": "/package/longdocs/1.0.4/img/icon.svg", + "type": "image/svg+xml" + } + ], + "name": "longdocs", + "path": "/package/longdocs/1.0.4", + "title": "Long Docs", + "type": "integration", + "version": "1.0.4", + "status": "not_installed" + }, + { + "description": "This is an integration with only the metrics category.\n", + "download": "/epr/metricsonly/metricsonly-2.0.1.tar.gz", + "icons": [ + { + "src": "/package/metricsonly/2.0.1/img/icon.svg", + "type": "image/svg+xml" + } + ], + "name": "metricsonly", + "path": "/package/metricsonly/2.0.1", + "title": "Metrics Only", + "type": "integration", + "version": "2.0.1", + "status": "not_installed" + }, + { + "description": "Multiple versions of this integration exist.\n", + "download": "/epr/multiversion/multiversion-1.1.0.tar.gz", + "icons": [ + { + "src": "/package/multiversion/1.1.0/img/icon.svg", + "type": "image/svg+xml" + } + ], + "name": "multiversion", + "path": "/package/multiversion/1.1.0", + "title": "Multi Version", + "type": "integration", + "version": "1.1.0", + "status": "not_installed" + }, + { + "description": "MySQL Integration", + "download": "/epr/mysql/mysql-0.1.0.tar.gz", + "icons": [ + { + "src": "/package/mysql/0.1.0/img/logo_mysql.svg", + "title": "logo mysql", + "size": "32x32", + "type": "image/svg+xml" + } + ], + "name": "mysql", + "path": "/package/mysql/0.1.0", + "title": "MySQL", + "type": "integration", + "version": "0.1.0", + "status": "not_installed" + }, + { + "description": "Nginx Integration", + "download": "/epr/nginx/nginx-0.1.0.tar.gz", + "icons": [ + { + "src": "/package/nginx/0.1.0/img/logo_nginx.svg", + "title": "logo nginx", + "size": "32x32", + "type": "image/svg+xml" + } + ], + "name": "nginx", + "path": "/package/nginx/0.1.0", + "title": "Nginx", + "type": "integration", + "version": "0.1.0", + "status": "not_installed" + }, + { + "description": "Redis Integration", + "download": "/epr/redis/redis-0.1.0.tar.gz", + "icons": [ + { + "src": "/package/redis/0.1.0/img/logo_redis.svg", + "title": "logo redis", + "size": "32x32", + "type": "image/svg+xml" + } + ], + "name": "redis", + "path": "/package/redis/0.1.0", + "title": "Redis", + "type": "integration", + "version": "0.1.0", + "status": "not_installed" + }, + { + "description": "This package is used for defining all the properties of a package, the possible assets etc. It serves as a reference on all the config options which are possible.\n", + "download": "/epr/reference/reference-1.0.0.tar.gz", + "icons": [ + { + "src": "/package/reference/1.0.0/img/icon.svg", + "size": "32x32", + "type": "image/svg+xml" + } + ], + "name": "reference", + "path": "/package/reference/1.0.0", + "title": "Reference package", + "type": "integration", + "version": "1.0.0", + "status": "not_installed" + }, + { + "description": "System Integration", + "download": "/epr/system/system-0.1.0.tar.gz", + "icons": [ + { + "src": "/package/system/0.1.0/img/system.svg", + "title": "system", + "size": "1000x1000", + "type": "image/svg+xml" + } + ], + "name": "system", + "path": "/package/system/0.1.0", + "title": "System", + "type": "integration", + "version": "0.1.0", + "status": "installed", + "savedObject": { + "type": "epm-packages", + "id": "system", + "attributes": { + "installed": [ + { + "id": "c431f410-f9ac-11e9-90e8-1fb18e796788", + "type": "dashboard" + }, + { + "id": "Metricbeat-system-overview-ecs", + "type": "dashboard" + }, + { + "id": "277876d0-fa2c-11e6-bbd3-29c986c96e5a-ecs", + "type": "dashboard" + }, + { + "id": "0d3f2380-fa78-11e6-ae9b-81e5311e8cab-ecs", + "type": "dashboard" + }, + { + "id": "CPU-slash-Memory-per-container-ecs", + "type": "dashboard" + }, + { + "id": "79ffd6e0-faa0-11e6-947f-177f697178b8-ecs", + "type": "dashboard" + }, + { + "id": "Filebeat-syslog-dashboard-ecs", + "type": "dashboard" + }, + { + "id": "5517a150-f9ce-11e6-8115-a7c18106d86a-ecs", + "type": "dashboard" + }, + { + "id": "9c69cad0-f9b0-11e9-90e8-1fb18e796788", + "type": "visualization" + }, + { + "id": "855899e0-1b1c-11e7-b09e-037021c4f8df-ecs", + "type": "visualization" + }, + { + "id": "a30871f0-f98f-11e9-90e8-1fb18e796788", + "type": "visualization" + }, + { + "id": "e121b140-fa78-11e6-a1df-a78bd7504d38-ecs", + "type": "visualization" + }, + { + "id": "f398d2f0-fa77-11e6-ae9b-81e5311e8cab-ecs", + "type": "visualization" + }, + { + "id": "c5e3cf90-4d60-11e7-9a4c-ed99bbcaa42b-ecs", + "type": "visualization" + }, + { + "id": "d3166e80-1b91-11e7-bec4-a5e9ec5cab8b-ecs", + "type": "visualization" + }, + { + "id": "346bb290-fa80-11e6-a1df-a78bd7504d38-ecs", + "type": "visualization" + }, + { + "id": "Container-Block-IO-ecs", + "type": "visualization" + }, + { + "id": "590a60f0-5d87-11e7-8884-1bb4c3b890e4-ecs", + "type": "visualization" + }, + { + "id": "341ffe70-f9ce-11e6-8115-a7c18106d86a-ecs", + "type": "visualization" + }, + { + "id": "System-Navigation-ecs", + "type": "visualization" + }, + { + "id": "089b85d0-1b16-11e7-b09e-037021c4f8df-ecs", + "type": "visualization" + }, + { + "id": "99381c80-4d60-11e7-9a4c-ed99bbcaa42b-ecs", + "type": "visualization" + }, + { + "id": "c6f2ffd0-4d17-11e7-a196-69b9a7a020a9-ecs", + "type": "visualization" + }, + { + "id": "d56ee420-fa79-11e6-a1df-a78bd7504d38-ecs", + "type": "visualization" + }, + { + "id": "1aae9140-1b93-11e7-8ada-3df93aab833e-ecs", + "type": "visualization" + }, + { + "id": "e0f001c0-1b18-11e7-b09e-037021c4f8df-ecs", + "type": "visualization" + }, + { + "id": "dc589770-fa2b-11e6-bbd3-29c986c96e5a-ecs", + "type": "visualization" + }, + { + "id": "96976150-4d5d-11e7-aa29-87a97a796de6-ecs", + "type": "visualization" + }, + { + "id": "8c071e20-f999-11e9-90e8-1fb18e796788", + "type": "visualization" + }, + { + "id": "d3f51850-f9b6-11e9-90e8-1fb18e796788", + "type": "visualization" + }, + { + "id": "5c7af030-fa2a-11e6-bbd3-29c986c96e5a-ecs", + "type": "visualization" + }, + { + "id": "e6e639e0-f992-11e9-90e8-1fb18e796788", + "type": "visualization" + }, + { + "id": "bfa5e400-1b16-11e7-b09e-037021c4f8df-ecs", + "type": "visualization" + }, + { + "id": "7cdb1330-4d1a-11e7-a196-69b9a7a020a9-ecs", + "type": "visualization" + }, + { + "id": "78b74f30-f9cd-11e6-8115-a7c18106d86a-ecs", + "type": "visualization" + }, + { + "id": "Syslog-events-by-hostname-ecs", + "type": "visualization" + }, + { + "id": "3d65d450-a9c3-11e7-af20-67db8aecb295-ecs", + "type": "visualization" + }, + { + "id": "ab2d1e90-1b1a-11e7-b09e-037021c4f8df-ecs", + "type": "visualization" + }, + { + "id": "825fdb80-4d1d-11e7-b5f2-2b7c1895bf32-ecs", + "type": "visualization" + }, + { + "id": "26732e20-1b91-11e7-bec4-a5e9ec5cab8b-ecs", + "type": "visualization" + }, + { + "id": "Syslog-hostnames-and-processes-ecs", + "type": "visualization" + }, + { + "id": "522ee670-1b92-11e7-bec4-a5e9ec5cab8b-ecs", + "type": "visualization" + }, + { + "id": "51164310-fa2b-11e6-bbd3-29c986c96e5a-ecs", + "type": "visualization" + }, + { + "id": "bb3a8720-f991-11e9-90e8-1fb18e796788", + "type": "visualization" + }, + { + "id": "Container-Memory-stats-ecs", + "type": "visualization" + }, + { + "id": "5dd15c00-fa78-11e6-ae9b-81e5311e8cab-ecs", + "type": "visualization" + }, + { + "id": "327417e0-8462-11e7-bab8-bd2f0fb42c54-ecs", + "type": "visualization" + }, + { + "id": "d2e80340-4d5c-11e7-aa29-87a97a796de6-ecs", + "type": "visualization" + }, + { + "id": "19e123b0-4d5a-11e7-aee5-fdc812cc3bec-ecs", + "type": "visualization" + }, + { + "id": "3cec3eb0-f9d3-11e6-8a3e-2b904044ea1d-ecs", + "type": "visualization" + }, + { + "id": "2e224660-1b19-11e7-b09e-037021c4f8df-ecs", + "type": "visualization" + }, + { + "id": "12667040-fa80-11e6-a1df-a78bd7504d38-ecs", + "type": "visualization" + }, + { + "id": "d16bb400-f9cc-11e6-8115-a7c18106d86a-ecs", + "type": "visualization" + }, + { + "id": "34f97ee0-1b96-11e7-8ada-3df93aab833e-ecs", + "type": "visualization" + }, + { + "id": "fe064790-1b1f-11e7-bec4-a5e9ec5cab8b-ecs", + "type": "visualization" + }, + { + "id": "83e12df0-1b91-11e7-bec4-a5e9ec5cab8b-ecs", + "type": "visualization" + }, + { + "id": "4e4bb1e0-1b1b-11e7-b09e-037021c4f8df-ecs", + "type": "visualization" + }, + { + "id": "4b254630-f998-11e9-90e8-1fb18e796788", + "type": "visualization" + }, + { + "id": "6b7b9a40-faa1-11e6-86b1-cd7735ff7e23-ecs", + "type": "visualization" + }, + { + "id": "4d546850-1b15-11e7-b09e-037021c4f8df-ecs", + "type": "visualization" + }, + { + "id": "Container-CPU-usage-ecs", + "type": "visualization" + }, + { + "id": "b6f321e0-fa25-11e6-bbd3-29c986c96e5a-ecs", + "type": "search" + }, + { + "id": "62439dc0-f9c9-11e6-a747-6121780e0414-ecs", + "type": "search" + }, + { + "id": "8030c1b0-fa77-11e6-ae9b-81e5311e8cab-ecs", + "type": "search" + }, + { + "id": "Syslog-system-logs-ecs", + "type": "search" + }, + { + "id": "eb0039f0-fa7f-11e6-a1df-a78bd7504d38-ecs", + "type": "search" + }, + { + "id": "logs-system.auth-0.1.0", + "type": "ingest-pipeline" + }, + { + "id": "logs-system.auth-0.1.0", + "type": "ingest-pipeline" + }, + { + "id": "logs-system.syslog-0.1.0", + "type": "ingest-pipeline" + }, + { + "id": "logs-system.syslog-0.1.0", + "type": "ingest-pipeline" + }, + { + "id": "logs-system.auth", + "type": "index-template" + }, + { + "id": "metrics-system.core", + "type": "index-template" + }, + { + "id": "metrics-system.cpu", + "type": "index-template" + }, + { + "id": "metrics-system.diskio", + "type": "index-template" + }, + { + "id": "metrics-system.entropy", + "type": "index-template" + }, + { + "id": "metrics-system.filesystem", + "type": "index-template" + }, + { + "id": "metrics-system.fsstat", + "type": "index-template" + }, + { + "id": "metrics-system.load", + "type": "index-template" + }, + { + "id": "metrics-system.memory", + "type": "index-template" + }, + { + "id": "metrics-system.network", + "type": "index-template" + }, + { + "id": "metrics-system.network_summary", + "type": "index-template" + }, + { + "id": "metrics-system.process", + "type": "index-template" + }, + { + "id": "metrics-system.process_summary", + "type": "index-template" + }, + { + "id": "metrics-system.raid", + "type": "index-template" + }, + { + "id": "metrics-system.service", + "type": "index-template" + }, + { + "id": "metrics-system.socket", + "type": "index-template" + }, + { + "id": "metrics-system.socket_summary", + "type": "index-template" + }, + { + "id": "logs-system.syslog", + "type": "index-template" + }, + { + "id": "metrics-system.uptime", + "type": "index-template" + }, + { + "id": "metrics-system.users", + "type": "index-template" + } + ], + "es_index_patterns": { + "auth": "logs-system.auth-*", + "core": "metrics-system.core-*", + "cpu": "metrics-system.cpu-*", + "diskio": "metrics-system.diskio-*", + "entropy": "metrics-system.entropy-*", + "filesystem": "metrics-system.filesystem-*", + "fsstat": "metrics-system.fsstat-*", + "load": "metrics-system.load-*", + "memory": "metrics-system.memory-*", + "network": "metrics-system.network-*", + "network_summary": "metrics-system.network_summary-*", + "process": "metrics-system.process-*", + "process_summary": "metrics-system.process_summary-*", + "raid": "metrics-system.raid-*", + "service": "metrics-system.service-*", + "socket": "metrics-system.socket-*", + "socket_summary": "metrics-system.socket_summary-*", + "syslog": "logs-system.syslog-*", + "uptime": "metrics-system.uptime-*", + "users": "metrics-system.users-*" + }, + "name": "system", + "version": "0.1.0", + "internal": false, + "removable": false + }, + "references": [], + "updated_at": "2020-05-15T20:08:08.708Z", + "version": "Wzk4LDFd" + } + }, + { + "description": "This package contains a yaml pipeline.\n", + "download": "/epr/yamlpipeline/yamlpipeline-1.0.0.tar.gz", + "name": "yamlpipeline", + "path": "/package/yamlpipeline/1.0.0", + "title": "Yaml Pipeline package", + "type": "integration", + "version": "1.0.0", + "status": "not_installed" + } + ], + "success": true + } + } + } + } + } + } + }, + "operationId": "get-epm-list" + }, + "parameters": [] + }, + "/epm/categories": { + "get": { + "summary": "EPM - Categories", + "tags": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "title": { + "type": "string" + }, + "count": { + "type": "number" + } + }, + "required": [ + "id", + "title", + "count" + ] + } + } + } + } + } + }, + "operationId": "get-epm-categories" + } + }, + "/fleet/agents": { + "get": { + "summary": "Fleet - Agent - List", + "tags": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "list": { + "type": "array", + "items": { + "type": "object" + } + }, + "success": { + "type": "boolean" + }, + "total": { + "type": "number" + }, + "page": { + "type": "number" + }, + "perPage": { + "type": "number" + } + }, + "required": [ + "list", + "success", + "total", + "page", + "perPage" + ] + }, + "examples": { + "example-1": { + "value": { + "list": [ + { + "id": "205661d0-5e53-11ea-ad31-4f31c06bd9a4", + "active": true, + "config_id": "ae556400-5e39-11ea-8b49-f9747e466f7b", + "type": "PERMANENT", + "enrolled_at": "2020-03-04T20:02:50.605Z", + "user_provided_metadata": { + "dev_agent_version": "0.0.1", + "region": "us-east" + }, + "local_metadata": { + "host": "localhost", + "ip": "127.0.0.1", + "system": "Darwin 18.7.0", + "memory": 34359738368 + }, + "actions": [ + { + "data": "{\"config\":{\"id\":\"ae556400-5e39-11ea-8b49-f9747e466f7b\",\"outputs\":{\"default\":{\"type\":\"elasticsearch\",\"hosts\":[\"http://localhost:9200\"],\"api_key\":\"\",\"api_token\":\"6ckkp3ABz7e_XRqr3LM8:gQuDfUNSRgmY0iziYqP9Hw\"}},\"datasources\":[]}}", + "created_at": "2020-03-04T20:02:56.149Z", + "id": "6a95c00a-d76d-4931-97c3-0bf935272d7d", + "type": "CONFIG_CHANGE" + } + ], + "access_api_key_id": "6Mkkp3ABz7e_XRqrzLNJ", + "default_api_key": "6ckkp3ABz7e_XRqr3LM8:gQuDfUNSRgmY0iziYqP9Hw", + "current_error_events": [], + "last_checkin": "2020-03-04T20:03:05.700Z", + "status": "online" + } + ], + "success": true, + "total": 1, + "page": 1, + "perPage": 20 + } + } + } + } + } + } + }, + "operationId": "get-fleet-agents", + "security": [ + { + "basicAuth": [] + } + ] + } + }, + "/fleet/agents/{agentId}": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "name": "agentId", + "in": "path", + "required": true + } + ], + "get": { + "summary": "Fleet - Agent - Info", + "tags": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "item": { + "type": "object" + }, + "success": { + "type": "string" + } + }, + "required": [ + "item", + "success" + ] + } + } + } + } + }, + "operationId": "get-fleet-agents-agentId" + }, + "put": { + "summary": "Fleet - Agent - Update", + "tags": [], + "responses": {}, + "operationId": "put-fleet-agents-agentId", + "parameters": [ + { + "$ref": "#/components/parameters/xsrfHeader" + } + ] + }, + "delete": { + "summary": "Fleet - Agent - Delete", + "tags": [], + "responses": {}, + "operationId": "delete-fleet-agents-agentId", + "parameters": [ + { + "$ref": "#/components/parameters/xsrfHeader" + } + ] + } + }, + "/fleet/agents/{agentId}/events": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "name": "agentId", + "in": "path", + "required": true + } + ], + "get": { + "summary": "Fleet - Agent - Events", + "tags": [], + "responses": {}, + "operationId": "get-fleet-agents-agentId-events" + } + }, + "/fleet/agents/{agentId}/checkin": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "name": "agentId", + "in": "path", + "required": true + } + ], + "post": { + "summary": "Fleet - Agent - Check In", + "tags": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "action": { + "type": "string", + "enum": [ + "checkin" + ] + }, + "success": { + "type": "string" + }, + "actions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "agent_id": { + "type": "string" + }, + "data": { + "type": "object" + }, + "id": { + "type": "string" + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "type": { + "type": "string" + } + }, + "required": [ + "agent_id", + "data", + "id", + "created_at", + "type" + ] + } + } + } + }, + "examples": { + "success": { + "value": { + "action": "checkin", + "success": true, + "actions": [ + { + "agent_id": "a6f14bd2-1a2a-481c-9212-9494d064ffdf", + "type": "CONFIG_CHANGE", + "data": { + "config": { + "id": "2fe89350-a5e0-11ea-a587-5f886c8a849f", + "outputs": { + "default": { + "type": "elasticsearch", + "hosts": [ + "http://localhost:9200" + ], + "api_key": "Z-XkgHIBvwtjzIKtSCTh:AejRqdKpQx6z-6dqSI1LHg" + } + }, + "datasources": [ + { + "id": "33d6bd70-a5e0-11ea-a587-5f886c8a849f", + "name": "system-1", + "namespace": "default", + "enabled": true, + "use_output": "default", + "inputs": [ + { + "type": "logs", + "enabled": true, + "streams": [ + { + "id": "logs-system.auth", + "enabled": true, + "dataset": "system.auth", + "paths": [ + "/var/log/auth.log*", + "/var/log/secure*" + ], + "exclude_files": [ + ".gz$" + ], + "multiline": { + "pattern": "^\\s", + "match": "after" + }, + "processors": [ + { + "add_locale": null + }, + { + "add_fields": { + "target": "", + "fields": { + "ecs.version": "1.5.0" + } + } + } + ] + }, + { + "id": "logs-system.syslog", + "enabled": true, + "dataset": "system.syslog", + "paths": [ + "/var/log/messages*", + "/var/log/syslog*" + ], + "exclude_files": [ + ".gz$" + ], + "multiline": { + "pattern": "^\\s", + "match": "after" + }, + "processors": [ + { + "add_locale": null + }, + { + "add_fields": { + "target": "", + "fields": { + "ecs.version": "1.5.0" + } + } + } + ] + } + ] + }, + { + "type": "system/metrics", + "enabled": true, + "streams": [ + { + "id": "system/metrics-system.core", + "enabled": true, + "dataset": "system.core", + "metricsets": [ + "core" + ], + "core.metrics": "percentages" + }, + { + "id": "system/metrics-system.cpu", + "enabled": true, + "dataset": "system.cpu", + "metricsets": [ + "cpu" + ], + "core.metrics": "percentages", + "cpu.metrics": "percentages,normalized_percentages", + "period": "10s", + "process.include_top_n.by_cpu": 5, + "process.include_top_n.by_memory": 5, + "processes": ".*" + }, + { + "id": "system/metrics-system.diskio", + "enabled": true, + "dataset": "system.diskio", + "metricsets": [ + "diskio" + ] + }, + { + "id": "system/metrics-system.entropy", + "enabled": true, + "dataset": "system.entropy", + "metricsets": [ + "entropy" + ] + }, + { + "id": "system/metrics-system.filesystem", + "enabled": true, + "dataset": "system.filesystem", + "metricsets": [ + "filesystem" + ], + "period": "1m", + "processors": [ + { + "drop_event.when.regexp": { + "system.filesystem.mount_point": "^/(sys|cgroup|proc|dev|etc|host|lib|snap)($|/)" + } + } + ] + }, + { + "id": "system/metrics-system.fsstat", + "enabled": true, + "dataset": "system.fsstat", + "metricsets": [ + "fsstat" + ], + "period": "1m", + "processors": [ + { + "drop_event.when.regexp": { + "system.filesystem.mount_point": "^/(sys|cgroup|proc|dev|etc|host|lib|snap)($|/)" + } + } + ] + }, + { + "id": "system/metrics-system.load", + "enabled": true, + "dataset": "system.load", + "metricsets": [ + "load" + ], + "core.metrics": "percentages", + "cpu.metrics": "percentages,normalized_percentages", + "period": "10s", + "process.include_top_n.by_cpu": 5, + "process.include_top_n.by_memory": 5, + "processes": ".*" + }, + { + "id": "system/metrics-system.memory", + "enabled": true, + "dataset": "system.memory", + "metricsets": [ + "memory" + ], + "core.metrics": "percentages", + "cpu.metrics": "percentages,normalized_percentages", + "period": "10s", + "process.include_top_n.by_cpu": 5, + "process.include_top_n.by_memory": 5, + "processes": ".*" + }, + { + "id": "system/metrics-system.network", + "enabled": true, + "dataset": "system.network", + "metricsets": [ + "network" + ], + "core.metrics": "percentages", + "cpu.metrics": "percentages,normalized_percentages", + "period": "10s", + "process.include_top_n.by_cpu": 5, + "process.include_top_n.by_memory": 5, + "processes": ".*" + }, + { + "id": "system/metrics-system.network_summary", + "enabled": true, + "dataset": "system.network_summary", + "metricsets": [ + "network_summary" + ] + }, + { + "id": "system/metrics-system.process", + "enabled": true, + "dataset": "system.process", + "metricsets": [ + "process" + ], + "core.metrics": "percentages", + "cpu.metrics": "percentages,normalized_percentages", + "period": "10s", + "process.include_top_n.by_cpu": 5, + "process.include_top_n.by_memory": 5, + "processes": ".*" + }, + { + "id": "system/metrics-system.process_summary", + "enabled": true, + "dataset": "system.process_summary", + "metricsets": [ + "process_summary" + ], + "core.metrics": "percentages", + "cpu.metrics": "percentages,normalized_percentages", + "period": "10s", + "process.include_top_n.by_cpu": 5, + "process.include_top_n.by_memory": 5, + "processes": ".*" + }, + { + "id": "system/metrics-system.raid", + "enabled": true, + "dataset": "system.raid", + "metricsets": [ + "raid" + ] + }, + { + "id": "system/metrics-system.service", + "enabled": true, + "dataset": "system.service", + "metricsets": [ + "service" + ] + }, + { + "id": "system/metrics-system.socket", + "enabled": true, + "dataset": "system.socket", + "metricsets": [ + "socket" + ] + }, + { + "id": "system/metrics-system.socket_summary", + "enabled": true, + "dataset": "system.socket_summary", + "metricsets": [ + "socket_summary" + ], + "core.metrics": "percentages", + "cpu.metrics": "percentages,normalized_percentages", + "period": "10s", + "process.include_top_n.by_cpu": 5, + "process.include_top_n.by_memory": 5, + "processes": ".*" + }, + { + "id": "system/metrics-system.uptime", + "enabled": true, + "dataset": "system.uptime", + "metricsets": [ + "uptime" + ], + "core.metrics": "percentages", + "cpu.metrics": "percentages,normalized_percentages", + "period": "10s", + "processes": ".*" + }, + { + "id": "system/metrics-system.users", + "enabled": true, + "dataset": "system.users", + "metricsets": [ + "users" + ] + } + ] + } + ], + "package": { + "name": "system", + "version": "0.1.0" + } + }, + { + "id": "fdb1fea0-a5f6-11ea-ad52-534e35d3cd6f", + "name": "endpoint-1", + "namespace": "default", + "enabled": true, + "use_output": "default", + "inputs": [], + "package": { + "name": "endpoint", + "version": "0.2.0" + } + }, + { + "id": "2d792280-a5f7-11ea-ad52-534e35d3cd6f", + "name": "endpoint-2", + "namespace": "default", + "enabled": true, + "use_output": "default", + "inputs": [], + "package": { + "name": "endpoint", + "version": "0.2.0" + } + } + ], + "revision": 4, + "settings": { + "monitoring": { + "use_output": "default", + "enabled": true, + "logs": true, + "metrics": true + } + } + } + }, + "id": "51c6ad1e-a9c0-4c70-80da-99a5c51eedaf", + "created_at": "2020-06-04T19:52:24.667Z" + } + ] + } + } + } + } + } + } + }, + "operationId": "post-fleet-agents-agentId-checkin", + "parameters": [ + { + "$ref": "#/components/parameters/xsrfHeader" + } + ], + "security": [ + { + "Access API Key": [] + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "local_metadata": { + "$ref": "#/components/schemas/AgentMetadata" + }, + "events": { + "type": "array", + "items": { + "$ref": "#/components/schemas/NewAgentEvent" + } + } + } + }, + "examples": { + "stoped to starting": { + "value": { + "events": [ + { + "type": "STATE", + "subtype": "STARTING", + "message": "state changed from STOPPED to STARTING", + "timestamp": "2019-10-01T13:42:54.323Z", + "payload": {}, + "agent_id": "bee40627-8cbd-45df-add9-98c390f9db10" + } + ] + } + }, + "running": { + "value": { + "events": [ + { + "type": "STATE", + "subtype": "RUNNING", + "message": "state changed from STOPPED to RUNNING", + "timestamp": "2020-05-26T20:44:57.480Z", + "payload": { + "random": "data", + "state": "RUNNING", + "previous_state": "STOPPED" + }, + "agent_id": "bee40627-8cbd-45df-add9-98c390f9db10" + } + ] + } + } + } + } + } + } + } + }, + "/fleet/agents/{agentId}/acks": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "name": "agentId", + "in": "path", + "required": true + } + ], + "post": { + "summary": "Fleet - Agent - Acks", + "tags": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "action": { + "type": "string", + "enum": [ + "acks" + ] + } + }, + "required": [ + "success", + "action" + ] + }, + "examples": { + "success": { + "value": { + "action": "checkin", + "success": true + } + } + } + } + } + } + }, + "operationId": "post-fleet-agents-agentId-acks", + "parameters": [ + { + "$ref": "#/components/parameters/xsrfHeader" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": {} + }, + "examples": { + "example-1": { + "value": { + "events": [ + { + "type": "ACTION_RESULT", + "subtype": "CONFIG", + "timestamp": "2019-01-04T14:32:03.36764-05:00", + "action_id": "51c6ad1e-a9c0-4c70-80da-99a5c51eedaf", + "agent_id": "a6f14bd2-1a2a-481c-9212-9494d064ffdf", + "message": "acknowledge" + } + ] + } + } + } + } + } + } + } + }, + "/fleet/agents/enroll": { + "post": { + "summary": "Fleet - Agent - Enroll", + "tags": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "action": { + "type": "string" + }, + "success": { + "type": "boolean" + }, + "item": { + "$ref": "#/components/schemas/Agent" + } + } + }, + "examples": { + "success": { + "value": { + "action": "created", + "success": true, + "item": { + "id": "8086fb1a-72ca-4a67-8533-09300c1639fa", + "active": true, + "config_id": "2fe89350-a5e0-11ea-a587-5f886c8a849f", + "type": "PERMANENT", + "enrolled_at": "2020-06-04T13:03:57.856Z", + "user_provided_metadata": { + "dev_agent_version": "0.0.1", + "region": "us-east" + }, + "local_metadata": { + "host": "localhost", + "ip": "127.0.0.1", + "system": "Darwin 18.7.0", + "memory": 34359738368 + }, + "current_error_events": [], + "access_api_key": "cU9KdWYzSUJ2d3RqeklLdFdnNF86ZW05ZjFrMThUWW1GRW13OHMwRGZvdw==", + "status": "error" + } + } + } + } + } + } + } + }, + "operationId": "post-fleet-agents-enroll", + "parameters": [ + { + "$ref": "#/components/parameters/xsrfHeader" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "PERMANENT", + "EPHEMERAL", + "TEMPORARY" + ] + }, + "shared_id": { + "type": "string" + }, + "metadata": { + "type": "object", + "required": [ + "local", + "user_provided" + ], + "properties": { + "local": { + "$ref": "#/components/schemas/AgentMetadata" + }, + "user_provided": { + "$ref": "#/components/schemas/AgentMetadata" + } + } + } + }, + "required": [ + "type", + "metadata" + ] + }, + "examples": { + "good": { + "value": { + "type": "PERMANENT", + "metadata": { + "local": { + "host": "localhost", + "ip": "127.0.0.1", + "system": "Darwin 18.7.0", + "memory": 34359738368 + }, + "user_provided": { + "dev_agent_version": "0.0.1", + "region": "us-east" + } + } + } + } + } + } + } + }, + "security": [ + { + "Enrollment API Key": [] + } + ] + } + }, + "/fleet/agents/unenroll": { + "post": { + "summary": "Fleet - Agent - Unenroll", + "tags": [], + "responses": {}, + "operationId": "post-fleet-agents-unenroll", + "parameters": [ + { + "$ref": "#/components/parameters/xsrfHeader" + } + ] + } + }, + "/fleet/config/{configId}/agent-status": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "name": "configId", + "in": "path", + "required": true + } + ], + "get": { + "summary": "Fleet - Agent - Status for config", + "tags": [], + "responses": {}, + "operationId": "get-fleet-config-configId-agent-status" + } + }, + "/fleet/enrollment-api-keys": { + "get": { + "summary": "Enrollment - List", + "tags": [], + "responses": {}, + "operationId": "get-fleet-enrollment-api-keys", + "parameters": [] + }, + "post": { + "summary": "Enrollment - Create", + "tags": [], + "responses": {}, + "operationId": "post-fleet-enrollment-api-keys", + "parameters": [ + { + "$ref": "#/components/parameters/xsrfHeader" + } + ] + } + }, + "/fleet/enrollment-api-keys/{keyId}": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "name": "keyId", + "in": "path", + "required": true + } + ], + "get": { + "summary": "Enrollment - Info", + "tags": [], + "responses": {}, + "operationId": "get-fleet-enrollment-api-keys-keyId" + }, + "delete": { + "summary": "Enrollment - Delete", + "tags": [], + "responses": {}, + "operationId": "delete-fleet-enrollment-api-keys-keyId", + "parameters": [ + { + "$ref": "#/components/parameters/xsrfHeader" + } + ] + } + }, + "/setup": { + "post": { + "summary": "Ingest Manager - Setup", + "tags": [], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "isInitialized": { + "type": "boolean" + } + } + }, + "examples": { + "success": { + "value": { + "isInitialized": true + } + } + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "message": { + "type": "string" + } + } + }, + "examples": {} + } + } + } + }, + "operationId": "post-setup", + "parameters": [ + { + "$ref": "#/components/parameters/xsrfHeader" + } + ] + } + }, + "/fleet/install/{osType}": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "name": "osType", + "in": "path", + "required": true + } + ], + "get": { + "summary": "Fleet - Get OS install script", + "tags": [], + "responses": {}, + "operationId": "get-fleet-install-osType" + } + } + }, + "components": { + "schemas": { + "AgentConfig": { + "allOf": [ + { + "$ref": "#/components/schemas/NewAgentConfig" + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "active", + "inactive" + ] + }, + "datasources": { + "oneOf": [ + { + "items": { + "type": "string" + } + }, + { + "items": { + "$ref": "#/components/schemas/Datasource" + } + } + ], + "type": "array" + }, + "updated_on": { + "type": "string", + "format": "date-time" + }, + "updated_by": { + "type": "string" + }, + "revision": { + "type": "number" + }, + "agents": { + "type": "number" + } + }, + "required": [ + "id", + "status" + ] + } + ] + }, + "Datasource": { + "title": "Datasource", + "allOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "revision": { + "type": "number" + }, + "inputs": { + "type": "array", + "items": {} + } + }, + "required": [ + "id", + "revision" + ] + }, + { + "$ref": "#/components/schemas/NewDatasource" + } + ], + "x-examples": { + "example-1": {} + } + }, + "NewAgentConfig": { + "title": "NewAgentConfig", + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "namespace": { + "type": "string" + }, + "description": { + "type": "string" + } + } + }, + "NewDatasource": { + "title": "NewDatasource", + "type": "object", + "x-examples": { + "example-1": { + "enabled": true, + "title": "This is a nice title for human", + "package": { + "name": "epm/nginx", + "version": "1.7.0" + }, + "namespace": "prod", + "use_output": "long_term_storage", + "inputs": [ + { + "type": "logs", + "streams": [ + { + "enabled": true, + "dataset": "nginx.acccess", + "paths": [ + "/var/log/nginx/access.log" + ] + }, + { + "enabled": true, + "dataset": "nginx.error", + "paths": [ + "/var/log/nginx/error.log" + ] + } + ] + }, + { + "type": "nginx/metrics", + "streams": [ + { + "id": "id string", + "enabled": true, + "dataset": "nginx.stub_status", + "metricset": "stub_status" + } + ] + } + ] + } + }, + "description": "", + "properties": { + "enabled": { + "type": "boolean" + }, + "package": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "version": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "required": [ + "name", + "version", + "title" + ] + }, + "namespace": { + "type": "string" + }, + "output_id": { + "type": "string" + }, + "inputs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "processors": { + "type": "array", + "items": { + "type": "string" + } + }, + "streams": { + "type": "array", + "items": {} + }, + "config": { + "type": "object" + }, + "vars": { + "type": "object" + } + }, + "required": [ + "type", + "enabled", + "streams" + ] + } + }, + "config_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string" + } + }, + "required": [ + "output_id", + "inputs", + "config_id", + "name" + ] + }, + "PackageInfo": { + "title": "PackageInfo", + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "title": { + "type": "string" + }, + "version": { + "type": "string" + }, + "readme": { + "type": "string" + }, + "description": { + "type": "string" + }, + "type": { + "type": "string" + }, + "categories": { + "type": "array", + "items": { + "type": "string" + } + }, + "requirement": { + "oneOf": [ + { + "properties": { + "kibana": { + "type": "object", + "properties": { + "versions": { + "type": "string" + } + } + } + } + }, + { + "properties": { + "elasticsearch": { + "type": "object", + "properties": { + "versions": { + "type": "string" + } + } + } + } + } + ], + "type": "object" + }, + "screenshots": { + "type": "array", + "items": { + "type": "object", + "properties": { + "src": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "required": [ + "src" + ] + } + }, + "icons": { + "type": "array", + "items": { + "type": "string" + } + }, + "assets": { + "type": "array", + "items": { + "type": "string" + } + }, + "internal": { + "type": "boolean" + }, + "format_version": { + "type": "string" + }, + "datasets": { + "type": "array", + "items": { + "type": "object", + "properties": { + "title": { + "type": "string" + }, + "name": { + "type": "string" + }, + "release": { + "type": "string" + }, + "ingeset_pipeline": { + "type": "string" + }, + "vars": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "default": { + "type": "string" + } + }, + "required": [ + "name", + "default" + ] + } + }, + "type": { + "type": "string" + }, + "package": { + "type": "string" + } + }, + "required": [ + "title", + "name", + "release", + "ingeset_pipeline", + "type", + "package" + ] + } + }, + "download": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": [ + "name", + "title", + "version", + "description", + "type", + "categories", + "requirement", + "assets", + "format_version", + "download", + "path" + ] + }, + "SearchResult": { + "title": "SearchResult", + "type": "object", + "properties": { + "description": { + "type": "string" + }, + "download": { + "type": "string" + }, + "icons": { + "type": "string" + }, + "name": { + "type": "string" + }, + "path": { + "type": "string" + }, + "title": { + "type": "string" + }, + "type": { + "type": "string" + }, + "version": { + "type": "string" + }, + "status": { + "type": "string" + }, + "savedObject": { + "type": "object" + } + }, + "required": [ + "description", + "download", + "icons", + "name", + "path", + "title", + "type", + "version", + "status" + ] + }, + "AgentStatus": { + "type": "string", + "title": "AgentStatus", + "enum": [ + "offline", + "error", + "online", + "inactive", + "warning" + ] + }, + "Agent": { + "title": "Agent", + "type": "object", + "properties": { + "type": { + "$ref": "#/components/schemas/AgentType" + }, + "active": { + "type": "boolean" + }, + "enrolled_at": { + "type": "string" + }, + "shared_id": { + "type": "string" + }, + "access_api_key_id": { + "type": "string" + }, + "default_api_key_id": { + "type": "string" + }, + "config_id": { + "type": "string" + }, + "config_revision": { + "type": [ + "number", + "null" + ] + }, + "config_newest_revision": { + "type": "number" + }, + "last_checkin": { + "type": "string" + }, + "user_provided_metadata": { + "$ref": "#/components/schemas/AgentMetadata" + }, + "local_metadata": { + "$ref": "#/components/schemas/AgentMetadata" + }, + "id": { + "type": "string" + }, + "current_error_events": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AgentEvent" + } + }, + "access_api_key": { + "type": "string" + }, + "status": { + "$ref": "#/components/schemas/AgentStatus" + }, + "default_api_key": { + "type": "string" + } + }, + "required": [ + "type", + "active", + "enrolled_at", + "id", + "current_error_events", + "status" + ] + }, + "AgentType": { + "type": "string", + "title": "AgentType", + "enum": [ + "PERMANENT", + "EPHEMERAL", + "TEMPORARY" + ] + }, + "AgentMetadata": { + "title": "AgentMetadata", + "type": "object" + }, + "NewAgentEvent": { + "title": "NewAgentEvent", + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "STATE", + "ERROR", + "ACTION_RESULT", + "ACTION" + ] + }, + "subtype": { + "type": "string", + "enum": [ + "RUNNING", + "STARTING", + "IN_PROGRESS", + "CONFIG", + "FAILED", + "STOPPING", + "STOPPED", + "DATA_DUMP", + "ACKNOWLEDGED", + "UNKNOWN" + ] + }, + "timestamp": { + "type": "string" + }, + "message": { + "type": "string" + }, + "payload": { + "type": "string" + }, + "agent_id": { + "type": "string" + }, + "config_id": { + "type": "string" + }, + "stream_id": { + "type": "string" + }, + "action_id": { + "type": "string" + } + }, + "required": [ + "type", + "subtype", + "timestamp", + "message", + "agent_id" + ] + }, + "AgentEvent": { + "title": "AgentEvent", + "allOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string" + } + }, + "required": [ + "id" + ] + }, + { + "$ref": "#/components/schemas/NewAgentEvent" + } + ] + }, + "AccessApiKey": { + "type": "string", + "title": "AccessApiKey", + "format": "byte" + }, + "EnrollmentApiKey": { + "type": "string", + "title": "EnrollmentApiKey", + "format": "byte" + } + }, + "parameters": { + "pageSizeParam": { + "name": "perPage", + "in": "query", + "description": "The number of items to return", + "required": false, + "schema": { + "type": "integer", + "default": 50 + } + }, + "pageIndexParam": { + "name": "page", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 1 + } + }, + "kueryParam": { + "name": "kuery", + "in": "query", + "required": false, + "schema": { + "type": "string" + } + }, + "xsrfHeader": { + "schema": { + "type": "string" + }, + "in": "header", + "name": "kbn-xsrf", + "required": true + } + }, + "securitySchemes": { + "basicAuth": { + "type": "http", + "scheme": "basic" + }, + "Enrollment API Key": { + "name": "Authorization", + "type": "apiKey", + "in": "header", + "description": "e.g. Authorization: ApiKey base64EnrollmentApiKey" + }, + "Access API Key": { + "name": "Authorization", + "type": "apiKey", + "in": "header", + "description": "e.g. Authorization: ApiKey base64AccessApiKey" + } + } + }, + "security": [ + { + "basicAuth": [] + } + ] +} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_messaging.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_messaging.tsx index 2b80ab9f0068e..f43419fc52ef0 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_messaging.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_messaging.tsx @@ -15,6 +15,7 @@ const Message = styled(EuiText).attrs((props) => ({ size: 's', }))` padding: ${(props) => props.theme.eui.paddingSizes.m}; + margin-top: auto; `; export const AlphaMessaging: React.FC<{}> = () => { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx index 47d723dd9a1ac..c79077e68afb0 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx @@ -167,7 +167,7 @@ export const SettingFlyout: React.FunctionComponent = ({ onClose }) => { 'xpack.ingestManager.settings.integrationUpgradeEnabledFieldLabel', { defaultMessage: - 'Automatically update Integrations to the latest version to receive the latest assets. Agent configurations may need to be updated in order to use new features.', + 'Automatically update integrations to the latest version to receive the latest assets. Agent configurations may need to be updated in order to use new features.', } ), }, @@ -190,7 +190,7 @@ export const SettingFlyout: React.FunctionComponent = ({ onClose }) => {

diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx index 72b12260a1a12..5e0cba7383e9c 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx @@ -9,7 +9,7 @@ import { EuiTabs, EuiTab, EuiFlexGroup, EuiFlexItem, EuiIcon, EuiButtonEmpty } f import { FormattedMessage } from '@kbn/i18n/react'; import { Section } from '../sections'; import { AlphaMessaging, SettingFlyout } from '../components'; -import { useLink, useConfig } from '../hooks'; +import { useLink, useConfig, useCore } from '../hooks'; interface Props { showSettings?: boolean; @@ -20,6 +20,8 @@ interface Props { const Container = styled.div` min-height: calc(100vh - ${(props) => props.theme.eui.euiHeaderChildSize}); background: ${(props) => props.theme.eui.euiColorEmptyShade}; + display: flex; + flex-direction: column; `; const Nav = styled.nav` @@ -40,6 +42,7 @@ export const DefaultLayout: React.FunctionComponent = ({ }) => { const { getHref } = useLink(); const { epm, fleet } = useConfig(); + const { uiSettings } = useCore(); const [isSettingsFlyoutOpen, setIsSettingsFlyoutOpen] = React.useState(false); return ( @@ -52,85 +55,89 @@ export const DefaultLayout: React.FunctionComponent = ({ /> )} - + {children} + diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/actions_menu.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/actions_menu.tsx index 78ed228012691..dc61da685c88d 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/actions_menu.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/actions_menu.tsx @@ -58,7 +58,7 @@ export const AgentConfigActionMenu = memo<{ configId: string; fullButton?: boole > , ]} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/custom_configure_datasource.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/custom_configure_datasource.tsx index aff764cb8ba3e..4263feb7cd8c7 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/custom_configure_datasource.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/custom_configure_datasource.tsx @@ -12,7 +12,8 @@ import { CreateDatasourceFrom } from '../types'; export interface CustomConfigureDatasourceProps { packageName: string; from: CreateDatasourceFrom; - datasource: NewDatasource | (NewDatasource & { id: string }); + datasource: NewDatasource; + datasourceId?: string; } /** diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_configure_datasource.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_configure_datasource.tsx index d9cf0fbfb7987..5499ac287ff05 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_configure_datasource.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_configure_datasource.tsx @@ -16,7 +16,8 @@ import { CreateDatasourceFrom } from './types'; export const StepConfigureDatasource: React.FunctionComponent<{ from?: CreateDatasourceFrom; packageInfo: PackageInfo; - datasource: NewDatasource | (NewDatasource & { id: string }); + datasource: NewDatasource; + datasourceId?: string; updateDatasource: (fields: Partial) => void; validationResults: DatasourceValidationResults; submitAttempted: boolean; @@ -24,6 +25,7 @@ export const StepConfigureDatasource: React.FunctionComponent<{ from = 'config', packageInfo, datasource, + datasourceId, updateDatasource, validationResults, submitAttempted, @@ -70,9 +72,10 @@ export const StepConfigureDatasource: React.FunctionComponent<{ ) : ( ); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/datasources/datasources_table.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/datasources/datasources_table.tsx index 01505fcf4c65e..caf0c149c0199 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/datasources/datasources_table.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/datasources/datasources_table.tsx @@ -280,7 +280,7 @@ export const DatasourcesTable: React.FunctionComponent = ({ > , ], diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/datasources/no_datasources.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/datasources/no_datasources.tsx index 72726f1c855ec..f2c204d955a0b 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/datasources/no_datasources.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/datasources/no_datasources.tsx @@ -38,7 +38,7 @@ export const NoDatasources = memo<{ configId: string }>(({ configId }) => { > } diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/edit_datasource_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/edit_datasource_page/index.tsx index 4bb42faedf7f6..d47eea80da8b7 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/edit_datasource_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/edit_datasource_page/index.tsx @@ -69,8 +69,7 @@ export const EditDatasourcePage: React.FunctionComponent = () => { const [loadingError, setLoadingError] = useState(); const [agentConfig, setAgentConfig] = useState(); const [packageInfo, setPackageInfo] = useState(); - const [datasource, setDatasource] = useState({ - id: '', + const [datasource, setDatasource] = useState({ name: '', description: '', config_id: '', @@ -94,6 +93,7 @@ export const EditDatasourcePage: React.FunctionComponent = () => { } if (datasourceData?.item) { const { + id, revision, inputs, created_by, @@ -302,6 +302,7 @@ export const EditDatasourcePage: React.FunctionComponent = () => { from={'edit'} packageInfo={packageInfo} datasource={datasource} + datasourceId={datasourceId} updateDatasource={updateDatasource} validationResults={validationResults!} submitAttempted={formState === 'INVALID'} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/confirm_package_uninstall.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/confirm_package_uninstall.tsx index 14b9bf77c3a00..11cdbe0be7b62 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/confirm_package_uninstall.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/confirm_package_uninstall.tsx @@ -56,7 +56,7 @@ export const ConfirmPackageUninstall = (props: ConfirmPackageUninstallProps) =>

diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/header.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/header.tsx index 318bab6c44951..db046d18ccebc 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/header.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/header.tsx @@ -74,7 +74,10 @@ export function Header(props: HeaderProps) { > diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/settings_panel.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/settings_panel.tsx index 5d24c180268a7..986b946131e33 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/settings_panel.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/settings_panel.tsx @@ -175,7 +175,7 @@ export const SettingsPanel = (

diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/header.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/header.tsx index a40fe98f93ddc..c378e5a47a9b9 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/header.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/header.tsx @@ -20,7 +20,7 @@ export const HeroCopy = memo(() => {

@@ -46,7 +46,7 @@ export const HeroImage = memo(() => { const Illustration = styled(EuiImage).attrs((props) => ({ alt: i18n.translate('xpack.ingestManager.epm.illustrationAltText', { - defaultMessage: 'Illustration of an Elastic integration', + defaultMessage: 'Illustration of an integration', }), url: IS_DARK_THEME ? toAssets('illustration_integrations_darkmode.svg') diff --git a/x-pack/plugins/ingest_manager/server/routes/data_streams/handlers.ts b/x-pack/plugins/ingest_manager/server/routes/data_streams/handlers.ts index e4c860713a6f1..2c65b08a68700 100644 --- a/x-pack/plugins/ingest_manager/server/routes/data_streams/handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/data_streams/handlers.ts @@ -31,12 +31,12 @@ export const getListHandler: RequestHandler = async (context, request, response) must: [ { exists: { - field: 'stream.namespace', + field: 'dataset.namespace', }, }, { exists: { - field: 'stream.dataset', + field: 'dataset.name', }, }, ], @@ -54,19 +54,19 @@ export const getListHandler: RequestHandler = async (context, request, response) aggs: { dataset: { terms: { - field: 'stream.dataset', + field: 'dataset.name', size: 1, }, }, namespace: { terms: { - field: 'stream.namespace', + field: 'dataset.namespace', size: 1, }, }, type: { terms: { - field: 'stream.type', + field: 'dataset.type', size: 1, }, }, diff --git a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts index 85d4a85e245c2..ef3542b7ecffd 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts @@ -388,12 +388,12 @@ const getIndexQuery = (templateName: string) => ({ must: [ { exists: { - field: 'stream.namespace', + field: 'dataset.namespace', }, }, { exists: { - field: 'stream.dataset', + field: 'dataset.name', }, }, ], diff --git a/x-pack/plugins/lists/common/schemas/common/schemas.ts b/x-pack/plugins/lists/common/schemas/common/schemas.ts index 14ae030c63df3..7f086647bbc75 100644 --- a/x-pack/plugins/lists/common/schemas/common/schemas.ts +++ b/x-pack/plugins/lists/common/schemas/common/schemas.ts @@ -8,8 +8,8 @@ import * as t from 'io-ts'; -import { DefaultStringArray, NonEmptyString } from '../types'; import { DefaultNamespace } from '../types/default_namespace'; +import { DefaultStringArray, NonEmptyString } from '../../siem_common_deps'; export const name = t.string; export type Name = t.TypeOf; diff --git a/x-pack/plugins/lists/common/schemas/request/create_exception_list_item_schema.ts b/x-pack/plugins/lists/common/schemas/request/create_exception_list_item_schema.ts index c10d441d93aa5..4322ff4c2801b 100644 --- a/x-pack/plugins/lists/common/schemas/request/create_exception_list_item_schema.ts +++ b/x-pack/plugins/lists/common/schemas/request/create_exception_list_item_schema.ts @@ -24,8 +24,9 @@ import { tags, } from '../common/schemas'; import { Identity, RequiredKeepUndefined } from '../../types'; -import { DefaultEntryArray, DefaultUuid } from '../types'; +import { DefaultEntryArray } from '../types'; import { EntriesArray } from '../types/entries'; +import { DefaultUuid } from '../../siem_common_deps'; export const createExceptionListItemSchema = t.intersection([ t.exact( diff --git a/x-pack/plugins/lists/common/schemas/request/create_exception_list_schema.ts b/x-pack/plugins/lists/common/schemas/request/create_exception_list_schema.ts index 3da8bfca126ae..a0aaa91c81427 100644 --- a/x-pack/plugins/lists/common/schemas/request/create_exception_list_schema.ts +++ b/x-pack/plugins/lists/common/schemas/request/create_exception_list_schema.ts @@ -22,7 +22,7 @@ import { tags, } from '../common/schemas'; import { Identity, RequiredKeepUndefined } from '../../types'; -import { DefaultUuid } from '../types/default_uuid'; +import { DefaultUuid } from '../../siem_common_deps'; export const createExceptionListSchema = t.intersection([ t.exact( diff --git a/x-pack/plugins/lists/common/schemas/request/import_list_item_schema.ts b/x-pack/plugins/lists/common/schemas/request/import_list_item_schema.ts index 94299c93b29d8..0a5e861d84483 100644 --- a/x-pack/plugins/lists/common/schemas/request/import_list_item_schema.ts +++ b/x-pack/plugins/lists/common/schemas/request/import_list_item_schema.ts @@ -6,6 +6,7 @@ /* eslint-disable @typescript-eslint/camelcase */ +// TODO: You cannot import a stream from common into the front end code! CHANGE THIS import { Readable } from 'stream'; import * as t from 'io-ts'; @@ -20,6 +21,7 @@ export const importListItemSchema = t.exact( export type ImportListItemSchema = t.TypeOf; +// TODO: You cannot import a stream from common into the front end code! CHANGE THIS export interface HapiReadableStream extends Readable { hapi: { filename: string; diff --git a/x-pack/plugins/lists/common/schemas/types/index.ts b/x-pack/plugins/lists/common/schemas/types/index.ts index 674d7c40c2970..2f38ff86d4fb2 100644 --- a/x-pack/plugins/lists/common/schemas/types/index.ts +++ b/x-pack/plugins/lists/common/schemas/types/index.ts @@ -4,7 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ export * from './default_entries_array'; -export * from './default_string_array'; -export * from './default_uuid'; export * from './entries'; -export * from './non_empty_string'; diff --git a/x-pack/plugins/lists/common/siem_common_deps.ts b/x-pack/plugins/lists/common/siem_common_deps.ts index 9de40e3f72932..3759305987f79 100644 --- a/x-pack/plugins/lists/common/siem_common_deps.ts +++ b/x-pack/plugins/lists/common/siem_common_deps.ts @@ -4,5 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ +export { NonEmptyString } from '../../security_solution/common/detection_engine/schemas/types/non_empty_string'; +export { DefaultUuid } from '../../security_solution/common/detection_engine/schemas/types/default_uuid'; +export { DefaultStringArray } from '../../security_solution/common/detection_engine/schemas/types/default_string_array'; export { exactCheck } from '../../security_solution/common/exact_check'; export { getPaths, foldLeftRight } from '../../security_solution/common/test_utils'; diff --git a/x-pack/plugins/maps/public/classes/styles/color_utils.tsx b/x-pack/plugins/maps/public/classes/styles/color_utils.tsx index 116e03096b0f5..0192a9d7ca68f 100644 --- a/x-pack/plugins/maps/public/classes/styles/color_utils.tsx +++ b/x-pack/plugins/maps/public/classes/styles/color_utils.tsx @@ -139,11 +139,11 @@ const COLOR_PALETTES_CONFIGS: ColorPalette[] = [ }, { id: 'palette_20', - colors: euiPaletteColorBlind(2), + colors: euiPaletteColorBlind({ rotations: 2 }), }, { id: 'palette_30', - colors: euiPaletteColorBlind(3), + colors: euiPaletteColorBlind({ rotations: 3 }), }, ]; diff --git a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_geometry_filter_form.js b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_geometry_filter_form.js index b103fb43af97c..e1779c1afbf47 100644 --- a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_geometry_filter_form.js +++ b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_geometry_filter_form.js @@ -9,18 +9,16 @@ import { EuiIcon } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; +import { URL_MAX_LENGTH } from '../../../../../../../src/core/public'; import { createSpatialFilterWithGeometry } from '../../../elasticsearch_geo_utils'; import { GEO_JSON_TYPE } from '../../../../common/constants'; import { GeometryFilterForm } from '../../../components/geometry_filter_form'; -import { UrlOverflowService } from '../../../../../../../src/plugins/kibana_legacy/public'; import rison from 'rison-node'; // over estimated and imprecise value to ensure filter has additional room for any meta keys added when filter is mapped. const META_OVERHEAD = 100; -const urlOverflow = new UrlOverflowService(); - export class FeatureGeometryFilterForm extends Component { state = { isLoading: false, @@ -82,7 +80,7 @@ export class FeatureGeometryFilterForm extends Component { // No elasticsearch support for pre-indexed shapes and geo_point spatial queries. if ( window.location.href.length + rison.encode(filter).length + META_OVERHEAD > - urlOverflow.failLength() + URL_MAX_LENGTH ) { this.setState({ errorMsg: i18n.translate('xpack.maps.tooltip.geometryFilterForm.filterTooLargeMessage', { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/_index.scss b/x-pack/plugins/ml/public/application/data_frame_analytics/_index.scss index 5508c021d3313..140593cb17f6e 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/_index.scss +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/_index.scss @@ -1,5 +1,3 @@ @import 'pages/analytics_exploration/components/regression_exploration/index'; @import 'pages/analytics_management/components/analytics_list/index'; -@import 'pages/analytics_management/components/create_analytics_form/index'; -@import 'pages/analytics_management/components/create_analytics_flyout/index'; @import 'pages/analytics_management/components/create_analytics_button/index'; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/analysis_fields_table.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/analysis_fields_table.tsx index ad540285e49f0..09aea596d81e9 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/analysis_fields_table.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/analysis_fields_table.tsx @@ -85,7 +85,7 @@ export const MemoizedAnalysisFieldsTable: FC<{ if (excludes.length > 0) { setCurrentSelection(excludes); } - }, []); + }, [tableItems]); // Only set form state on unmount to prevent re-renders due to props changing if exludes was updated on each selection useEffect(() => { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/configuration_step_form.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/configuration_step_form.tsx index 9446dfd4ed525..e63756686a4ba 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/configuration_step_form.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/configuration_step_form.tsx @@ -20,13 +20,13 @@ import { TRAINING_PERCENT_MAX, } from '../../../../common/analytics'; import { CreateAnalyticsStepProps } from '../../../analytics_management/hooks/use_create_analytics_form'; -import { Messages } from '../../../analytics_management/components/create_analytics_form/messages'; +import { Messages } from '../shared'; import { DEFAULT_MODEL_MEMORY_LIMIT, getJobConfigFromFormState, State, } from '../../../analytics_management/hooks/use_create_analytics_form/state'; -import { shouldAddAsDepVarOption } from '../../../analytics_management/components/create_analytics_form/form_options_validation'; +import { shouldAddAsDepVarOption } from './form_options_validation'; import { ml } from '../../../../../services/ml_api_service'; import { getToastNotifications } from '../../../../../util/dependency_cache'; @@ -56,7 +56,7 @@ export const ConfigurationStepForm: FC = ({ const { currentSavedSearch, currentIndexPattern } = mlContext; const { savedSearchQuery, savedSearchQueryStr } = useSavedSearch(); - const { initiateWizard, setEstimatedModelMemoryLimit, setFormState } = actions; + const { setEstimatedModelMemoryLimit, setFormState } = actions; const { estimatedModelMemoryLimit, form, isJobCreated, requestMessages } = state; const firstUpdate = useRef(true); const { @@ -75,9 +75,12 @@ export const ConfigurationStepForm: FC = ({ modelMemoryLimit, previousJobType, requiredFieldsError, + sourceIndex, trainingPercent, } = form; + const toastNotifications = getToastNotifications(); + const setJobConfigQuery = ({ query, queryString }: { query: any; queryString: string }) => { setFormState({ jobConfigQuery: query, jobConfigQueryString: queryString }); }; @@ -90,7 +93,7 @@ export const ConfigurationStepForm: FC = ({ const indexPreviewProps = { ...indexData, dataTestSubj: 'mlAnalyticsCreationDataGrid', - toastNotifications: getToastNotifications(), + toastNotifications, }; const isJobTypeWithDepVar = @@ -209,7 +212,8 @@ export const ConfigurationStepForm: FC = ({ }); } } catch (e) { - let errorMessage; + let maxDistinctValuesErrorMessage; + if ( jobType === ANALYSIS_CONFIG_TYPE.CLASSIFICATION && e.body && @@ -218,7 +222,23 @@ export const ConfigurationStepForm: FC = ({ (e.body.message.includes('must have at most') || e.body.message.includes('must have at least')) ) { - errorMessage = e.body.message; + maxDistinctValuesErrorMessage = e.body.message; + } + + if ( + e.body && + e.body.message !== undefined && + e.body.message.includes('status_exception') && + e.body.message.includes('Unable to estimate memory usage as no documents') + ) { + toastNotifications.addWarning( + i18n.translate('xpack.ml.dataframe.analytics.create.allDocsMissingFieldsErrorMessage', { + defaultMessage: `Unable to estimate memory usage. There are mapped fields for source index [{index}] that do not exist in any indexed documents. You will have to switch to the JSON editor for explicit field selection and include only fields that exist in indexed documents.`, + values: { + index: sourceIndex, + }, + }) + ); } const fallbackModelMemoryLimit = jobType !== undefined @@ -227,17 +247,13 @@ export const ConfigurationStepForm: FC = ({ setEstimatedModelMemoryLimit(fallbackModelMemoryLimit); setFormState({ fieldOptionsFetchFail: true, - maxDistinctValuesError: errorMessage, + maxDistinctValuesError: maxDistinctValuesErrorMessage, loadingFieldOptions: false, ...(shouldUpdateModelMemoryLimit ? { modelMemoryLimit: fallbackModelMemoryLimit } : {}), }); } }, 300); - useEffect(() => { - initiateWizard(); - }, []); - useEffect(() => { setFormState({ sourceIndex: currentIndexPattern.title }); }, []); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/form_options_validation.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/form_options_validation.ts similarity index 93% rename from x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/form_options_validation.ts rename to x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/form_options_validation.ts index 0579283c97d61..bf3ab01549139 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/form_options_validation.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/form_options_validation.ts @@ -7,7 +7,7 @@ import { ES_FIELD_TYPES } from '../../../../../../../../../../src/plugins/data/public'; import { Field, EVENT_RATE_FIELD_ID } from '../../../../../../../common/types/fields'; import { ANALYSIS_CONFIG_TYPE } from '../../../../common/analytics'; -import { AnalyticsJobType } from '../../hooks/use_create_analytics_form/state'; +import { AnalyticsJobType } from '../../../analytics_management/hooks/use_create_analytics_form/state'; import { BASIC_NUMERICAL_TYPES, EXTENDED_NUMERICAL_TYPES } from '../../../../common/fields'; export const CATEGORICAL_TYPES = new Set(['ip', 'keyword']); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/supported_fields_message.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/supported_fields_message.tsx index fe13cc1d6edfc..0a4ba67831818 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/supported_fields_message.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/supported_fields_message.tsx @@ -12,10 +12,7 @@ import { AnalyticsJobType } from '../../../analytics_management/hooks/use_create import { ANALYSIS_CONFIG_TYPE } from '../../../../common/analytics'; import { Field, EVENT_RATE_FIELD_ID } from '../../../../../../../common/types/fields'; import { BASIC_NUMERICAL_TYPES, EXTENDED_NUMERICAL_TYPES } from '../../../../common/fields'; -import { - OMIT_FIELDS, - CATEGORICAL_TYPES, -} from '../../../analytics_management/components/create_analytics_form/form_options_validation'; +import { OMIT_FIELDS, CATEGORICAL_TYPES } from './form_options_validation'; import { ES_FIELD_TYPES } from '../../../../../../../../../../src/plugins/data/public'; import { newJobCapsService } from '../../../../../services/new_job_capabilities_service'; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_advanced_editor/create_analytics_advanced_editor.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/create_analytics_advanced_editor/create_analytics_advanced_editor.tsx similarity index 95% rename from x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_advanced_editor/create_analytics_advanced_editor.tsx rename to x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/create_analytics_advanced_editor/create_analytics_advanced_editor.tsx index 17b905cab135b..a35a314bec985 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_advanced_editor/create_analytics_advanced_editor.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/create_analytics_advanced_editor/create_analytics_advanced_editor.tsx @@ -22,9 +22,9 @@ import { XJsonMode } from '../../../../../../../shared_imports'; const xJsonMode = new XJsonMode(); -import { CreateAnalyticsFormProps } from '../../hooks/use_create_analytics_form'; -import { CreateStep } from '../../../analytics_creation/components/create_step'; -import { ANALYTICS_STEPS } from '../../../analytics_creation/page'; +import { CreateAnalyticsFormProps } from '../../../analytics_management/hooks/use_create_analytics_form'; +import { CreateStep } from '../create_step'; +import { ANALYTICS_STEPS } from '../../page'; export const CreateAnalyticsAdvancedEditor: FC = (props) => { const { actions, state } = props; @@ -125,7 +125,6 @@ export const CreateAnalyticsAdvancedEditor: FC = (prop onChange={onChange} setOptions={{ fontSize: '12px', - maxLines: 20, }} theme="textmate" aria-label={i18n.translate( diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_advanced_editor/index.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/create_analytics_advanced_editor/index.ts similarity index 100% rename from x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_advanced_editor/index.ts rename to x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/create_analytics_advanced_editor/index.ts diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/create_step/create_step.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/create_step/create_step.tsx index 2dda5f5d819b7..8d51848a25f50 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/create_step/create_step.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/create_step/create_step.tsx @@ -16,7 +16,7 @@ import { import { i18n } from '@kbn/i18n'; import { CreateAnalyticsFormProps } from '../../../analytics_management/hooks/use_create_analytics_form'; -import { Messages } from '../../../analytics_management/components/create_analytics_form/messages'; +import { Messages } from '../shared'; import { ANALYTICS_STEPS } from '../../page'; import { BackToListPanel } from '../back_to_list_panel'; @@ -26,14 +26,7 @@ interface Props extends CreateAnalyticsFormProps { export const CreateStep: FC = ({ actions, state, step }) => { const { createAnalyticsJob, startAnalyticsJob } = actions; - const { - isAdvancedEditorValidJson, - isJobCreated, - isJobStarted, - isModalButtonDisabled, - isValid, - requestMessages, - } = state; + const { isAdvancedEditorValidJson, isJobCreated, isJobStarted, isValid, requestMessages } = state; const [checked, setChecked] = useState(true); @@ -75,7 +68,7 @@ export const CreateStep: FC = ({ actions, state, step }) => { { +interface Props { + jobId?: DataFrameAnalyticsId; +} + +export const Page: FC = ({ jobId }) => { const [currentStep, setCurrentStep] = useState(ANALYTICS_STEPS.CONFIGURATION); const [activatedSteps, setActivatedSteps] = useState([true, false, false, false]); @@ -44,23 +50,36 @@ export const Page: FC = () => { const createAnalyticsForm = useCreateAnalyticsForm(); const { isAdvancedEditorEnabled } = createAnalyticsForm.state; const { jobType } = createAnalyticsForm.state.form; - const { switchToAdvancedEditor } = createAnalyticsForm.actions; + const { initiateWizard, setJobClone, switchToAdvancedEditor } = createAnalyticsForm.actions; useEffect(() => { - if (activatedSteps[currentStep] === false) { - activatedSteps.splice(currentStep, 1, true); - setActivatedSteps(activatedSteps); - } - }, [currentStep]); + initiateWizard(); - useEffect(() => { if (currentIndexPattern) { (async function () { await newJobCapsService.initializeFromIndexPattern(currentIndexPattern, false, false); + + if (jobId !== undefined) { + const analyticsConfigs = await ml.dataFrameAnalytics.getDataFrameAnalytics(jobId); + if ( + Array.isArray(analyticsConfigs.data_frame_analytics) && + analyticsConfigs.data_frame_analytics.length > 0 + ) { + const clonedJobConfig: any = analyticsConfigs.data_frame_analytics[0]; + await setJobClone(clonedJobConfig); + } + } })(); } }, []); + useEffect(() => { + if (activatedSteps[currentStep] === false) { + activatedSteps.splice(currentStep, 1, true); + setActivatedSteps(activatedSteps); + } + }, [currentStep]); + const analyticsWizardSteps = [ { title: i18n.translate('xpack.ml.dataframe.analytics.creation.configurationStepTitle', { @@ -127,10 +146,19 @@ export const Page: FC = () => {

- + {jobId === undefined && ( + + )} + {jobId !== undefined && ( + + )}

diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/action_clone.test.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/action_clone.test.ts index 9221f8c500326..01d92d8e192c1 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/action_clone.test.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/action_clone.test.ts @@ -140,8 +140,8 @@ describe('Analytics job clone action', () => { expect(isAdvancedConfig(advancedClassificationJob)).toBe(true); }); - test('should detect advanced outlier_detection job', () => { - const advancedOutlierDetectionJob = { + test('should detect advanced regression job', () => { + const advancedRegressionJob = { description: "Outlier detection job with 'glass' dataset", source: { index: ['glass_withoutdupl_norm'], @@ -155,10 +155,8 @@ describe('Analytics job clone action', () => { results_field: 'ml', }, analysis: { - outlier_detection: { - compute_feature_influence: false, - outlier_fraction: 0.05, - standardization_enabled: true, + regression: { + loss_function: 'msle', }, }, analyzed_fields: { @@ -168,7 +166,7 @@ describe('Analytics job clone action', () => { model_memory_limit: '1mb', allow_lazy_start: false, }; - expect(isAdvancedConfig(advancedOutlierDetectionJob)).toBe(true); + expect(isAdvancedConfig(advancedRegressionJob)).toBe(true); }); test('should detect a custom query', () => { @@ -207,32 +205,6 @@ describe('Analytics job clone action', () => { expect(isAdvancedConfig(advancedRegressionJob)).toBe(true); }); - test('should detect custom analysis settings', () => { - const config = { - description: "Classification clone with 'bank-marketing' dataset", - source: { - index: 'bank-marketing', - }, - dest: { - index: 'bank_classification4', - }, - analyzed_fields: { - excludes: [], - }, - analysis: { - classification: { - dependent_variable: 'y', - training_percent: 71, - max_trees: 1500, - num_top_feature_importance_values: 4, - }, - }, - model_memory_limit: '400mb', - }; - - expect(isAdvancedConfig(config)).toBe(true); - }); - test('should detect as advanced if the prop is unknown', () => { const config = { description: "Classification clone with 'bank-marketing' dataset", diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/action_clone.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/action_clone.tsx index cfb11856670c4..a1f0448b819d1 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/action_clone.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/action_clone.tsx @@ -8,10 +8,12 @@ import { EuiButtonEmpty } from '@elastic/eui'; import React, { FC } from 'react'; import { isEqual, cloneDeep } from 'lodash'; import { i18n } from '@kbn/i18n'; +import { IIndexPattern } from 'src/plugins/data/common'; import { DeepReadonly } from '../../../../../../../common/types/common'; import { DataFrameAnalyticsConfig, isOutlierAnalysis } from '../../../../common'; import { isClassificationAnalysis, isRegressionAnalysis } from '../../../../common/analytics'; import { DEFAULT_RESULTS_FIELD } from '../../../../common/constants'; +import { useMlKibana } from '../../../../../contexts/kibana'; import { CreateAnalyticsFormProps, DEFAULT_NUM_TOP_FEATURE_IMPORTANCE_VALUES, @@ -19,6 +21,7 @@ import { import { State } from '../../hooks/use_create_analytics_form/state'; import { DataFrameAnalyticsListRow } from './common'; import { checkPermission } from '../../../../../capabilities/check_capabilities'; +import { extractErrorMessage } from '../../../../../util/error_utils'; interface PropDefinition { /** @@ -74,31 +77,39 @@ const getAnalyticsJobMeta = (config: CloneDataFrameAnalyticsConfig): AnalyticsJo }, eta: { optional: true, + formKey: 'eta', }, feature_bag_fraction: { optional: true, + formKey: 'featureBagFraction', }, max_trees: { optional: true, + formKey: 'maxTrees', }, gamma: { optional: true, + formKey: 'gamma', }, lambda: { optional: true, + formKey: 'lambda', }, num_top_classes: { optional: true, defaultValue: 2, + formKey: 'numTopClasses', }, prediction_field_name: { optional: true, defaultValue: `${config.analysis.classification.dependent_variable}_prediction`, + formKey: 'predictionFieldName', }, randomize_seed: { optional: true, // By default it is randomly generated ignore: true, + formKey: 'randomizeSeed', }, num_top_feature_importance_values: { optional: true, @@ -118,23 +129,29 @@ const getAnalyticsJobMeta = (config: CloneDataFrameAnalyticsConfig): AnalyticsJo standardization_enabled: { defaultValue: true, optional: true, + formKey: 'standardizationEnabled', }, compute_feature_influence: { defaultValue: true, optional: true, + formKey: 'computeFeatureInfluence', }, outlier_fraction: { defaultValue: 0.05, optional: true, + formKey: 'outlierFraction', }, feature_influence_threshold: { optional: true, + formKey: 'featureInfluenceThreshold', }, method: { optional: true, + formKey: 'method', }, n_neighbors: { optional: true, + formKey: 'nNeighbors', }, }, } @@ -152,22 +169,28 @@ const getAnalyticsJobMeta = (config: CloneDataFrameAnalyticsConfig): AnalyticsJo }, eta: { optional: true, + formKey: 'eta', }, feature_bag_fraction: { optional: true, + formKey: 'featureBagFraction', }, max_trees: { optional: true, + formKey: 'maxTrees', }, gamma: { optional: true, + formKey: 'gamma', }, lambda: { optional: true, + formKey: 'lambda', }, prediction_field_name: { optional: true, defaultValue: `${config.analysis.regression.dependent_variable}_prediction`, + formKey: 'predictionFieldName', }, num_top_feature_importance_values: { optional: true, @@ -178,11 +201,15 @@ const getAnalyticsJobMeta = (config: CloneDataFrameAnalyticsConfig): AnalyticsJo optional: true, // By default it is randomly generated ignore: true, + formKey: 'randomizeSeed', }, loss_function: { optional: true, defaultValue: 'mse', }, + loss_function_parameter: { + optional: true, + }, }, } : {}), @@ -332,9 +359,52 @@ export const CloneAction: FC = ({ createAnalyticsForm, item }) const buttonText = i18n.translate('xpack.ml.dataframe.analyticsList.cloneJobButtonLabel', { defaultMessage: 'Clone job', }); - const { actions } = createAnalyticsForm; + + const { notifications, savedObjects } = useMlKibana().services; + const savedObjectsClient = savedObjects.client; + const onClick = async () => { - await actions.setJobClone(item.config); + const sourceIndex = Array.isArray(item.config.source.index) + ? item.config.source.index[0] + : item.config.source.index; + let sourceIndexId; + + try { + const response = await savedObjectsClient.find({ + type: 'index-pattern', + perPage: 10, + search: `"${sourceIndex}"`, + searchFields: ['title'], + fields: ['title'], + }); + + const ip = response.savedObjects.find( + (obj) => obj.attributes.title.toLowerCase() === sourceIndex.toLowerCase() + ); + if (ip !== undefined) { + sourceIndexId = ip.id; + } + } catch (e) { + const { toasts } = notifications; + const error = extractErrorMessage(e); + + toasts.addDanger( + i18n.translate( + 'xpack.ml.dataframe.analyticsList.fetchSourceIndexPatternForCloneErrorMessage', + { + defaultMessage: + 'An error occurred checking if index pattern {indexPattern} exists: {error}', + values: { indexPattern: sourceIndex, error }, + } + ) + ); + } + + if (sourceIndexId) { + window.location.href = `ml#/data_frame_analytics/new_job?index=${encodeURIComponent( + sourceIndexId + )}&jobId=${item.config.id}`; + } }; return ( diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/actions.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/actions.tsx index 295a3988e1b58..72514c91ff58b 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/actions.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/actions.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { i18n } from '@kbn/i18n'; import { EuiButtonEmpty, EuiToolTip } from '@elastic/eui'; -// import { DeepReadonly } from '../../../../../../../common/types/common'; +import { DeepReadonly } from '../../../../../../../common/types/common'; import { checkPermission, @@ -21,7 +21,7 @@ import { isClassificationAnalysis, } from '../../../../common/analytics'; import { CreateAnalyticsFormProps } from '../../hooks/use_create_analytics_form'; -// import { CloneAction } from './action_clone'; +import { CloneAction } from './action_clone'; import { getResultsUrl, isDataFrameAnalyticsRunning, DataFrameAnalyticsListRow } from './common'; import { stopAnalytics } from '../../services/analytics_service'; @@ -106,10 +106,10 @@ export const getActions = (createAnalyticsForm: CreateAnalyticsFormProps) => { return ; }, }, - // { - // render: (item: DeepReadonly) => { - // return ; - // }, - // }, + { + render: (item: DeepReadonly) => { + return ; + }, + }, ]; }; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/analytics_list.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/analytics_list.tsx index bb012a2190859..25e3a2808fc61 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/analytics_list.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/analytics_list.tsx @@ -51,7 +51,6 @@ import { AnalyticStatsBarStats, StatsBar } from '../../../../../components/stats import { RefreshAnalyticsListButton } from '../refresh_analytics_list_button'; import { CreateAnalyticsButton } from '../create_analytics_button'; import { CreateAnalyticsFormProps } from '../../hooks/use_create_analytics_form'; -import { CreateAnalyticsFlyoutWrapper } from '../create_analytics_flyout_wrapper'; import { getSelectedJobIdFromUrl } from '../../../../../jobs/jobs_list/components/utils'; import { SourceSelection } from '../source_selection'; @@ -286,9 +285,6 @@ export const DataFrameAnalyticsList: FC = ({ } data-test-subj="mlNoDataFrameAnalyticsFound" /> - {!isManagementTable && createAnalyticsForm && ( - - )} {isSourceIndexModalVisible === true && ( setIsSourceIndexModalVisible(false)} /> )} @@ -440,9 +436,6 @@ export const DataFrameAnalyticsList: FC = ({ /> - {!isManagementTable && createAnalyticsForm?.state.isModalVisible && ( - - )} {isSourceIndexModalVisible === true && ( setIsSourceIndexModalVisible(false)} /> )} diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout/_create_analytics_flyout.scss b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout/_create_analytics_flyout.scss deleted file mode 100644 index e6c6ffafc446a..0000000000000 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout/_create_analytics_flyout.scss +++ /dev/null @@ -1,3 +0,0 @@ -.mlAnalyticsCreateFlyout__footerButton { - float: right; -} diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout/_index.scss b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout/_index.scss deleted file mode 100644 index 668b35f8370d2..0000000000000 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout/_index.scss +++ /dev/null @@ -1 +0,0 @@ -@import 'create_analytics_flyout'; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout/create_analytics_flyout.test.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout/create_analytics_flyout.test.tsx deleted file mode 100644 index dc91c955184b0..0000000000000 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout/create_analytics_flyout.test.tsx +++ /dev/null @@ -1,42 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { mount } from 'enzyme'; -import React from 'react'; -import { mountHook } from 'test_utils/enzyme_helpers'; - -import { CreateAnalyticsFlyout } from './create_analytics_flyout'; - -import { MlContext } from '../../../../../contexts/ml'; -import { kibanaContextValueMock } from '../../../../../contexts/ml/__mocks__/kibana_context_value'; - -import { useCreateAnalyticsForm } from '../../hooks/use_create_analytics_form'; - -const getMountedHook = () => - mountHook( - () => useCreateAnalyticsForm(), - ({ children }) => ( - {children} - ) - ); - -// workaround to make React.memo() work with enzyme -jest.mock('react', () => { - const r = jest.requireActual('react'); - return { ...r, memo: (x: any) => x }; -}); - -describe('Data Frame Analytics: ', () => { - test('Minimal initialization', () => { - const { getLastHookValue } = getMountedHook(); - const props = getLastHookValue(); - const wrapper = mount(); - - expect(wrapper.find('[data-test-subj="mlDataFrameAnalyticsFlyoutHeaderTitle"]').text()).toBe( - 'Create analytics job' - ); - }); -}); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout/create_analytics_flyout.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout/create_analytics_flyout.tsx deleted file mode 100644 index b0f13e398cc50..0000000000000 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout/create_analytics_flyout.tsx +++ /dev/null @@ -1,108 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { FC } from 'react'; - -import { - EuiButton, - EuiButtonEmpty, - EuiFlyout, - EuiFlyoutBody, - EuiFlyoutHeader, - EuiFlyoutFooter, - EuiTitle, -} from '@elastic/eui'; - -import { i18n } from '@kbn/i18n'; - -import { CreateAnalyticsFormProps } from '../../hooks/use_create_analytics_form'; - -export const CreateAnalyticsFlyout: FC = ({ - actions, - children, - state, -}) => { - const { closeModal, createAnalyticsJob, startAnalyticsJob } = actions; - const { - isJobCreated, - isJobStarted, - isModalButtonDisabled, - isValid, - isAdvancedEditorValidJson, - cloneJob, - } = state; - - const headerText = !!cloneJob - ? i18n.translate('xpack.ml.dataframe.analytics.clone.flyoutHeaderTitle', { - defaultMessage: 'Clone job from {job_id}', - values: { job_id: cloneJob.id }, - }) - : i18n.translate('xpack.ml.dataframe.analytics.create.flyoutHeaderTitle', { - defaultMessage: 'Create analytics job', - }); - - return ( - - - -

{headerText}

-
-
- {children} - - {(!isJobCreated || !isJobStarted) && ( - - {isJobCreated === true - ? i18n.translate('xpack.ml.dataframe.analytics.create.flyoutCloseButton', { - defaultMessage: 'Close', - }) - : i18n.translate('xpack.ml.dataframe.analytics.create.flyoutCancelButton', { - defaultMessage: 'Cancel', - })} - - )} - - {!isJobCreated && !isJobStarted && ( - - {i18n.translate('xpack.ml.dataframe.analytics.create.flyoutCreateButton', { - defaultMessage: 'Create', - })} - - )} - {isJobCreated && !isJobStarted && ( - - {i18n.translate('xpack.ml.dataframe.analytics.create.flyoutStartButton', { - defaultMessage: 'Start', - })} - - )} - {isJobCreated && isJobStarted && ( - - {i18n.translate('xpack.ml.dataframe.analytics.create.flyoutCloseButton', { - defaultMessage: 'Close', - })} - - )} - -
- ); -}; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout_wrapper/create_analytics_flyout_wrapper.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout_wrapper/create_analytics_flyout_wrapper.tsx deleted file mode 100644 index 2f3c38b6ffe4e..0000000000000 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout_wrapper/create_analytics_flyout_wrapper.tsx +++ /dev/null @@ -1,28 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { FC } from 'react'; - -import { CreateAnalyticsFormProps } from '../../hooks/use_create_analytics_form'; - -import { CreateAnalyticsAdvancedEditor } from '../create_analytics_advanced_editor'; -import { CreateAnalyticsForm } from '../create_analytics_form'; -import { CreateAnalyticsFlyout } from '../create_analytics_flyout'; - -export const CreateAnalyticsFlyoutWrapper: FC = (props) => { - const { isAdvancedEditorEnabled, isModalVisible } = props.state; - - if (isModalVisible === false) { - return null; - } - - return ( - - {isAdvancedEditorEnabled === false && } - {isAdvancedEditorEnabled === true && } - - ); -}; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/_create_analytics_form.scss b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/_create_analytics_form.scss deleted file mode 100644 index 9b4559f9e2cb2..0000000000000 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/_create_analytics_form.scss +++ /dev/null @@ -1,31 +0,0 @@ -/* - The job creation form displayed in the modal adapts its height dynamically - if the content changes. If a form element changes to show/hide error messages, - this results in a changing height of the modal. If you type quickly e.g. - in the job ID input field and type chars which are invalid only for example - at the end of the string, this will result in an unwanted height toggling - effect. The following CSS avoids this by 1) delaying the visilibity of the - error message by 500ms and 2) animating the height and opacity to create - a fade-in effect after that so the modal grows smoothly and doesn't - toggle its height. - */ - -@keyframes mlDelayedShow { - 0%, 50% { - max-height: 0; - opacity: 0; - padding: 0; - visibility: hidden; - } - 100% { - max-height: 300px; - opacity: 1; - padding-top: $euiSizeS; - } -} - -.mlDataFrameAnalyticsCreateForm { - .euiFormErrorText { - animation: mlDelayedShow 1s; - } -} diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/_index.scss b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/_index.scss deleted file mode 100644 index 66fa2c02e60f5..0000000000000 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/_index.scss +++ /dev/null @@ -1 +0,0 @@ -@import 'create_analytics_form'; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/create_analytics_form.test.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/create_analytics_form.test.tsx deleted file mode 100644 index 85cd70912b41f..0000000000000 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/create_analytics_form.test.tsx +++ /dev/null @@ -1,69 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { mount } from 'enzyme'; -import React from 'react'; -import { mountHook } from 'test_utils/enzyme_helpers'; - -import { CreateAnalyticsForm } from './create_analytics_form'; - -import { MlContext } from '../../../../../contexts/ml'; -import { kibanaContextValueMock } from '../../../../../contexts/ml/__mocks__/kibana_context_value'; - -import { useCreateAnalyticsForm } from '../../hooks/use_create_analytics_form'; - -const getMountedHook = () => - mountHook( - () => useCreateAnalyticsForm(), - ({ children }) => ( - {children} - ) - ); - -// workaround to make React.memo() work with enzyme -jest.mock('react', () => { - const r = jest.requireActual('react'); - return { ...r, memo: (x: any) => x }; -}); - -jest.mock('../../../../../contexts/kibana', () => ({ - useMlKibana: () => { - return { - services: { - docLinks: () => ({ - ELASTIC_WEBSITE_URL: 'https://www.elastic.co/', - DOC_LINK_VERSION: 'jest-metadata-mock-branch', - }), - }, - }; - }, -})); - -describe('Data Frame Analytics: ', () => { - test('Minimal initialization', () => { - const { getLastHookValue } = getMountedHook(); - const props = getLastHookValue(); - const wrapper = mount( - - - - ); - - const euiFormRows = wrapper.find('EuiFormRow'); - expect(euiFormRows.length).toBe(10); - - const row1 = euiFormRows.at(0); - expect(row1.find('label').text()).toBe('Job type'); - - const options = row1.find('option'); - expect(options.at(0).props().value).toBe(''); - expect(options.at(1).props().value).toBe('outlier_detection'); - expect(options.at(2).props().value).toBe('regression'); - - const row2 = euiFormRows.at(1); - expect(row2.find('EuiSwitch').text()).toBe('Enable advanced editor'); - }); -}); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/create_analytics_form.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/create_analytics_form.tsx deleted file mode 100644 index 64fe736e67b17..0000000000000 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/create_analytics_form.tsx +++ /dev/null @@ -1,850 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { Fragment, FC, useEffect, useMemo, useRef } from 'react'; - -import { - EuiComboBox, - EuiComboBoxOptionOption, - EuiForm, - EuiFieldNumber, - EuiFieldText, - EuiFormRow, - EuiLink, - EuiRange, - EuiSwitch, -} from '@elastic/eui'; -import { debounce } from 'lodash'; - -import { i18n } from '@kbn/i18n'; -import { FormattedMessage } from '@kbn/i18n/react'; - -import { useMlKibana } from '../../../../../contexts/kibana'; -import { ml } from '../../../../../services/ml_api_service'; -import { newJobCapsService } from '../../../../../services/new_job_capabilities_service'; -import { useMlContext } from '../../../../../contexts/ml'; -import { CreateAnalyticsFormProps } from '../../hooks/use_create_analytics_form'; -import { - DEFAULT_MODEL_MEMORY_LIMIT, - getJobConfigFromFormState, - State, -} from '../../hooks/use_create_analytics_form/state'; -import { JOB_ID_MAX_LENGTH } from '../../../../../../../common/constants/validation'; -import { Messages } from './messages'; -import { JobType } from './job_type'; -import { JobDescriptionInput } from './job_description'; -import { getModelMemoryLimitErrors } from '../../hooks/use_create_analytics_form/reducer'; -import { IndexPattern, indexPatterns } from '../../../../../../../../../../src/plugins/data/public'; -import { - ANALYSIS_CONFIG_TYPE, - DfAnalyticsExplainResponse, - FieldSelectionItem, - NUM_TOP_FEATURE_IMPORTANCE_VALUES_MIN, - TRAINING_PERCENT_MIN, - TRAINING_PERCENT_MAX, -} from '../../../../common/analytics'; -import { shouldAddAsDepVarOption, OMIT_FIELDS } from './form_options_validation'; - -const requiredFieldsErrorText = i18n.translate( - 'xpack.ml.dataframe.analytics.create.requiredFieldsErrorMessage', - { - defaultMessage: 'At least one field must be included in the analysis.', - } -); - -export const CreateAnalyticsForm: FC = ({ actions, state }) => { - const { - services: { docLinks }, - } = useMlKibana(); - const { ELASTIC_WEBSITE_URL, DOC_LINK_VERSION } = docLinks; - const { setFormState, setEstimatedModelMemoryLimit } = actions; - const mlContext = useMlContext(); - const { - estimatedModelMemoryLimit, - form, - indexPatternsMap, - isAdvancedEditorEnabled, - isJobCreated, - requestMessages, - } = state; - - const forceInput = useRef(null); - const firstUpdate = useRef(true); - - const { - createIndexPattern, - dependentVariable, - dependentVariableFetchFail, - dependentVariableOptions, - description, - destinationIndex, - destinationIndexNameEmpty, - destinationIndexNameExists, - destinationIndexNameValid, - destinationIndexPatternTitleExists, - excludes, - excludesOptions, - fieldOptionsFetchFail, - jobId, - jobIdEmpty, - jobIdExists, - jobIdValid, - jobIdInvalidMaxLength, - jobType, - loadingDepVarOptions, - loadingFieldOptions, - maxDistinctValuesError, - modelMemoryLimit, - modelMemoryLimitValidationResult, - numTopFeatureImportanceValues, - numTopFeatureImportanceValuesValid, - previousJobType, - previousSourceIndex, - requiredFieldsError, - sourceIndex, - sourceIndexNameEmpty, - sourceIndexNameValid, - sourceIndexContainsNumericalFields, - sourceIndexFieldsCheckFailed, - trainingPercent, - } = form; - const characterList = indexPatterns.ILLEGAL_CHARACTERS_VISIBLE.join(', '); - - const mmlErrors = useMemo(() => getModelMemoryLimitErrors(modelMemoryLimitValidationResult), [ - modelMemoryLimitValidationResult, - ]); - - const isJobTypeWithDepVar = - jobType === ANALYSIS_CONFIG_TYPE.REGRESSION || jobType === ANALYSIS_CONFIG_TYPE.CLASSIFICATION; - - // Find out if index pattern contain numeric fields. Provides a hint in the form - // that an analytics jobs is not able to identify outliers if there are no numeric fields present. - const validateSourceIndexFields = async () => { - try { - const indexPattern: IndexPattern = await mlContext.indexPatterns.get( - indexPatternsMap[sourceIndex].value - ); - const containsNumericalFields: boolean = indexPattern.fields.some( - ({ name, type }) => !OMIT_FIELDS.includes(name) && type === 'number' - ); - - setFormState({ - sourceIndexContainsNumericalFields: containsNumericalFields, - sourceIndexFieldsCheckFailed: false, - }); - } catch (e) { - setFormState({ - sourceIndexFieldsCheckFailed: true, - }); - } - }; - - const onCreateOption = (searchValue: string, flattenedOptions: EuiComboBoxOptionOption[]) => { - const normalizedSearchValue = searchValue.trim().toLowerCase(); - - if (!normalizedSearchValue) { - return; - } - - const newOption = { - label: searchValue, - }; - - // Create the option if it doesn't exist. - if ( - !flattenedOptions.some( - (option: EuiComboBoxOptionOption) => - option.label.trim().toLowerCase() === normalizedSearchValue - ) - ) { - excludesOptions.push(newOption); - setFormState({ excludes: [...excludes, newOption.label] }); - } - }; - - const debouncedGetExplainData = debounce(async () => { - const jobTypeOrIndexChanged = - previousSourceIndex !== sourceIndex || previousJobType !== jobType; - const shouldUpdateModelMemoryLimit = !firstUpdate.current || !modelMemoryLimit; - const shouldUpdateEstimatedMml = - !firstUpdate.current || !modelMemoryLimit || estimatedModelMemoryLimit === ''; - - if (firstUpdate.current) { - firstUpdate.current = false; - } - // Reset if sourceIndex or jobType changes (jobType requires dependent_variable to be set - - // which won't be the case if switching from outlier detection) - if (jobTypeOrIndexChanged) { - setFormState({ - loadingFieldOptions: true, - }); - } - - try { - const jobConfig = getJobConfigFromFormState(form); - delete jobConfig.dest; - delete jobConfig.model_memory_limit; - const resp: DfAnalyticsExplainResponse = await ml.dataFrameAnalytics.explainDataFrameAnalytics( - jobConfig - ); - const expectedMemoryWithoutDisk = resp.memory_estimation?.expected_memory_without_disk; - - if (shouldUpdateEstimatedMml) { - setEstimatedModelMemoryLimit(expectedMemoryWithoutDisk); - } - - const fieldSelection: FieldSelectionItem[] | undefined = resp.field_selection; - - let hasRequiredFields = false; - if (fieldSelection) { - for (let i = 0; i < fieldSelection.length; i++) { - const field = fieldSelection[i]; - if (field.is_included === true && field.is_required === false) { - hasRequiredFields = true; - break; - } - } - } - - // If sourceIndex has changed load analysis field options again - if (jobTypeOrIndexChanged) { - const analyzedFieldsOptions: EuiComboBoxOptionOption[] = []; - - if (resp.field_selection) { - resp.field_selection.forEach((selectedField: FieldSelectionItem) => { - if (selectedField.is_included === true && selectedField.name !== dependentVariable) { - analyzedFieldsOptions.push({ label: selectedField.name }); - } - }); - } - - setFormState({ - ...(shouldUpdateModelMemoryLimit ? { modelMemoryLimit: expectedMemoryWithoutDisk } : {}), - excludesOptions: analyzedFieldsOptions, - loadingFieldOptions: false, - fieldOptionsFetchFail: false, - maxDistinctValuesError: undefined, - requiredFieldsError: !hasRequiredFields ? requiredFieldsErrorText : undefined, - }); - } else { - setFormState({ - ...(shouldUpdateModelMemoryLimit ? { modelMemoryLimit: expectedMemoryWithoutDisk } : {}), - requiredFieldsError: !hasRequiredFields ? requiredFieldsErrorText : undefined, - }); - } - } catch (e) { - let errorMessage; - if ( - jobType === ANALYSIS_CONFIG_TYPE.CLASSIFICATION && - e.body && - e.body.message !== undefined && - e.body.message.includes('status_exception') && - e.body.message.includes('must have at most') - ) { - errorMessage = e.body.message; - } - const fallbackModelMemoryLimit = - jobType !== undefined - ? DEFAULT_MODEL_MEMORY_LIMIT[jobType] - : DEFAULT_MODEL_MEMORY_LIMIT.outlier_detection; - setEstimatedModelMemoryLimit(fallbackModelMemoryLimit); - setFormState({ - fieldOptionsFetchFail: true, - maxDistinctValuesError: errorMessage, - loadingFieldOptions: false, - ...(shouldUpdateModelMemoryLimit ? { modelMemoryLimit: fallbackModelMemoryLimit } : {}), - }); - } - }, 400); - - const loadDepVarOptions = async (formState: State['form']) => { - setFormState({ - loadingDepVarOptions: true, - // clear when the source index changes - maxDistinctValuesError: undefined, - sourceIndexFieldsCheckFailed: false, - sourceIndexContainsNumericalFields: true, - }); - try { - const indexPattern: IndexPattern = await mlContext.indexPatterns.get( - indexPatternsMap[sourceIndex].value - ); - - if (indexPattern !== undefined) { - const formStateUpdate: { - loadingDepVarOptions: boolean; - dependentVariableFetchFail: boolean; - dependentVariableOptions: State['form']['dependentVariableOptions']; - dependentVariable?: State['form']['dependentVariable']; - } = { - loadingDepVarOptions: false, - dependentVariableFetchFail: false, - dependentVariableOptions: [] as State['form']['dependentVariableOptions'], - }; - - await newJobCapsService.initializeFromIndexPattern(indexPattern, false, false); - // Get fields and filter for supported types for job type - const { fields } = newJobCapsService; - - let resetDependentVariable = true; - for (const field of fields) { - if (shouldAddAsDepVarOption(field, jobType)) { - formStateUpdate.dependentVariableOptions.push({ - label: field.id, - }); - - if (formState.dependentVariable === field.id) { - resetDependentVariable = false; - } - } - } - - if (resetDependentVariable) { - formStateUpdate.dependentVariable = ''; - } - - setFormState(formStateUpdate); - } - } catch (e) { - setFormState({ loadingDepVarOptions: false, dependentVariableFetchFail: true }); - } - }; - - const getSourceIndexErrorMessages = () => { - const errors = []; - if (!sourceIndexNameEmpty && !sourceIndexNameValid) { - errors.push( - - - - ); - } - - if (sourceIndexFieldsCheckFailed === true) { - errors.push( - - - - ); - } - - return errors; - }; - - const onSourceIndexChange = (selectedOptions: EuiComboBoxOptionOption[]) => { - setFormState({ - excludes: [], - excludesOptions: [], - previousSourceIndex: sourceIndex, - sourceIndex: selectedOptions[0].label || '', - requiredFieldsError: undefined, - }); - }; - - useEffect(() => { - if (isJobTypeWithDepVar && sourceIndexNameEmpty === false) { - loadDepVarOptions(form); - } - - if (jobType === ANALYSIS_CONFIG_TYPE.OUTLIER_DETECTION && sourceIndexNameEmpty === false) { - validateSourceIndexFields(); - } - }, [sourceIndex, jobType, sourceIndexNameEmpty]); - - useEffect(() => { - const hasBasicRequiredFields = - jobType !== undefined && sourceIndex !== '' && sourceIndexNameValid === true; - - const hasRequiredAnalysisFields = - (isJobTypeWithDepVar && dependentVariable !== '') || - jobType === ANALYSIS_CONFIG_TYPE.OUTLIER_DETECTION; - - if (hasBasicRequiredFields && hasRequiredAnalysisFields) { - debouncedGetExplainData(); - } - - return () => { - debouncedGetExplainData.cancel(); - }; - }, [ - jobType, - sourceIndex, - sourceIndexNameEmpty, - dependentVariable, - trainingPercent, - JSON.stringify(excludes), - ]); - - // Temp effect to close the context menu popover on Clone button click - useEffect(() => { - if (forceInput.current === null) { - return; - } - const evt = document.createEvent('MouseEvents'); - evt.initEvent('mouseup', true, true); - forceInput.current.dispatchEvent(evt); - }, []); - - const noSupportetdAnalysisFields = - excludesOptions.length === 0 && fieldOptionsFetchFail === false && !sourceIndexNameEmpty; - - return ( - - - {!isJobCreated && ( - - - - - - - { - if (input) { - forceInput.current = input; - } - }} - disabled={isJobCreated} - placeholder={i18n.translate('xpack.ml.dataframe.analytics.create.jobIdPlaceholder', { - defaultMessage: 'Job ID', - })} - value={jobId} - onChange={(e) => setFormState({ jobId: e.target.value })} - aria-label={i18n.translate( - 'xpack.ml.dataframe.analytics.create.jobIdInputAriaLabel', - { - defaultMessage: 'Choose a unique analytics job ID.', - } - )} - isInvalid={(!jobIdEmpty && !jobIdValid) || jobIdExists} - data-test-subj="mlAnalyticsCreateJobFlyoutJobIdInput" - /> - - - - - {!isJobCreated && ( - - a.label.localeCompare(b.label) - )} - selectedOptions={ - indexPatternsMap[sourceIndex] !== undefined ? [{ label: sourceIndex }] : [] - } - onChange={onSourceIndexChange} - isClearable={false} - data-test-subj="mlAnalyticsCreateJobFlyoutSourceIndexSelect" - /> - )} - {isJobCreated && ( - - )} - - - - {i18n.translate( - 'xpack.ml.dataframe.analytics.create.destinationIndexInvalidError', - { - defaultMessage: 'Invalid destination index name.', - } - )} -
- - {i18n.translate( - 'xpack.ml.dataframe.stepDetailsForm.destinationIndexInvalidErrorLink', - { - defaultMessage: 'Learn more about index name limitations.', - } - )} - -
, - ] - } - > - setFormState({ destinationIndex: e.target.value })} - aria-label={i18n.translate( - 'xpack.ml.dataframe.analytics.create.destinationIndexInputAriaLabel', - { - defaultMessage: 'Choose a unique destination index name.', - } - )} - isInvalid={!destinationIndexNameEmpty && !destinationIndexNameValid} - data-test-subj="mlAnalyticsCreateJobFlyoutDestinationIndexInput" - /> - - {(jobType === ANALYSIS_CONFIG_TYPE.REGRESSION || - jobType === ANALYSIS_CONFIG_TYPE.CLASSIFICATION) && ( - - - {i18n.translate( - 'xpack.ml.dataframe.analytics.create.dependentVariableMaxDistictValuesError', - { - defaultMessage: 'Invalid. {message}', - values: { message: maxDistinctValuesError }, - } - )} - , - ] - : []), - ]} - > - - - - {i18n.translate( - 'xpack.ml.dataframe.analytics.create.dependentVariableOptionsFetchError', - { - defaultMessage: - 'There was a problem fetching fields. Please refresh the page and try again.', - } - )} - , - ] - : []), - ]} - > - - setFormState({ - dependentVariable: selectedOptions[0].label || '', - }) - } - isClearable={false} - isInvalid={dependentVariable === ''} - data-test-subj="mlAnalyticsCreateJobFlyoutDependentVariableSelect" - /> - - - setFormState({ trainingPercent: +e.target.value })} - data-test-subj="mlAnalyticsCreateJobFlyoutTrainingPercentSlider" - /> - - {/* num_top_feature_importance_values */} - - {i18n.translate( - 'xpack.ml.dataframe.analytics.create.numTopFeatureImportanceValuesErrorText', - { - defaultMessage: - 'Invalid maximum number of feature importance values.', - } - )} - , - ] - : []), - ]} - > - setFormState({ numTopFeatureImportanceValues: +e.target.value })} - step={1} - value={numTopFeatureImportanceValues} - /> - - - )} - - - - - ({ - label: field, - }))} - onCreateOption={onCreateOption} - onChange={(selectedOptions) => - setFormState({ excludes: selectedOptions.map((option) => option.label) }) - } - isClearable={true} - data-test-subj="mlAnalyticsCreateJobFlyoutExcludesSelect" - /> - - - setFormState({ modelMemoryLimit: e.target.value })} - isInvalid={modelMemoryLimitValidationResult !== null} - data-test-subj="mlAnalyticsCreateJobFlyoutModelMemoryInput" - /> - - - setFormState({ createIndexPattern: !createIndexPattern })} - data-test-subj="mlAnalyticsCreateJobFlyoutCreateIndexPatternSwitch" - /> - - - )} -
- ); -}; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_description.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_description.tsx deleted file mode 100644 index 46301a6f832e7..0000000000000 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_description.tsx +++ /dev/null @@ -1,37 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { FC } from 'react'; -import { EuiFormRow, EuiTextArea } from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; - -const helpText = i18n.translate('xpack.ml.dataframe.analytics.create.jobDescription.helpText', { - defaultMessage: 'Optional descriptive text', -}); - -interface Props { - description: string; - setFormState: React.Dispatch>; -} - -export const JobDescriptionInput: FC = ({ description, setFormState }) => ( - - { - const value = e.target.value; - setFormState({ description: value }); - }} - data-test-subj="mlDFAnalyticsJobCreationJobDescription" - /> - -); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_type.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_type.tsx deleted file mode 100644 index 6daa72dd805b1..0000000000000 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_type.tsx +++ /dev/null @@ -1,80 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { Fragment, FC } from 'react'; -import { i18n } from '@kbn/i18n'; - -import { EuiFormRow, EuiSelect } from '@elastic/eui'; -import { ANALYSIS_CONFIG_TYPE } from '../../../../common'; - -import { AnalyticsJobType } from '../../hooks/use_create_analytics_form/state'; - -interface Props { - type: AnalyticsJobType; - setFormState: React.Dispatch>; -} - -export const JobType: FC = ({ type, setFormState }) => { - const outlierHelpText = i18n.translate( - 'xpack.ml.dataframe.analytics.create.outlierDetectionHelpText', - { - defaultMessage: - 'Outlier detection jobs require a source index that is mapped as a table-like data structure and analyze only numeric and boolean fields. Use the advanced editor to add custom options to the configuration.', - } - ); - - const regressionHelpText = i18n.translate( - 'xpack.ml.dataframe.analytics.create.outlierRegressionHelpText', - { - defaultMessage: - 'Regression jobs analyze only numeric fields. Use the advanced editor to apply custom options, such as the prediction field name.', - } - ); - - const classificationHelpText = i18n.translate( - 'xpack.ml.dataframe.analytics.create.classificationHelpText', - { - defaultMessage: - 'Classification jobs require a source index that is mapped as a table-like data structure and support fields that are numeric, boolean, text, keyword, or ip. Use the advanced editor to apply custom options, such as the prediction field name.', - } - ); - - const helpText = { - [ANALYSIS_CONFIG_TYPE.REGRESSION]: regressionHelpText, - [ANALYSIS_CONFIG_TYPE.OUTLIER_DETECTION]: outlierHelpText, - [ANALYSIS_CONFIG_TYPE.CLASSIFICATION]: classificationHelpText, - }; - - return ( - - - ({ - value: jobType, - text: jobType.replace(/_/g, ' '), - }))} - value={type} - hasNoInitialSelection={true} - onChange={(e) => { - const value = e.target.value as AnalyticsJobType; - setFormState({ - previousJobType: type, - jobType: value, - excludes: [], - requiredFieldsError: undefined, - }); - }} - data-test-subj="mlAnalyticsCreateJobFlyoutJobTypeSelect" - /> - - - ); -}; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/actions.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/actions.ts index c42e03b584a56..a9eedbb2bc5e3 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/actions.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/actions.ts @@ -57,11 +57,6 @@ export type Action = } | { type: ACTION.SET_IS_JOB_CREATED; isJobCreated: State['isJobCreated'] } | { type: ACTION.SET_IS_JOB_STARTED; isJobStarted: State['isJobStarted'] } - | { - type: ACTION.SET_IS_MODAL_BUTTON_DISABLED; - isModalButtonDisabled: State['isModalButtonDisabled']; - } - | { type: ACTION.SET_IS_MODAL_VISIBLE; isModalVisible: State['isModalVisible'] } | { type: ACTION.SET_JOB_CONFIG; payload: State['jobConfig'] } | { type: ACTION.SET_JOB_IDS; jobIds: State['jobIds'] } | { type: ACTION.SET_ESTIMATED_MODEL_MEMORY_LIMIT; value: State['estimatedModelMemoryLimit'] } @@ -71,12 +66,10 @@ export type Action = export interface ActionDispatchers { closeModal: () => void; createAnalyticsJob: () => void; - openModal: () => Promise; initiateWizard: () => Promise; resetAdvancedEditorMessages: () => void; setAdvancedEditorRawString: (payload: State['advancedEditorRawString']) => void; setFormState: (payload: Partial) => void; - setIsModalVisible: (payload: State['isModalVisible']) => void; setJobConfig: (payload: State['jobConfig']) => void; startAnalyticsJob: () => void; switchToAdvancedEditor: () => void; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/reducer.test.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/reducer.test.ts index fc604c9f5eb0b..e6769a7b64e2b 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/reducer.test.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/reducer.test.ts @@ -79,21 +79,6 @@ describe('useCreateAnalyticsForm', () => { expect(resettedState).toEqual(initialState); }); - test('reducer(): open/close the modal', () => { - const initialState = getInitialState(); - expect(initialState.isModalVisible).toBe(false); - - const openModalState = reducer(initialState, { - type: ACTION.OPEN_MODAL, - }); - expect(openModalState.isModalVisible).toBe(true); - - const closedModalState = reducer(openModalState, { - type: ACTION.CLOSE_MODAL, - }); - expect(closedModalState.isModalVisible).toBe(false); - }); - test('reducer(): add/reset request messages', () => { const initialState = getInitialState(); expect(initialState.requestMessages).toHaveLength(0); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/reducer.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/reducer.ts index a79a8fcf61ed4..1353a35d8ecc6 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/reducer.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/reducer.ts @@ -442,12 +442,6 @@ export function reducer(state: State, action: Action): State { case ACTION.RESET_REQUEST_MESSAGES: return { ...state, requestMessages: [] }; - case ACTION.CLOSE_MODAL: - return { ...state, isModalVisible: false }; - - case ACTION.OPEN_MODAL: - return { ...state, isModalVisible: true }; - case ACTION.RESET_ADVANCED_EDITOR_MESSAGES: return { ...state, advancedEditorMessages: [] }; @@ -536,12 +530,6 @@ export function reducer(state: State, action: Action): State { case ACTION.SET_IS_JOB_STARTED: return { ...state, isJobStarted: action.isJobStarted }; - case ACTION.SET_IS_MODAL_BUTTON_DISABLED: - return { ...state, isModalButtonDisabled: action.isModalButtonDisabled }; - - case ACTION.SET_IS_MODAL_VISIBLE: - return { ...state, isModalVisible: action.isModalVisible }; - case ACTION.SET_JOB_CONFIG: return validateAdvancedEditor({ ...state, jobConfig: action.payload }); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.test.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.test.ts index 547a55da7438b..b9a9caadcebd0 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.test.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.test.ts @@ -4,7 +4,43 @@ * you may not use this file except in compliance with the Elastic License. */ -import { getInitialState, getJobConfigFromFormState } from './state'; +import { + getCloneFormStateFromJobConfig, + getInitialState, + getJobConfigFromFormState, +} from './state'; + +const regJobConfig = { + id: 'reg-test-01', + description: 'Reg test job description', + source: { + index: ['reg-test-index'], + query: { + match_all: {}, + }, + }, + dest: { + index: 'reg-test-01-index', + results_field: 'ml', + }, + analysis: { + regression: { + dependent_variable: 'price', + num_top_feature_importance_values: 2, + prediction_field_name: 'airbnb_test', + training_percent: 5, + randomize_seed: 4998776294664380000, + }, + }, + analyzed_fields: { + includes: [], + excludes: [], + }, + model_memory_limit: '22mb', + create_time: 1590514291395, + version: '8.0.0', + allow_lazy_start: false, +}; describe('useCreateAnalyticsForm', () => { test('state: getJobConfigFromFormState()', () => { @@ -28,4 +64,20 @@ describe('useCreateAnalyticsForm', () => { 'the-source-index-2', ]); }); + + test('state: getCloneFormStateFromJobConfig()', () => { + const clonedState = getCloneFormStateFromJobConfig(regJobConfig); + + expect(clonedState?.sourceIndex).toBe('reg-test-index'); + expect(clonedState?.excludes).toStrictEqual([]); + expect(clonedState?.dependentVariable).toBe('price'); + expect(clonedState?.numTopFeatureImportanceValues).toBe(2); + expect(clonedState?.predictionFieldName).toBe('airbnb_test'); + expect(clonedState?.trainingPercent).toBe(5); + expect(clonedState?.randomizeSeed).toBe(4998776294664380000); + expect(clonedState?.modelMemoryLimit).toBe('22mb'); + // destination index and job id should be undefined + expect(clonedState?.destinationIndex).toBe(undefined); + expect(clonedState?.jobId).toBe(undefined); + }); }); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts index 387ce89ee4120..8a07704e39910 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts @@ -92,7 +92,6 @@ export interface State { outlierFraction: undefined | number; predictionFieldName: undefined | string; previousJobType: null | AnalyticsJobType; - previousSourceIndex: EsIndexName | undefined; requiredFieldsError: string | undefined; randomizeSeed: undefined | number; sourceIndex: EsIndexName; @@ -110,8 +109,6 @@ export interface State { isAdvancedEditorValidJson: boolean; isJobCreated: boolean; isJobStarted: boolean; - isModalButtonDisabled: boolean; - isModalVisible: boolean; isValid: boolean; jobConfig: DeepPartial; jobIds: DataFrameAnalyticsId[]; @@ -167,7 +164,6 @@ export const getInitialState = (): State => ({ outlierFraction: undefined, predictionFieldName: undefined, previousJobType: null, - previousSourceIndex: undefined, requiredFieldsError: undefined, randomizeSeed: undefined, sourceIndex: '', @@ -189,8 +185,6 @@ export const getInitialState = (): State => ({ isAdvancedEditorValidJson: true, isJobCreated: false, isJobStarted: false, - isModalVisible: false, - isModalButtonDisabled: false, isValid: false, jobIds: [], requestMessages: [], @@ -328,6 +322,14 @@ export const getJobConfigFromFormState = ( return jobConfig; }; +function toCamelCase(property: string): string { + const camelCased = property.replace(/_([a-z])/g, function (g) { + return g[1].toUpperCase(); + }); + + return camelCased; +} + /** * Extracts form state for a job clone from the analytics job configuration. * For cloning we keep job id and destination index empty. @@ -353,13 +355,12 @@ export function getCloneFormStateFromJobConfig( ) { const analysisConfig = analyticsJobConfig.analysis[jobType]; - resultState.dependentVariable = analysisConfig.dependent_variable; - resultState.numTopFeatureImportanceValues = analysisConfig.num_top_feature_importance_values; - resultState.trainingPercent = analysisConfig.training_percent; - - if (isClassificationAnalysis(analyticsJobConfig.analysis)) { - // @ts-ignore - resultState.numTopClasses = analysisConfig.num_top_classes; + for (const key in analysisConfig) { + if (analysisConfig.hasOwnProperty(key)) { + const camelCased = toCamelCase(key); + // @ts-ignore + resultState[camelCased] = analysisConfig[key]; + } } } diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.test.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.test.tsx index 182e50a5d74d1..ac1c710e1d106 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.test.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.test.tsx @@ -46,39 +46,13 @@ describe('getErrorMessage()', () => { describe('useCreateAnalyticsForm()', () => { test('initialization', () => { const { getLastHookValue } = getMountedHook(); - const { state, actions } = getLastHookValue(); + const { actions } = getLastHookValue(); - expect(state.isModalVisible).toBe(false); - expect(typeof actions.closeModal).toBe('function'); expect(typeof actions.createAnalyticsJob).toBe('function'); - expect(typeof actions.openModal).toBe('function'); expect(typeof actions.startAnalyticsJob).toBe('function'); expect(typeof actions.setFormState).toBe('function'); }); - test('open/close modal', () => { - const { act, getLastHookValue } = getMountedHook(); - const { state, actions } = getLastHookValue(); - - expect(state.isModalVisible).toBe(false); - - act(() => { - // this should be actions.openModal(), but that doesn't work yet because act() doesn't support async yet. - // we need to wait for an update to React 16.9 - actions.setIsModalVisible(true); - }); - const { state: stateModalOpen } = getLastHookValue(); - expect(stateModalOpen.isModalVisible).toBe(true); - - act(() => { - // this should be actions.closeModal(), but that doesn't work yet because act() doesn't support async yet. - // we need to wait for an update to React 16.9 - actions.setIsModalVisible(false); - }); - const { state: stateModalClosed } = getLastHookValue(); - expect(stateModalClosed.isModalVisible).toBe(false); - }); - // TODO // add tests for createAnalyticsJob() and startAnalyticsJob() // once React 16.9 with support for async act() is available. diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts index c4cbe149f88bc..2de9a1dcadd4b 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts @@ -87,12 +87,6 @@ export const useCreateAnalyticsForm = (): CreateAnalyticsFormProps => { dispatch({ type: ACTION.SET_IS_JOB_STARTED, isJobStarted }); }; - const setIsModalButtonDisabled = (isModalButtonDisabled: boolean) => - dispatch({ type: ACTION.SET_IS_MODAL_BUTTON_DISABLED, isModalButtonDisabled }); - - const setIsModalVisible = (isModalVisible: boolean) => - dispatch({ type: ACTION.SET_IS_MODAL_VISIBLE, isModalVisible }); - const setJobIds = (jobIds: DataFrameAnalyticsId[]) => dispatch({ type: ACTION.SET_JOB_IDS, jobIds }); @@ -102,7 +96,6 @@ export const useCreateAnalyticsForm = (): CreateAnalyticsFormProps => { const createAnalyticsJob = async () => { resetRequestMessages(); - setIsModalButtonDisabled(true); const analyticsJobConfig = (isAdvancedEditorEnabled ? jobConfig @@ -123,7 +116,6 @@ export const useCreateAnalyticsForm = (): CreateAnalyticsFormProps => { } ), }); - setIsModalButtonDisabled(false); setIsJobCreated(true); if (createIndexPattern) { createKibanaIndexPattern(); @@ -139,7 +131,6 @@ export const useCreateAnalyticsForm = (): CreateAnalyticsFormProps => { } ), }); - setIsModalButtonDisabled(false); } }; @@ -267,13 +258,6 @@ export const useCreateAnalyticsForm = (): CreateAnalyticsFormProps => { } }; - const openModal = async () => { - await mlContext.indexPatterns.clearCache(); - resetForm(); - await prepareFormValidation(); - dispatch({ type: ACTION.OPEN_MODAL }); - }; - const initiateWizard = async () => { await mlContext.indexPatterns.clearCache(); await prepareFormValidation(); @@ -327,8 +311,6 @@ export const useCreateAnalyticsForm = (): CreateAnalyticsFormProps => { const setJobClone = async (cloneJob: DeepReadonly) => { resetForm(); - await prepareFormValidation(); - const config = extractCloningConfig(cloneJob); if (isAdvancedConfig(config)) { setJobConfig(config); @@ -339,18 +321,15 @@ export const useCreateAnalyticsForm = (): CreateAnalyticsFormProps => { } dispatch({ type: ACTION.SET_JOB_CLONE, cloneJob }); - dispatch({ type: ACTION.OPEN_MODAL }); }; const actions: ActionDispatchers = { closeModal, createAnalyticsJob, - openModal, initiateWizard, resetAdvancedEditorMessages, setAdvancedEditorRawString, setFormState, - setIsModalVisible, setJobConfig, startAnalyticsJob, switchToAdvancedEditor, diff --git a/x-pack/plugins/ml/public/application/routing/routes/data_frame_analytics/analytics_job_creation.tsx b/x-pack/plugins/ml/public/application/routing/routes/data_frame_analytics/analytics_job_creation.tsx index 68af9a2a49cab..ebc7bd95fb0c3 100644 --- a/x-pack/plugins/ml/public/application/routing/routes/data_frame_analytics/analytics_job_creation.tsx +++ b/x-pack/plugins/ml/public/application/routing/routes/data_frame_analytics/analytics_job_creation.tsx @@ -30,12 +30,15 @@ export const analyticsJobsCreationRoute: MlRoute = { }; const PageWrapper: FC = ({ location, deps }) => { - const { index, savedSearchId }: Record = parse(location.search, { sort: false }); + const { index, jobId, savedSearchId }: Record = parse(location.search, { + sort: false, + }); + const { context } = useResolver(index, savedSearchId, deps.config, basicResolvers(deps)); return ( - + ); }; diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/manifest.json index 4c0186023b458..11d4f8e0b97df 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/manifest.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/manifest.json @@ -7,7 +7,7 @@ "defaultIndexPattern": "kibana_sample_data_ecommerce", "query": { "bool": { - "filter": [{ "term": { "_index": "kibana_sample_data_ecommerce" } }] + "filter": [{ "term": { "event.dataset": "sample_ecommerce" } }] } }, "jobs": [ diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/ml/datafeed_high_sum_total_sales.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/ml/datafeed_high_sum_total_sales.json index 0a955a766bd53..d61e6ba22ec2f 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/ml/datafeed_high_sum_total_sales.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/ml/datafeed_high_sum_total_sales.json @@ -3,7 +3,7 @@ "indices": ["INDEX_PATTERN_NAME"], "query": { "bool": { - "filter": [{ "term": { "_index": "kibana_sample_data_ecommerce" } }] + "filter": [{ "term": { "event.dataset": "sample_ecommerce" } }] } } } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/manifest.json index a0b47e7135312..446f56a717e11 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/manifest.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/manifest.json @@ -7,7 +7,7 @@ "defaultIndexPattern": "kibana_sample_data_logs", "query": { "bool": { - "filter": [{ "term": { "_index": "kibana_sample_data_logs" } }] + "filter": [{ "term": { "event.dataset": "sample_web_logs" } }] } }, "jobs": [ diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_low_request_rate.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_low_request_rate.json index 843a7d1651dc8..a9865183320d5 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_low_request_rate.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_low_request_rate.json @@ -3,7 +3,7 @@ "indices": ["INDEX_PATTERN_NAME"], "query": { "bool": { - "filter": [{ "term": { "_index": "kibana_sample_data_logs" } }] + "filter": [{ "term": { "event.dataset": "sample_web_logs" } }] } }, "aggregations": { diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_response_code_rates.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_response_code_rates.json index 3a0f67daa392a..9aef3386cb9ef 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_response_code_rates.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_response_code_rates.json @@ -3,7 +3,7 @@ "indices": ["INDEX_PATTERN_NAME"], "query": { "bool": { - "filter": [{ "term": { "_index": "kibana_sample_data_logs" } }] + "filter": [{ "term": { "event.dataset": "sample_web_logs" } }] } } } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_url_scanning.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_url_scanning.json index 3a0f67daa392a..9aef3386cb9ef 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_url_scanning.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_url_scanning.json @@ -3,7 +3,7 @@ "indices": ["INDEX_PATTERN_NAME"], "query": { "bool": { - "filter": [{ "term": { "_index": "kibana_sample_data_logs" } }] + "filter": [{ "term": { "event.dataset": "sample_web_logs" } }] } } } diff --git a/x-pack/plugins/security_solution/common/constants.ts b/x-pack/plugins/security_solution/common/constants.ts index d04d1f2c91b97..7a2b531346ac3 100644 --- a/x-pack/plugins/security_solution/common/constants.ts +++ b/x-pack/plugins/security_solution/common/constants.ts @@ -143,3 +143,9 @@ export const showAllOthersBucket: string[] = [ 'destination.ip', 'user.name', ]; + +/** + * CreateTemplateTimelineBtn + * Remove the comment here to enable template timeline + */ +export const disableTemplate = true; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/common/schemas.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/common/schemas.ts index 9eb2d9abccbd3..7db8e57421d02 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/common/schemas.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/common/schemas.ts @@ -14,16 +14,35 @@ import { PositiveIntegerGreaterThanZero } from '../types/positive_integer_greate import { PositiveInteger } from '../types/positive_integer'; export const description = t.string; +export type Description = t.TypeOf; + +export const descriptionOrUndefined = t.union([description, t.undefined]); +export type DescriptionOrUndefined = t.TypeOf; + export const enabled = t.boolean; -export const exclude_export_details = t.boolean; +export type Enabled = t.TypeOf; + +export const enabledOrUndefined = t.union([enabled, t.undefined]); +export type EnabledOrUndefined = t.TypeOf; + export const false_positives = t.array(t.string); +export type FalsePositives = t.TypeOf; + +export const falsePositivesOrUndefined = t.union([false_positives, t.undefined]); +export type FalsePositivesOrUndefined = t.TypeOf; + export const file_name = t.string; +export type FileName = t.TypeOf; + +export const exclude_export_details = t.boolean; +export type ExcludeExportDetails = t.TypeOf; /** * TODO: Right now the filters is an "unknown", when it could more than likely * become the actual ESFilter as a type. */ export const filters = t.array(t.unknown); // Filters are not easily type-able yet +export type Filters = t.TypeOf; // Filters are not easily type-able yet /** * Params is an "object", since it is a type of AlertActionParams which is action templates. @@ -43,30 +62,98 @@ export const action = t.exact( ); export const actions = t.array(action); +export type Actions = t.TypeOf; // TODO: Create a regular expression type or custom date math part type here export const from = t.string; +export type From = t.TypeOf; + +export const fromOrUndefined = t.union([from, t.undefined]); +export type FromOrUndefined = t.TypeOf; export const immutable = t.boolean; +export type Immutable = t.TypeOf; // Note: Never make this a strict uuid, we allow the rule_id to be any string at the moment // in case we encounter 3rd party rule systems which might be using auto incrementing numbers // or other different things. export const rule_id = t.string; +export type RuleId = t.TypeOf; + +export const ruleIdOrUndefined = t.union([rule_id, t.undefined]); +export type RuleIdOrUndefined = t.TypeOf; export const id = UUID; +export const idOrUndefined = t.union([id, t.undefined]); +export type IdOrUndefined = t.TypeOf; + export const index = t.array(t.string); +export type Index = t.TypeOf; + +export const indexOrUndefined = t.union([index, t.undefined]); +export type IndexOrUndefined = t.TypeOf; + export const interval = t.string; +export type Interval = t.TypeOf; + +export const intervalOrUndefined = t.union([interval, t.undefined]); +export type IntervalOrUndefined = t.TypeOf; + export const query = t.string; +export type Query = t.TypeOf; + +export const queryOrUndefined = t.union([query, t.undefined]); +export type QueryOrUndefined = t.TypeOf; + export const language = t.keyof({ kuery: null, lucene: null }); +export type Language = t.TypeOf; + +export const languageOrUndefined = t.union([language, t.undefined]); +export type LanguageOrUndefined = t.TypeOf; + export const objects = t.array(t.type({ rule_id })); + export const output_index = t.string; +export type OutputIndex = t.TypeOf; + +export const outputIndexOrUndefined = t.union([output_index, t.undefined]); +export type OutputIndexOrUndefined = t.TypeOf; + export const saved_id = t.string; +export type SavedId = t.TypeOf; + +export const savedIdOrUndefined = t.union([saved_id, t.undefined]); +export type SavedIdOrUndefined = t.TypeOf; + export const timeline_id = t.string; +export type TimelineId = t.TypeOf; + +export const timelineIdOrUndefined = t.union([timeline_id, t.undefined]); +export type TimelineIdOrUndefined = t.TypeOf; + export const timeline_title = t.string; +export type TimelineTitle = t.TypeOf; + +export const timelineTitleOrUndefined = t.union([timeline_title, t.undefined]); +export type TimelineTitleOrUndefined = t.TypeOf; + export const throttle = t.string; +export type Throttle = t.TypeOf; + +export const throttleOrNull = t.union([throttle, t.null]); +export type ThrottleOrNull = t.TypeOf; + export const anomaly_threshold = PositiveInteger; +export type AnomalyThreshold = t.TypeOf; + +export const anomalyThresholdOrUndefined = t.union([anomaly_threshold, t.undefined]); +export type AnomalyThresholdOrUndefined = t.TypeOf; + export const machine_learning_job_id = t.string; +export type MachineLearningJobId = t.TypeOf; + +export const machineLearningJobIdOrUndefined = t.union([machine_learning_job_id, t.undefined]); +export type MachineLearningJobIdOrUndefined = t.TypeOf; /** * Note that this is a plain unknown object because we allow the UI @@ -76,30 +163,103 @@ export const machine_learning_job_id = t.string; * so we have tighter control over 3rd party data structures. */ export const meta = t.object; +export type Meta = t.TypeOf; +export const metaOrUndefined = t.union([meta, t.undefined]); +export type MetaOrUndefined = t.TypeOf; + export const max_signals = PositiveIntegerGreaterThanZero; +export type MaxSignals = t.TypeOf; + +export const maxSignalsOrUndefined = t.union([max_signals, t.undefined]); +export type MaxSignalsOrUndefined = t.TypeOf; + export const name = t.string; +export type Name = t.TypeOf; + +export const nameOrUndefined = t.union([name, t.undefined]); +export type NameOrUndefined = t.TypeOf; + export const risk_score = RiskScore; +export type RiskScore = t.TypeOf; + +export const riskScoreOrUndefined = t.union([risk_score, t.undefined]); +export type RiskScoreOrUndefined = t.TypeOf; + export const severity = t.keyof({ low: null, medium: null, high: null, critical: null }); +export type Severity = t.TypeOf; + +export const severityOrUndefined = t.union([severity, t.undefined]); +export type SeverityOrUndefined = t.TypeOf; + export const status = t.keyof({ open: null, closed: null }); + export const job_status = t.keyof({ succeeded: null, failed: null, 'going to run': null }); // TODO: Create a regular expression type or custom date math part type here export const to = t.string; +export type To = t.TypeOf; + +export const toOrUndefined = t.union([to, t.undefined]); +export type ToOrUndefined = t.TypeOf; export const type = t.keyof({ machine_learning: null, query: null, saved_query: null }); +export type Type = t.TypeOf; + +export const typeOrUndefined = t.union([type, t.undefined]); +export type TypeOrUndefined = t.TypeOf; + export const queryFilter = t.string; +export type QueryFilter = t.TypeOf; + +export const queryFilterOrUndefined = t.union([queryFilter, t.undefined]); +export type QueryFilterOrUndefined = t.TypeOf; + export const references = t.array(t.string); +export type References = t.TypeOf; + +export const referencesOrUndefined = t.union([references, t.undefined]); +export type ReferencesOrUndefined = t.TypeOf; + export const per_page = PositiveInteger; +export type PerPage = t.TypeOf; + +export const perPageOrUndefined = t.union([per_page, t.undefined]); +export type PerPageOrUndefined = t.TypeOf; + export const page = PositiveIntegerGreaterThanZero; +export type Page = t.TypeOf; + +export const pageOrUndefined = t.union([page, t.undefined]); +export type PageOrUndefined = t.TypeOf; + export const signal_ids = t.array(t.string); // TODO: Can this be more strict or is this is the set of all Elastic Queries? export const signal_status_query = t.object; export const sort_field = t.string; +export type SortField = t.TypeOf; + +export const sortFieldOrUndefined = t.union([sort_field, t.undefined]); +export type SortFieldOrUndefined = t.TypeOf; + export const sort_order = t.keyof({ asc: null, desc: null }); +export type sortOrder = t.TypeOf; + +export const sortOrderOrUndefined = t.union([sort_order, t.undefined]); +export type SortOrderOrUndefined = t.TypeOf; + export const tags = t.array(t.string); +export type Tags = t.TypeOf; + +export const tagsOrUndefined = t.union([tags, t.undefined]); +export type TagsOrUndefined = t.TypeOf; + export const fields = t.array(t.string); +export type Fields = t.TypeOf; +export const fieldsOrUndefined = t.union([fields, t.undefined]); +export type FieldsOrUndefined = t.TypeOf; + export const threat_framework = t.string; export const threat_tactic_id = t.string; export const threat_tactic_name = t.string; @@ -129,11 +289,23 @@ export const threat = t.array( }) ) ); + +export type Threat = t.TypeOf; + +export const threatOrUndefined = t.union([threat, t.undefined]); +export type ThreatOrUndefined = t.TypeOf; + export const created_at = IsoDateString; export const updated_at = IsoDateString; export const updated_by = t.string; export const created_by = t.string; + export const version = PositiveIntegerGreaterThanZero; +export type Version = t.TypeOf; + +export const versionOrUndefined = t.union([version, t.undefined]); +export type VersionOrUndefined = t.TypeOf; + export const last_success_at = IsoDateString; export const last_success_message = t.string; export const last_failure_at = IsoDateString; @@ -150,7 +322,12 @@ export const success_count = PositiveInteger; export const rules_custom_installed = PositiveInteger; export const rules_not_installed = PositiveInteger; export const rules_not_updated = PositiveInteger; + export const note = t.string; +export type Note = t.TypeOf; + +export const noteOrUndefined = t.union([note, t.undefined]); +export type NoteOrUndefined = t.TypeOf; // NOTE: Experimental list support not being shipped currently and behind a feature flag // TODO: Remove this comment once we lists have passed testing and is ready for the release @@ -185,3 +362,6 @@ export const list_and = t.intersection([ and: t.array(list), }), ]); + +export const listAndOrUndefined = t.union([t.array(list_and), t.undefined]); +export type ListAndOrUndefined = t.TypeOf; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackaged_rules_schema.mock.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackaged_rules_schema.mock.ts new file mode 100644 index 0000000000000..52a210f3a01aa --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackaged_rules_schema.mock.ts @@ -0,0 +1,47 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + AddPrepackagedRulesSchema, + AddPrepackagedRulesSchemaDecoded, +} from './add_prepackaged_rules_schema'; +import { DEFAULT_MAX_SIGNALS } from '../../../constants'; + +export const getAddPrepackagedRulesSchemaMock = (): AddPrepackagedRulesSchema => ({ + description: 'some description', + name: 'Query with a rule id', + query: 'user.name: root or user.name: admin', + severity: 'high', + type: 'query', + risk_score: 55, + language: 'kuery', + rule_id: 'rule-1', + version: 1, +}); + +export const getAddPrepackagedRulesSchemaDecodedMock = (): AddPrepackagedRulesSchemaDecoded => ({ + description: 'some description', + name: 'Query with a rule id', + query: 'user.name: root or user.name: admin', + severity: 'high', + type: 'query', + risk_score: 55, + language: 'kuery', + references: [], + actions: [], + enabled: false, + false_positives: [], + from: 'now-6m', + interval: '5m', + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + to: 'now', + threat: [], + throttle: null, + version: 1, + exceptions_list: [], + rule_id: 'rule-1', +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackaged_rules_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackaged_rules_schema.ts new file mode 100644 index 0000000000000..3e7e7e5409c9c --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackaged_rules_schema.ts @@ -0,0 +1,134 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; + +/* eslint-disable @typescript-eslint/camelcase */ +import { + description, + anomaly_threshold, + filters, + index, + saved_id, + timeline_id, + timeline_title, + meta, + machine_learning_job_id, + risk_score, + MaxSignals, + name, + severity, + Tags, + To, + type, + Threat, + ThrottleOrNull, + note, + References, + Actions, + Enabled, + FalsePositives, + From, + Interval, + language, + query, + rule_id, + version, +} from '../common/schemas'; +/* eslint-enable @typescript-eslint/camelcase */ + +import { DefaultStringArray } from '../types/default_string_array'; +import { DefaultActionsArray } from '../types/default_actions_array'; +import { DefaultBooleanFalse } from '../types/default_boolean_false'; +import { DefaultFromString } from '../types/default_from_string'; +import { DefaultIntervalString } from '../types/default_interval_string'; +import { DefaultMaxSignalsNumber } from '../types/default_max_signals_number'; +import { DefaultToString } from '../types/default_to_string'; +import { DefaultThreatArray } from '../types/default_threat_array'; +import { DefaultThrottleNull } from '../types/default_throttle_null'; +import { ListsDefaultArray, ListsDefaultArraySchema } from '../types/lists_default_array'; + +/** + * Big differences between this schema and the createRulesSchema + * - rule_id is required here + * - output_index is not allowed (and instead the space index must be used) + * - immutable is forbidden but defaults to true instead of to false and it can only ever be true (This is forced directly in the route and not here) + * - enabled defaults to false instead of true + * - version is a required field that must exist + * - index is a required field that must exist if type !== machine_learning (Checked within the runtime type dependent system) + */ +export const addPrepackagedRulesSchema = t.intersection([ + t.exact( + t.type({ + description, + risk_score, + name, + severity, + type, + rule_id, + version, + }) + ), + t.exact( + t.partial({ + actions: DefaultActionsArray, // defaults to empty actions array if not set during decode + anomaly_threshold, // defaults to undefined if not set during decode + enabled: DefaultBooleanFalse, // defaults to false if not set during decode + false_positives: DefaultStringArray, // defaults to empty string array if not set during decode + filters, // defaults to undefined if not set during decode + from: DefaultFromString, // defaults to "now-6m" if not set during decode + index, // defaults to undefined if not set during decode + interval: DefaultIntervalString, // defaults to "5m" if not set during decode + query, // defaults to undefined if not set during decode + language, // defaults to undefined if not set during decode + saved_id, // defaults to "undefined" if not set during decode + timeline_id, // defaults to "undefined" if not set during decode + timeline_title, // defaults to "undefined" if not set during decode + meta, // defaults to "undefined" if not set during decode + machine_learning_job_id, // defaults to "undefined" if not set during decode + max_signals: DefaultMaxSignalsNumber, // defaults to DEFAULT_MAX_SIGNALS (100) if not set during decode + tags: DefaultStringArray, // defaults to empty string array if not set during decode + to: DefaultToString, // defaults to "now" if not set during decode + threat: DefaultThreatArray, // defaults to empty array if not set during decode + throttle: DefaultThrottleNull, // defaults to "null" if not set during decode + references: DefaultStringArray, // defaults to empty array of strings if not set during decode + note, // defaults to "undefined" if not set during decode + exceptions_list: ListsDefaultArray, // defaults to empty array if not set during decode + }) + ), +]); + +export type AddPrepackagedRulesSchema = t.TypeOf; + +// This type is used after a decode since some things are defaults after a decode. +export type AddPrepackagedRulesSchemaDecoded = Omit< + AddPrepackagedRulesSchema, + | 'references' + | 'actions' + | 'enabled' + | 'false_positives' + | 'from' + | 'interval' + | 'max_signals' + | 'tags' + | 'to' + | 'threat' + | 'throttle' + | 'exceptions_list' +> & { + references: References; + actions: Actions; + enabled: Enabled; + false_positives: FalsePositives; + from: From; + interval: Interval; + max_signals: MaxSignals; + tags: Tags; + to: To; + threat: Threat; + throttle: ThrottleOrNull; + exceptions_list: ListsDefaultArraySchema; +}; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackaged_rules_type_dependents.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackaged_rules_type_dependents.test.ts new file mode 100644 index 0000000000000..793d4b04ed0e5 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackaged_rules_type_dependents.test.ts @@ -0,0 +1,71 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { AddPrepackagedRulesSchema } from './add_prepackaged_rules_schema'; +import { addPrepackagedRuleValidateTypeDependents } from './add_prepackaged_rules_type_dependents'; +import { getAddPrepackagedRulesSchemaMock } from './add_prepackaged_rules_schema.mock'; + +describe('create_rules_type_dependents', () => { + test('saved_id is required when type is saved_query and will not validate without out', () => { + const schema: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + type: 'saved_query', + }; + delete schema.saved_id; + const errors = addPrepackagedRuleValidateTypeDependents(schema); + expect(errors).toEqual(['when "type" is "saved_query", "saved_id" is required']); + }); + + test('saved_id is required when type is saved_query and validates with it', () => { + const schema: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + type: 'saved_query', + saved_id: '123', + }; + const errors = addPrepackagedRuleValidateTypeDependents(schema); + expect(errors).toEqual([]); + }); + + test('You cannot omit timeline_title when timeline_id is present', () => { + const schema: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + timeline_id: '123', + }; + delete schema.timeline_title; + const errors = addPrepackagedRuleValidateTypeDependents(schema); + expect(errors).toEqual(['when "timeline_id" exists, "timeline_title" must also exist']); + }); + + test('You cannot have empty string for timeline_title when timeline_id is present', () => { + const schema: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + timeline_id: '123', + timeline_title: '', + }; + const errors = addPrepackagedRuleValidateTypeDependents(schema); + expect(errors).toEqual(['"timeline_title" cannot be an empty string']); + }); + + test('You cannot have timeline_title with an empty timeline_id', () => { + const schema: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + timeline_id: '', + timeline_title: 'some-title', + }; + const errors = addPrepackagedRuleValidateTypeDependents(schema); + expect(errors).toEqual(['"timeline_id" cannot be an empty string']); + }); + + test('You cannot have timeline_title without timeline_id', () => { + const schema: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + timeline_title: 'some-title', + }; + delete schema.timeline_id; + const errors = addPrepackagedRuleValidateTypeDependents(schema); + expect(errors).toEqual(['when "timeline_title" exists, "timeline_id" must also exist']); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackaged_rules_type_dependents.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackaged_rules_type_dependents.ts new file mode 100644 index 0000000000000..2788c331154d2 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackaged_rules_type_dependents.ts @@ -0,0 +1,107 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { AddPrepackagedRulesSchema } from './add_prepackaged_rules_schema'; + +export const validateAnomalyThreshold = (rule: AddPrepackagedRulesSchema): string[] => { + if (rule.type === 'machine_learning') { + if (rule.anomaly_threshold == null) { + return ['when "type" is "machine_learning" anomaly_threshold is required']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateQuery = (rule: AddPrepackagedRulesSchema): string[] => { + if (rule.type === 'machine_learning') { + if (rule.query != null) { + return ['when "type" is "machine_learning", "query" cannot be set']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateLanguage = (rule: AddPrepackagedRulesSchema): string[] => { + if (rule.type === 'machine_learning') { + if (rule.language != null) { + return ['when "type" is "machine_learning", "language" cannot be set']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateSavedId = (rule: AddPrepackagedRulesSchema): string[] => { + if (rule.type === 'saved_query') { + if (rule.saved_id == null) { + return ['when "type" is "saved_query", "saved_id" is required']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateMachineLearningJobId = (rule: AddPrepackagedRulesSchema): string[] => { + if (rule.type === 'machine_learning') { + if (rule.machine_learning_job_id == null) { + return ['when "type" is "machine_learning", "machine_learning_job_id" is required']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateTimelineId = (rule: AddPrepackagedRulesSchema): string[] => { + if (rule.timeline_id != null) { + if (rule.timeline_title == null) { + return ['when "timeline_id" exists, "timeline_title" must also exist']; + } else if (rule.timeline_id === '') { + return ['"timeline_id" cannot be an empty string']; + } else { + return []; + } + } + return []; +}; + +export const validateTimelineTitle = (rule: AddPrepackagedRulesSchema): string[] => { + if (rule.timeline_title != null) { + if (rule.timeline_id == null) { + return ['when "timeline_title" exists, "timeline_id" must also exist']; + } else if (rule.timeline_title === '') { + return ['"timeline_title" cannot be an empty string']; + } else { + return []; + } + } + return []; +}; + +export const addPrepackagedRuleValidateTypeDependents = ( + schema: AddPrepackagedRulesSchema +): string[] => { + return [ + ...validateAnomalyThreshold(schema), + ...validateQuery(schema), + ...validateLanguage(schema), + ...validateSavedId(schema), + ...validateMachineLearningJobId(schema), + ...validateTimelineId(schema), + ...validateTimelineTitle(schema), + ]; +}; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackged_rules_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackged_rules_schema.test.ts new file mode 100644 index 0000000000000..5d170f5a78645 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/add_prepackged_rules_schema.test.ts @@ -0,0 +1,1389 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + addPrepackagedRulesSchema, + AddPrepackagedRulesSchemaDecoded, + AddPrepackagedRulesSchema, +} from './add_prepackaged_rules_schema'; + +import { exactCheck } from '../../../exact_check'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { foldLeftRight, getPaths } from '../../../test_utils'; +import { left } from 'fp-ts/lib/Either'; +import { + getAddPrepackagedRulesSchemaMock, + getAddPrepackagedRulesSchemaDecodedMock, +} from './add_prepackaged_rules_schema.mock'; +import { DEFAULT_MAX_SIGNALS } from '../../../constants'; + +describe('add prepackaged rules schema', () => { + test('empty objects do not validate', () => { + const payload: Partial = {}; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "description"', + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + 'Invalid value "undefined" supplied to "rule_id"', + 'Invalid value "undefined" supplied to "version"', + ]); + expect(message.schema).toEqual({}); + }); + + test('made up values do not validate', () => { + const payload: AddPrepackagedRulesSchema & { madeUp: string } = { + ...getAddPrepackagedRulesSchemaMock(), + madeUp: 'hi', + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "madeUp"']); + expect(message.schema).toEqual({}); + }); + + test('[rule_id] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "description"', + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + 'Invalid value "undefined" supplied to "version"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + 'Invalid value "undefined" supplied to "version"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + 'Invalid value "undefined" supplied to "version"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + 'Invalid value "undefined" supplied to "version"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + 'Invalid value "undefined" supplied to "version"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "type"', + 'Invalid value "undefined" supplied to "version"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity, type] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "version"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity, type, interval] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "version"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity, type, interval, index] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + interval: '5m', + index: ['index-1'], + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "version"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity, type, query, index, interval, version] does validate', () => { + const payload: AddPrepackagedRulesSchema = { + rule_id: 'rule-1', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + query: 'some query', + index: ['index-1'], + interval: '5m', + version: 1, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchemaDecoded = { + rule_id: 'rule-1', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + query: 'some query', + index: ['index-1'], + interval: '5m', + references: [], + actions: [], + enabled: false, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + version: 1, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, query, language] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + risk_score: 50, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "version"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, query, language, version] does validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + risk_score: 50, + version: 1, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchemaDecoded = { + rule_id: 'rule-1', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + references: [], + actions: [], + enabled: false, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + version: 1, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, query, language, risk_score, output_index] does not validate', () => { + const payload: Partial & { output_index: string } = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "version"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, query, language, risk_score, output_index, version] does not validate because output_index is not allowed', () => { + const payload: Partial & { output_index: string } = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + version: 1, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "output_index"']); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, version] does validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + risk_score: 50, + version: 1, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchemaDecoded = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + risk_score: 50, + version: 1, + actions: [], + enabled: false, + exceptions_list: [], + false_positives: [], + max_signals: 100, + references: [], + tags: [], + threat: [], + throttle: null, + }; + expect(message.schema).toEqual(expected); + }); + + test('You can send in an empty array to threat', () => { + const payload: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + threat: [], + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...getAddPrepackagedRulesSchemaDecodedMock(), + threat: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, output_index, threat] does validate', () => { + const payload: AddPrepackagedRulesSchema = { + rule_id: 'rule-1', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + threat: [ + { + framework: 'someFramework', + tactic: { + id: 'fakeId', + name: 'fakeName', + reference: 'fakeRef', + }, + technique: [ + { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + ], + }, + ], + version: 1, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchemaDecoded = { + rule_id: 'rule-1', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + threat: [ + { + framework: 'someFramework', + tactic: { + id: 'fakeId', + name: 'fakeName', + reference: 'fakeRef', + }, + technique: [ + { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + ], + }, + ], + references: [], + actions: [], + enabled: false, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + throttle: null, + version: 1, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('allows references to be sent as valid', () => { + const payload: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + references: ['index-1'], + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...getAddPrepackagedRulesSchemaDecodedMock(), + references: ['index-1'], + }; + expect(message.schema).toEqual(expected); + }); + + test('defaults references to an array if it is not sent in', () => { + const { references, ...noReferences } = getAddPrepackagedRulesSchemaMock(); + const decoded = addPrepackagedRulesSchema.decode(noReferences); + const checked = exactCheck(noReferences, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...getAddPrepackagedRulesSchemaDecodedMock(), + references: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('immutable cannot be set in a pre-packaged rule', () => { + const payload: AddPrepackagedRulesSchema & { immutable: boolean } = { + ...getAddPrepackagedRulesSchemaMock(), + immutable: true, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "immutable"']); + expect(message.schema).toEqual({}); + }); + + test('defaults enabled to false', () => { + const payload: AddPrepackagedRulesSchema = getAddPrepackagedRulesSchemaMock(); + delete payload.enabled; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(((message.schema as unknown) as AddPrepackagedRulesSchemaDecoded).enabled).toEqual( + false + ); + }); + + test('rule_id is required', () => { + const payload: AddPrepackagedRulesSchema = getAddPrepackagedRulesSchemaMock(); + delete payload.rule_id; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "rule_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('references cannot be numbers', () => { + const payload: Omit & { references: number[] } = { + ...getAddPrepackagedRulesSchemaMock(), + references: [5], + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('indexes cannot be numbers', () => { + const payload: Omit & { index: number[] } = { + ...getAddPrepackagedRulesSchemaMock(), + index: [5], + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to "index"']); + expect(message.schema).toEqual({}); + }); + + test('defaults interval to 5 min', () => { + const { interval, ...noInterval } = getAddPrepackagedRulesSchemaMock(); + const payload: AddPrepackagedRulesSchema = { + ...noInterval, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { + interval: expectedInterval, + ...expectedNoInterval + } = getAddPrepackagedRulesSchemaDecodedMock(); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...expectedNoInterval, + interval: '5m', + }; + expect(message.schema).toEqual(expected); + }); + + test('defaults max signals to 100', () => { + const { max_signals, ...noMaxSignals } = getAddPrepackagedRulesSchemaMock(); + const payload: AddPrepackagedRulesSchema = { + ...noMaxSignals, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { + max_signals: expectedMaxSignals, + ...expectedNoMaxSignals + } = getAddPrepackagedRulesSchemaDecodedMock(); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...expectedNoMaxSignals, + max_signals: 100, + }; + expect(message.schema).toEqual(expected); + }); + + test('saved_query type can have filters with it', () => { + const payload: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + filters: [], + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...getAddPrepackagedRulesSchemaDecodedMock(), + filters: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('filters cannot be a string', () => { + const payload: Omit & { filters: string } = { + ...getAddPrepackagedRulesSchemaMock(), + filters: 'some string', + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "some string" supplied to "filters"', + ]); + expect(message.schema).toEqual({}); + }); + + test('language validates with kuery', () => { + const payload: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + language: 'kuery', + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...getAddPrepackagedRulesSchemaDecodedMock(), + language: 'kuery', + }; + expect(message.schema).toEqual(expected); + }); + + test('language validates with lucene', () => { + const payload: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + language: 'lucene', + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...getAddPrepackagedRulesSchemaDecodedMock(), + language: 'lucene', + }; + expect(message.schema).toEqual(expected); + }); + + test('language does not validate with something made up', () => { + const payload: Omit & { language: string } = { + ...getAddPrepackagedRulesSchemaMock(), + language: 'something-made-up', + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "something-made-up" supplied to "language"', + ]); + expect(message.schema).toEqual({}); + }); + + test('max_signals cannot be negative', () => { + const payload: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + max_signals: -1, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "-1" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('max_signals cannot be zero', () => { + const payload: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + max_signals: 0, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "0" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('max_signals can be 1', () => { + const payload: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + max_signals: 1, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...getAddPrepackagedRulesSchemaDecodedMock(), + max_signals: 1, + }; + expect(message.schema).toEqual(expected); + }); + + test('You can optionally send in an array of tags', () => { + const payload: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + tags: ['tag_1', 'tag_2'], + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...getAddPrepackagedRulesSchemaDecodedMock(), + tags: ['tag_1', 'tag_2'], + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot send in an array of tags that are numbers', () => { + const payload: Omit & { tags: number[] } = { + ...getAddPrepackagedRulesSchemaMock(), + tags: [0, 1, 2], + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "0" supplied to ""', + 'Invalid value "1" supplied to ""', + 'Invalid value "2" supplied to ""', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of threat that are missing "framework"', () => { + const payload: Omit & { + threat: Array>>; + } = { + ...getAddPrepackagedRulesSchemaMock(), + threat: [ + { + tactic: { + id: 'fakeId', + name: 'fakeName', + reference: 'fakeRef', + }, + technique: [ + { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + ], + }, + ], + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "framework"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of threat that are missing "tactic"', () => { + const payload: Omit & { + threat: Array>>; + } = { + ...getAddPrepackagedRulesSchemaMock(), + threat: [ + { + framework: 'fake', + technique: [ + { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + ], + }, + ], + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "tactic"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of threat that are missing "technique"', () => { + const payload: Omit & { + threat: Array>>; + } = { + ...getAddPrepackagedRulesSchemaMock(), + threat: [ + { + framework: 'fake', + tactic: { + id: 'fakeId', + name: 'fakeName', + reference: 'fakeRef', + }, + }, + ], + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "technique"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You can optionally send in an array of false positives', () => { + const payload: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + false_positives: ['false_1', 'false_2'], + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...getAddPrepackagedRulesSchemaDecodedMock(), + false_positives: ['false_1', 'false_2'], + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot send in an array of false positives that are numbers', () => { + const payload: Omit & { + false_positives: number[]; + } = { + ...getAddPrepackagedRulesSchemaMock(), + false_positives: [5, 4], + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "5" supplied to ""', + 'Invalid value "4" supplied to ""', + ]); + expect(message.schema).toEqual({}); + }); + test('You cannot set the risk_score to 101', () => { + const payload: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + risk_score: 101, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "101" supplied to "risk_score"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot set the risk_score to -1', () => { + const payload: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + risk_score: -1, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "-1" supplied to "risk_score"']); + expect(message.schema).toEqual({}); + }); + + test('You can set the risk_score to 0', () => { + const payload: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + risk_score: 0, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...getAddPrepackagedRulesSchemaDecodedMock(), + risk_score: 0, + }; + expect(message.schema).toEqual(expected); + }); + + test('You can set the risk_score to 100', () => { + const payload: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + risk_score: 100, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...getAddPrepackagedRulesSchemaDecodedMock(), + risk_score: 100, + }; + expect(message.schema).toEqual(expected); + }); + + test('You can set meta to any object you want', () => { + const payload: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + meta: { + somethingMadeUp: { somethingElse: true }, + }, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...getAddPrepackagedRulesSchemaDecodedMock(), + meta: { + somethingMadeUp: { somethingElse: true }, + }, + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot create meta as a string', () => { + const payload: Omit & { meta: string } = { + ...getAddPrepackagedRulesSchemaMock(), + meta: 'should not work', + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "should not work" supplied to "meta"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You can omit the query string when filters are present', () => { + const { query, ...noQuery } = getAddPrepackagedRulesSchemaMock(); + const payload: AddPrepackagedRulesSchema = { + ...noQuery, + filters: [], + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { query: expectedQuery, ...expectedNoQuery } = getAddPrepackagedRulesSchemaDecodedMock(); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...expectedNoQuery, + filters: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('validates with timeline_id and timeline_title', () => { + const payload: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + timeline_id: 'timeline-id', + timeline_title: 'timeline-title', + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...getAddPrepackagedRulesSchemaDecodedMock(), + timeline_id: 'timeline-id', + timeline_title: 'timeline-title', + }; + expect(message.schema).toEqual(expected); + }); + + test('The default for "from" will be "now-6m"', () => { + const { from, ...noFrom } = getAddPrepackagedRulesSchemaMock(); + const payload: AddPrepackagedRulesSchema = { + ...noFrom, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { from: expectedFrom, ...expectedNoFrom } = getAddPrepackagedRulesSchemaDecodedMock(); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...expectedNoFrom, + from: 'now-6m', + }; + expect(message.schema).toEqual(expected); + }); + + test('The default for "to" will be "now"', () => { + const { to, ...noTo } = getAddPrepackagedRulesSchemaMock(); + const payload: AddPrepackagedRulesSchema = { + ...noTo, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { to: expectedTo, ...expectedNoTo } = getAddPrepackagedRulesSchemaDecodedMock(); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...expectedNoTo, + to: 'now', + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot set the severity to a value other than low, medium, high, or critical', () => { + const payload: Omit & { severity: string } = { + ...getAddPrepackagedRulesSchemaMock(), + severity: 'junk', + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "junk" supplied to "severity"']); + expect(message.schema).toEqual({}); + }); + + test('The default for "actions" will be an empty array', () => { + const { actions, ...noActions } = getAddPrepackagedRulesSchemaMock(); + const payload: AddPrepackagedRulesSchema = { + ...noActions, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { + actions: expectedActions, + ...expectedNoActions + } = getAddPrepackagedRulesSchemaDecodedMock(); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...expectedNoActions, + actions: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot send in an array of actions that are missing "group"', () => { + const payload: Omit = { + ...getAddPrepackagedRulesSchemaMock(), + actions: [{ id: 'id', action_type_id: 'action_type_id', params: {} }], + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "group"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are missing "id"', () => { + const payload: Omit = { + ...getAddPrepackagedRulesSchemaMock(), + actions: [{ group: 'group', action_type_id: 'action_type_id', params: {} }], + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are missing "action_type_id"', () => { + const payload: Omit = { + ...getAddPrepackagedRulesSchemaMock(), + actions: [{ group: 'group', id: 'id', params: {} }], + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "action_type_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are missing "params"', () => { + const payload: Omit = { + ...getAddPrepackagedRulesSchemaMock(), + actions: [{ group: 'group', id: 'id', action_type_id: 'action_type_id' }], + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "params"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are including "actionTypeId"', () => { + const payload: Omit = { + ...getAddPrepackagedRulesSchemaMock(), + actions: [ + { + group: 'group', + id: 'id', + actionTypeId: 'actionTypeId', + params: {}, + }, + ], + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "action_type_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('The default for "throttle" will be null', () => { + const { throttle, ...noThrottle } = getAddPrepackagedRulesSchemaMock(); + const payload: AddPrepackagedRulesSchema = { + ...noThrottle, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { + throttle: expectedThrottle, + ...expectedNoThrottle + } = getAddPrepackagedRulesSchemaDecodedMock(); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...expectedNoThrottle, + throttle: null, + }; + expect(message.schema).toEqual(expected); + }); + + describe('note', () => { + test('You can set note to a string', () => { + const payload: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + note: '# documentation markdown here', + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchemaDecoded = { + ...getAddPrepackagedRulesSchemaDecodedMock(), + note: '# documentation markdown here', + }; + expect(message.schema).toEqual(expected); + }); + + test('You can set note to an empty string', () => { + const payload: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaMock(), + note: '', + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchema = { + ...getAddPrepackagedRulesSchemaDecodedMock(), + note: '', + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot create note as an object', () => { + const payload: Omit & { note: {} } = { + ...getAddPrepackagedRulesSchemaMock(), + note: { + somethingHere: 'something else', + }, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + // TODO: Fix/Change the formatErrors to be better able to handle objects + 'Invalid value "[object Object]" supplied to "note"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note] does validate', () => { + const payload: AddPrepackagedRulesSchema = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + risk_score: 50, + note: '# some markdown', + version: 1, + }; + + const decoded = addPrepackagedRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: AddPrepackagedRulesSchemaDecoded = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + risk_score: 50, + note: '# some markdown', + references: [], + actions: [], + enabled: false, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + version: 1, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + }); + + // TODO: The exception_list tests are skipped and empty until we re-integrate it from the lists plugin + describe.skip('exception_list', () => { + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and exceptions_list] does validate', () => {}); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and empty exceptions_list] does validate', () => {}); + + test('rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and invalid exceptions_list] does NOT validate', () => {}); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and non-existent exceptions_list] does validate with empty exceptions_list', () => {}); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_bulk_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_bulk_schema.test.ts new file mode 100644 index 0000000000000..e79dde41752a3 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_bulk_schema.test.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + createRulesBulkSchema, + CreateRulesBulkSchema, + CreateRulesBulkSchemaDecoded, +} from './create_rules_bulk_schema'; +import { exactCheck } from '../../../exact_check'; +import { foldLeftRight } from '../../../test_utils'; +import { + getCreateRulesSchemaMock, + getCreateRulesSchemaDecodedMock, +} from './create_rules_schema.mock'; +import { formatErrors } from '../../../format_errors'; +import { CreateRulesSchema } from './create_rules_schema'; + +// only the basics of testing are here. +// see: create_rules_schema.test.ts for the bulk of the validation tests +// this just wraps createRulesSchema in an array +describe('create_rules_bulk_schema', () => { + test('can take an empty array and validate it', () => { + const payload: CreateRulesBulkSchema = []; + + const decoded = createRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(output.errors).toEqual([]); + expect(output.schema).toEqual([]); + }); + + test('made up values do not validate for a single element', () => { + const payload: Array<{ madeUp: string }> = [{ madeUp: 'hi' }]; + + const decoded = createRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([ + 'Invalid value "undefined" supplied to "description"', + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(output.schema).toEqual({}); + }); + + test('single array element does validate', () => { + const payload: CreateRulesBulkSchema = [getCreateRulesSchemaMock()]; + + const decoded = createRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect(output.schema).toEqual([getCreateRulesSchemaDecodedMock()]); + }); + + test('two array elements do validate', () => { + const payload: CreateRulesBulkSchema = [getCreateRulesSchemaMock(), getCreateRulesSchemaMock()]; + + const decoded = createRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect(output.schema).toEqual([ + getCreateRulesSchemaDecodedMock(), + getCreateRulesSchemaDecodedMock(), + ]); + }); + + test('single array element with a missing value (risk_score) will not validate', () => { + const singleItem = getCreateRulesSchemaMock(); + delete singleItem.risk_score; + const payload: CreateRulesBulkSchema = [singleItem]; + + const decoded = createRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(output.schema).toEqual({}); + }); + + test('two array elements where the first is valid but the second is invalid (risk_score) will not validate', () => { + const singleItem = getCreateRulesSchemaMock(); + const secondItem = getCreateRulesSchemaMock(); + delete secondItem.risk_score; + const payload: CreateRulesBulkSchema = [singleItem, secondItem]; + + const decoded = createRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(output.schema).toEqual({}); + }); + + test('two array elements where the first is invalid (risk_score) but the second is valid will not validate', () => { + const singleItem = getCreateRulesSchemaMock(); + const secondItem = getCreateRulesSchemaMock(); + delete singleItem.risk_score; + const payload: CreateRulesBulkSchema = [singleItem, secondItem]; + + const decoded = createRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(output.schema).toEqual({}); + }); + + test('two array elements where both are invalid (risk_score) will not validate', () => { + const singleItem = getCreateRulesSchemaMock(); + const secondItem = getCreateRulesSchemaMock(); + delete singleItem.risk_score; + delete secondItem.risk_score; + const payload: CreateRulesBulkSchema = [singleItem, secondItem]; + + const decoded = createRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(output.schema).toEqual({}); + }); + + test('two array elements where the first is invalid (extra key and value) but the second is valid will not validate', () => { + const singleItem: CreateRulesSchema & { madeUpValue: string } = { + ...getCreateRulesSchemaMock(), + madeUpValue: 'something', + }; + const secondItem = getCreateRulesSchemaMock(); + const payload: CreateRulesBulkSchema = [singleItem, secondItem]; + + const decoded = createRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual(['invalid keys "madeUpValue"']); + expect(output.schema).toEqual({}); + }); + + test('two array elements where the second is invalid (extra key and value) but the first is valid will not validate', () => { + const singleItem: CreateRulesSchema = getCreateRulesSchemaMock(); + const secondItem: CreateRulesSchema & { madeUpValue: string } = { + ...getCreateRulesSchemaMock(), + madeUpValue: 'something', + }; + const payload: CreateRulesBulkSchema = [singleItem, secondItem]; + + const decoded = createRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual(['invalid keys "madeUpValue"']); + expect(output.schema).toEqual({}); + }); + + test('two array elements where both are invalid (extra key and value) will not validate', () => { + const singleItem: CreateRulesSchema & { madeUpValue: string } = { + ...getCreateRulesSchemaMock(), + madeUpValue: 'something', + }; + const secondItem: CreateRulesSchema & { madeUpValue: string } = { + ...getCreateRulesSchemaMock(), + madeUpValue: 'something', + }; + const payload: CreateRulesBulkSchema = [singleItem, secondItem]; + + const decoded = createRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual(['invalid keys "madeUpValue,madeUpValue"']); + expect(output.schema).toEqual({}); + }); + + test('The default for "from" will be "now-6m"', () => { + const { from, ...withoutFrom } = getCreateRulesSchemaMock(); + const payload: CreateRulesBulkSchema = [withoutFrom]; + + const decoded = createRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect((output.schema as CreateRulesBulkSchemaDecoded)[0].from).toEqual('now-6m'); + }); + + test('The default for "to" will be "now"', () => { + const { to, ...withoutTo } = getCreateRulesSchemaMock(); + const payload: CreateRulesBulkSchema = [withoutTo]; + + const decoded = createRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect((output.schema as CreateRulesBulkSchemaDecoded)[0].to).toEqual('now'); + }); + + test('You cannot set the severity to a value other than low, medium, high, or critical', () => { + const badSeverity = { ...getCreateRulesSchemaMock(), severity: 'madeup' }; + const payload = [badSeverity]; + + const decoded = createRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual(['Invalid value "madeup" supplied to "severity"']); + expect(output.schema).toEqual({}); + }); + + test('You can set "note" to a string', () => { + const payload: CreateRulesBulkSchema = [ + { ...getCreateRulesSchemaMock(), note: '# test markdown' }, + ]; + + const decoded = createRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect(output.schema).toEqual([ + { ...getCreateRulesSchemaDecodedMock(), note: '# test markdown' }, + ]); + }); + + test('You can set "note" to an empty string', () => { + const payload: CreateRulesBulkSchema = [{ ...getCreateRulesSchemaMock(), note: '' }]; + + const decoded = createRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect(output.schema).toEqual([{ ...getCreateRulesSchemaDecodedMock(), note: '' }]); + }); + + test('You can set "note" to anything other than string', () => { + const payload = [ + { + ...getCreateRulesSchemaMock(), + note: { + something: 'some object', + }, + }, + ]; + + const decoded = createRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + // TODO: We should change the formatter used to better print objects + expect(formatErrors(output.errors)).toEqual([ + 'Invalid value "[object Object]" supplied to "note"', + ]); + expect(output.schema).toEqual({}); + }); + + test('The default for "actions" will be an empty array', () => { + const { actions, ...withoutActions } = getCreateRulesSchemaMock(); + const payload: CreateRulesBulkSchema = [withoutActions]; + + const decoded = createRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect((output.schema as CreateRulesBulkSchemaDecoded)[0].actions).toEqual([]); + }); + + test('The default for "throttle" will be null', () => { + const { throttle, ...withoutThrottle } = getCreateRulesSchemaMock(); + const payload: CreateRulesBulkSchema = [withoutThrottle]; + + const decoded = createRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect((output.schema as CreateRulesBulkSchemaDecoded)[0].throttle).toEqual(null); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_bulk_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_bulk_schema.ts new file mode 100644 index 0000000000000..c6233cc63fa9f --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_bulk_schema.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; + +import { createRulesSchema, CreateRulesSchemaDecoded } from './create_rules_schema'; + +export const createRulesBulkSchema = t.array(createRulesSchema); +export type CreateRulesBulkSchema = t.TypeOf; + +export type CreateRulesBulkSchemaDecoded = CreateRulesSchemaDecoded[]; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_schema.mock.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_schema.mock.ts new file mode 100644 index 0000000000000..a9ab6f8959e24 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_schema.mock.ts @@ -0,0 +1,43 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { CreateRulesSchema, CreateRulesSchemaDecoded } from './create_rules_schema'; +import { DEFAULT_MAX_SIGNALS } from '../../../constants'; + +export const getCreateRulesSchemaMock = (): CreateRulesSchema => ({ + description: 'some description', + name: 'Query with a rule id', + query: 'user.name: root or user.name: admin', + severity: 'high', + type: 'query', + risk_score: 55, + language: 'kuery', + rule_id: 'rule-1', +}); + +export const getCreateRulesSchemaDecodedMock = (): CreateRulesSchemaDecoded => ({ + description: 'some description', + name: 'Query with a rule id', + query: 'user.name: root or user.name: admin', + severity: 'high', + type: 'query', + risk_score: 55, + language: 'kuery', + references: [], + actions: [], + enabled: true, + false_positives: [], + from: 'now-6m', + interval: '5m', + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + to: 'now', + threat: [], + throttle: null, + version: 1, + exceptions_list: [], + rule_id: 'rule-1', +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_schema.test.ts new file mode 100644 index 0000000000000..d672d38028902 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_schema.test.ts @@ -0,0 +1,1445 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + createRulesSchema, + CreateRulesSchema, + CreateRulesSchemaDecoded, +} from './create_rules_schema'; +import { exactCheck } from '../../../exact_check'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { foldLeftRight, getPaths } from '../../../test_utils'; +import { left } from 'fp-ts/lib/Either'; +import { + getCreateRulesSchemaMock, + getCreateRulesSchemaDecodedMock, +} from './create_rules_schema.mock'; +import { DEFAULT_MAX_SIGNALS } from '../../../constants'; + +describe('create rules schema', () => { + test('empty objects do not validate', () => { + const payload: Partial = {}; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "description"', + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('made up values do not validate', () => { + const payload: CreateRulesSchema & { madeUp: string } = { + ...getCreateRulesSchemaMock(), + madeUp: 'hi', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "madeUp"']); + expect(message.schema).toEqual({}); + }); + + test('[rule_id] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "description"', + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity, type] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity, type, interval] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity, type, interval, index] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + interval: '5m', + index: ['index-1'], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity, type, query, index, interval] does validate', () => { + const payload: CreateRulesSchema = { + rule_id: 'rule-1', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + query: 'some query', + index: ['index-1'], + interval: '5m', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + rule_id: 'rule-1', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + query: 'some query', + index: ['index-1'], + interval: '5m', + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + version: 1, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, query, language] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, query, language, risk_score] does validate', () => { + const payload: CreateRulesSchema = { + rule_id: 'rule-1', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + rule_id: 'rule-1', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + version: 1, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, query, language, risk_score, output_index] does validate', () => { + const payload: CreateRulesSchema = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + version: 1, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score] does validate', () => { + const payload: CreateRulesSchema = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + risk_score: 50, + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + risk_score: 50, + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + version: 1, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, output_index] does validate', () => { + const payload: CreateRulesSchema = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + version: 1, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('You can send in an empty array to threat', () => { + const payload: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + threat: [], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + ...getCreateRulesSchemaDecodedMock(), + threat: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, output_index, threat] does validate', () => { + const payload: CreateRulesSchema = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + threat: [ + { + framework: 'someFramework', + tactic: { + id: 'fakeId', + name: 'fakeName', + reference: 'fakeRef', + }, + technique: [ + { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + ], + }, + ], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + threat: [ + { + framework: 'someFramework', + tactic: { + id: 'fakeId', + name: 'fakeName', + reference: 'fakeRef', + }, + technique: [ + { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + ], + }, + ], + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + throttle: null, + version: 1, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('allows references to be sent as valid', () => { + const payload: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + references: ['index-1'], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + ...getCreateRulesSchemaDecodedMock(), + references: ['index-1'], + }; + expect(message.schema).toEqual(expected); + }); + + test('defaults references to an array if it is not sent in', () => { + const { references, ...noReferences } = getCreateRulesSchemaMock(); + const decoded = createRulesSchema.decode(noReferences); + const checked = exactCheck(noReferences, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + ...getCreateRulesSchemaDecodedMock(), + references: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('references cannot be numbers', () => { + const payload: Omit & { references: number[] } = { + ...getCreateRulesSchemaMock(), + references: [5], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('indexes cannot be numbers', () => { + const payload: Omit & { index: number[] } = { + ...getCreateRulesSchemaMock(), + index: [5], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to "index"']); + expect(message.schema).toEqual({}); + }); + + test('saved_query type can have filters with it', () => { + const payload: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + filters: [], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + ...getCreateRulesSchemaDecodedMock(), + filters: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('filters cannot be a string', () => { + const payload: Omit & { filters: string } = { + ...getCreateRulesSchemaMock(), + filters: 'some string', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "some string" supplied to "filters"', + ]); + expect(message.schema).toEqual({}); + }); + + test('language validates with kuery', () => { + const payload: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + language: 'kuery', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + ...getCreateRulesSchemaDecodedMock(), + language: 'kuery', + }; + expect(message.schema).toEqual(expected); + }); + + test('language validates with lucene', () => { + const payload: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + language: 'lucene', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + ...getCreateRulesSchemaDecodedMock(), + language: 'lucene', + }; + expect(message.schema).toEqual(expected); + }); + + test('language does not validate with something made up', () => { + const payload: Omit & { language: string } = { + ...getCreateRulesSchemaMock(), + language: 'something-made-up', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "something-made-up" supplied to "language"', + ]); + expect(message.schema).toEqual({}); + }); + + test('max_signals cannot be negative', () => { + const payload: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + max_signals: -1, + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "-1" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('max_signals cannot be zero', () => { + const payload: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + max_signals: 0, + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "0" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('max_signals can be 1', () => { + const payload: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + max_signals: 1, + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + ...getCreateRulesSchemaDecodedMock(), + max_signals: 1, + }; + expect(message.schema).toEqual(expected); + }); + + test('You can optionally send in an array of tags', () => { + const payload: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + tags: ['tag_1', 'tag_2'], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + ...getCreateRulesSchemaDecodedMock(), + tags: ['tag_1', 'tag_2'], + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot send in an array of tags that are numbers', () => { + const payload: Omit & { tags: number[] } = { + ...getCreateRulesSchemaMock(), + tags: [0, 1, 2], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "0" supplied to ""', + 'Invalid value "1" supplied to ""', + 'Invalid value "2" supplied to ""', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of threat that are missing "framework"', () => { + const payload: Omit & { + threat: Array>>; + } = { + ...getCreateRulesSchemaMock(), + threat: [ + { + tactic: { + id: 'fakeId', + name: 'fakeName', + reference: 'fakeRef', + }, + technique: [ + { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + ], + }, + ], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "framework"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of threat that are missing "tactic"', () => { + const payload: Omit & { + threat: Array>>; + } = { + ...getCreateRulesSchemaMock(), + threat: [ + { + framework: 'fake', + technique: [ + { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + ], + }, + ], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "tactic"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of threat that are missing "technique"', () => { + const payload: Omit & { + threat: Array>>; + } = { + ...getCreateRulesSchemaMock(), + threat: [ + { + framework: 'fake', + tactic: { + id: 'fakeId', + name: 'fakeName', + reference: 'fakeRef', + }, + }, + ], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "technique"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You can optionally send in an array of false positives', () => { + const payload: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + false_positives: ['false_1', 'false_2'], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + ...getCreateRulesSchemaDecodedMock(), + false_positives: ['false_1', 'false_2'], + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot send in an array of false positives that are numbers', () => { + const payload: Omit & { false_positives: number[] } = { + ...getCreateRulesSchemaMock(), + false_positives: [5, 4], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "5" supplied to ""', + 'Invalid value "4" supplied to ""', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot set the immutable to a number when trying to create a rule', () => { + const payload: Omit & { immutable: number } = { + ...getCreateRulesSchemaMock(), + immutable: 5, + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "immutable"']); + expect(message.schema).toEqual({}); + }); + + test('You cannot set the risk_score to 101', () => { + const payload: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + risk_score: 101, + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "101" supplied to "risk_score"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot set the risk_score to -1', () => { + const payload: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + risk_score: -1, + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "-1" supplied to "risk_score"']); + expect(message.schema).toEqual({}); + }); + + test('You can set the risk_score to 0', () => { + const payload: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + risk_score: 0, + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + ...getCreateRulesSchemaDecodedMock(), + risk_score: 0, + }; + expect(message.schema).toEqual(expected); + }); + + test('You can set the risk_score to 100', () => { + const payload: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + risk_score: 100, + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + ...getCreateRulesSchemaDecodedMock(), + risk_score: 100, + }; + expect(message.schema).toEqual(expected); + }); + + test('You can set meta to any object you want', () => { + const payload: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + meta: { + somethingMadeUp: { somethingElse: true }, + }, + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + ...getCreateRulesSchemaDecodedMock(), + meta: { + somethingMadeUp: { somethingElse: true }, + }, + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot create meta as a string', () => { + const payload: Omit & { meta: string } = { + ...getCreateRulesSchemaMock(), + meta: 'should not work', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "should not work" supplied to "meta"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You can omit the query string when filters are present', () => { + const { query, ...noQuery } = getCreateRulesSchemaMock(); + const payload: CreateRulesSchema = { + ...noQuery, + filters: [], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { query: expectedQuery, ...expectedNoQuery } = getCreateRulesSchemaDecodedMock(); + const expected: CreateRulesSchemaDecoded = { + ...expectedNoQuery, + filters: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('validates with timeline_id and timeline_title', () => { + const payload: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + timeline_id: 'timeline-id', + timeline_title: 'timeline-title', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + ...getCreateRulesSchemaDecodedMock(), + timeline_id: 'timeline-id', + timeline_title: 'timeline-title', + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot set the severity to a value other than low, medium, high, or critical', () => { + const payload: Omit & { severity: string } = { + ...getCreateRulesSchemaMock(), + severity: 'junk', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "junk" supplied to "severity"']); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are missing "group"', () => { + const payload: Omit = { + ...getCreateRulesSchemaMock(), + actions: [{ id: 'id', action_type_id: 'action_type_id', params: {} }], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "group"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are missing "id"', () => { + const payload: Omit = { + ...getCreateRulesSchemaMock(), + actions: [{ group: 'group', action_type_id: 'action_type_id', params: {} }], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are missing "action_type_id"', () => { + const payload: Omit = { + ...getCreateRulesSchemaMock(), + actions: [{ group: 'group', id: 'id', params: {} }], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "action_type_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are missing "params"', () => { + const payload: Omit = { + ...getCreateRulesSchemaMock(), + actions: [{ group: 'group', id: 'id', action_type_id: 'action_type_id' }], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "params"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are including "actionTypeId"', () => { + const payload: Omit = { + ...getCreateRulesSchemaMock(), + actions: [ + { + group: 'group', + id: 'id', + actionTypeId: 'actionTypeId', + params: {}, + }, + ], + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "action_type_id"', + ]); + expect(message.schema).toEqual({}); + }); + + describe('note', () => { + test('You can set note to a string', () => { + const payload: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + note: '# documentation markdown here', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + ...getCreateRulesSchemaDecodedMock(), + note: '# documentation markdown here', + }; + expect(message.schema).toEqual(expected); + }); + + test('You can set note to an empty string', () => { + const payload: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + note: '', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + ...getCreateRulesSchemaDecodedMock(), + note: '', + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot create note as an object', () => { + const payload: Omit & { note: {} } = { + ...getCreateRulesSchemaMock(), + note: { + somethingHere: 'something else', + }, + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + // TODO: Fix/Change the formatErrors to be better able to handle objects + 'Invalid value "[object Object]" supplied to "note"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note] does validate', () => { + const payload: CreateRulesSchema = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + risk_score: 50, + note: '# some markdown', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + risk_score: 50, + note: '# some markdown', + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + version: 1, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + }); + + test('defaults interval to 5 min', () => { + const { interval, ...noInterval } = getCreateRulesSchemaMock(); + const payload: CreateRulesSchema = { + ...noInterval, + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { interval: expectedInterval, ...expectedNoInterval } = getCreateRulesSchemaDecodedMock(); + const expected: CreateRulesSchemaDecoded = { + ...expectedNoInterval, + interval: '5m', + }; + expect(message.schema).toEqual(expected); + }); + + test('defaults max signals to 100', () => { + const { max_signals, ...noMaxSignals } = getCreateRulesSchemaMock(); + const payload: CreateRulesSchema = { + ...noMaxSignals, + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { + max_signals: expectedMaxSignals, + ...expectedNoMaxSignals + } = getCreateRulesSchemaDecodedMock(); + const expected: CreateRulesSchemaDecoded = { + ...expectedNoMaxSignals, + max_signals: 100, + }; + expect(message.schema).toEqual(expected); + }); + + test('The default for "from" will be "now-6m"', () => { + const { from, ...noFrom } = getCreateRulesSchemaMock(); + const payload: CreateRulesSchema = { + ...noFrom, + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { from: expectedFrom, ...expectedNoFrom } = getCreateRulesSchemaDecodedMock(); + const expected: CreateRulesSchemaDecoded = { + ...expectedNoFrom, + from: 'now-6m', + }; + expect(message.schema).toEqual(expected); + }); + + test('The default for "to" will be "now"', () => { + const { to, ...noTo } = getCreateRulesSchemaMock(); + const payload: CreateRulesSchema = { + ...noTo, + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { to: expectedTo, ...expectedNoTo } = getCreateRulesSchemaDecodedMock(); + const expected: CreateRulesSchemaDecoded = { + ...expectedNoTo, + to: 'now', + }; + expect(message.schema).toEqual(expected); + }); + + test('The default for "actions" will be an empty array', () => { + const { actions, ...noActions } = getCreateRulesSchemaMock(); + const payload: CreateRulesSchema = { + ...noActions, + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { actions: expectedActions, ...expectedNoActions } = getCreateRulesSchemaDecodedMock(); + const expected: CreateRulesSchemaDecoded = { + ...expectedNoActions, + actions: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('The default for "throttle" will be null', () => { + const { throttle, ...noThrottle } = getCreateRulesSchemaMock(); + const payload: CreateRulesSchema = { + ...noThrottle, + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { throttle: expectedThrottle, ...expectedNoThrottle } = getCreateRulesSchemaDecodedMock(); + const expected: CreateRulesSchemaDecoded = { + ...expectedNoThrottle, + throttle: null, + }; + expect(message.schema).toEqual(expected); + }); + + test('machine_learning type does validate', () => { + const payload: CreateRulesSchema = { + type: 'machine_learning', + anomaly_threshold: 50, + machine_learning_job_id: 'linux_anomalous_network_activity_ecs', + false_positives: [], + references: [], + risk_score: 50, + threat: [], + name: 'ss', + description: 'ss', + severity: 'low', + tags: [], + interval: '5m', + from: 'now-360s', + to: 'now', + meta: { from: '1m' }, + actions: [], + enabled: true, + throttle: 'no_actions', + rule_id: 'rule-1', + }; + + const decoded = createRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: CreateRulesSchemaDecoded = { + type: 'machine_learning', + anomaly_threshold: 50, + machine_learning_job_id: 'linux_anomalous_network_activity_ecs', + false_positives: [], + references: [], + risk_score: 50, + threat: [], + name: 'ss', + description: 'ss', + severity: 'low', + tags: [], + interval: '5m', + from: 'now-360s', + to: 'now', + meta: { from: '1m' }, + actions: [], + enabled: true, + throttle: 'no_actions', + exceptions_list: [], + max_signals: DEFAULT_MAX_SIGNALS, + version: 1, + rule_id: 'rule-1', + }; + expect(message.schema).toEqual(expected); + }); + + test('it generates a uuid v4 whenever you omit the rule_id', () => { + const { rule_id, ...noRuleId } = getCreateRulesSchemaMock(); + const decoded = createRulesSchema.decode(noRuleId); + const checked = exactCheck(noRuleId, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as CreateRulesSchemaDecoded).rule_id).toMatch( + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i + ); + }); + + // TODO: The exception_list tests are skipped and empty until we re-integrate it from the lists plugin + describe.skip('exception_list', () => { + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and exceptions_list] does validate', () => {}); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and empty exceptions_list] does validate', () => {}); + + test('rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and invalid exceptions_list] does NOT validate', () => {}); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and non-existent exceptions_list] does validate with empty exceptions_list', () => {}); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_schema.ts new file mode 100644 index 0000000000000..4e60201b8030e --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_schema.ts @@ -0,0 +1,134 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; + +/* eslint-disable @typescript-eslint/camelcase */ +import { + description, + anomaly_threshold, + filters, + RuleId, + index, + output_index, + saved_id, + timeline_id, + timeline_title, + meta, + machine_learning_job_id, + risk_score, + MaxSignals, + name, + severity, + Tags, + To, + type, + Threat, + ThrottleOrNull, + note, + Version, + References, + Actions, + Enabled, + FalsePositives, + From, + Interval, + language, + query, +} from '../common/schemas'; +/* eslint-enable @typescript-eslint/camelcase */ + +import { DefaultStringArray } from '../types/default_string_array'; +import { DefaultActionsArray } from '../types/default_actions_array'; +import { DefaultBooleanTrue } from '../types/default_boolean_true'; +import { DefaultFromString } from '../types/default_from_string'; +import { DefaultIntervalString } from '../types/default_interval_string'; +import { DefaultMaxSignalsNumber } from '../types/default_max_signals_number'; +import { DefaultToString } from '../types/default_to_string'; +import { DefaultThreatArray } from '../types/default_threat_array'; +import { DefaultThrottleNull } from '../types/default_throttle_null'; +import { DefaultVersionNumber } from '../types/default_version_number'; +import { ListsDefaultArray, ListsDefaultArraySchema } from '../types/lists_default_array'; +import { DefaultUuid } from '../types/default_uuid'; + +export const createRulesSchema = t.intersection([ + t.exact( + t.type({ + description, + risk_score, + name, + severity, + type, + }) + ), + t.exact( + t.partial({ + actions: DefaultActionsArray, // defaults to empty actions array if not set during decode + anomaly_threshold, // defaults to undefined if not set during decode + enabled: DefaultBooleanTrue, // defaults to true if not set during decode + false_positives: DefaultStringArray, // defaults to empty string array if not set during decode + filters, // defaults to undefined if not set during decode + from: DefaultFromString, // defaults to "now-6m" if not set during decode + rule_id: DefaultUuid, + index, // defaults to undefined if not set during decode + interval: DefaultIntervalString, // defaults to "5m" if not set during decode + query, // defaults to undefined if not set during decode + language, // defaults to undefined if not set during decode + // TODO: output_index: This should be removed eventually + output_index, // defaults to "undefined" if not set during decode + saved_id, // defaults to "undefined" if not set during decode + timeline_id, // defaults to "undefined" if not set during decode + timeline_title, // defaults to "undefined" if not set during decode + meta, // defaults to "undefined" if not set during decode + machine_learning_job_id, // defaults to "undefined" if not set during decode + max_signals: DefaultMaxSignalsNumber, // defaults to DEFAULT_MAX_SIGNALS (100) if not set during decode + tags: DefaultStringArray, // defaults to empty string array if not set during decode + to: DefaultToString, // defaults to "now" if not set during decode + threat: DefaultThreatArray, // defaults to empty array if not set during decode + throttle: DefaultThrottleNull, // defaults to "null" if not set during decode + references: DefaultStringArray, // defaults to empty array of strings if not set during decode + note, // defaults to "undefined" if not set during decode + version: DefaultVersionNumber, // defaults to 1 if not set during decode + exceptions_list: ListsDefaultArray, // defaults to empty array if not set during decode + }) + ), +]); + +export type CreateRulesSchema = t.TypeOf; + +// This type is used after a decode since some things are defaults after a decode. +export type CreateRulesSchemaDecoded = Omit< + CreateRulesSchema, + | 'references' + | 'actions' + | 'enabled' + | 'false_positives' + | 'from' + | 'interval' + | 'max_signals' + | 'tags' + | 'to' + | 'threat' + | 'throttle' + | 'version' + | 'exceptions_list' + | 'rule_id' +> & { + references: References; + actions: Actions; + enabled: Enabled; + false_positives: FalsePositives; + from: From; + interval: Interval; + max_signals: MaxSignals; + tags: Tags; + to: To; + threat: Threat; + throttle: ThrottleOrNull; + version: Version; + exceptions_list: ListsDefaultArraySchema; + rule_id: RuleId; +}; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_type_dependents.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_type_dependents.test.ts new file mode 100644 index 0000000000000..ebf0b2e591ca9 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_type_dependents.test.ts @@ -0,0 +1,68 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { getCreateRulesSchemaMock } from './create_rules_schema.mock'; +import { CreateRulesSchema } from './create_rules_schema'; +import { createRuleValidateTypeDependents } from './create_rules_type_dependents'; + +describe('create_rules_type_dependents', () => { + test('saved_id is required when type is saved_query and will not validate without out', () => { + const schema: CreateRulesSchema = { ...getCreateRulesSchemaMock(), type: 'saved_query' }; + delete schema.saved_id; + const errors = createRuleValidateTypeDependents(schema); + expect(errors).toEqual(['when "type" is "saved_query", "saved_id" is required']); + }); + + test('saved_id is required when type is saved_query and validates with it', () => { + const schema: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + type: 'saved_query', + saved_id: '123', + }; + const errors = createRuleValidateTypeDependents(schema); + expect(errors).toEqual([]); + }); + + test('You cannot omit timeline_title when timeline_id is present', () => { + const schema: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + timeline_id: '123', + }; + delete schema.timeline_title; + const errors = createRuleValidateTypeDependents(schema); + expect(errors).toEqual(['when "timeline_id" exists, "timeline_title" must also exist']); + }); + + test('You cannot have empty string for timeline_title when timeline_id is present', () => { + const schema: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + timeline_id: '123', + timeline_title: '', + }; + const errors = createRuleValidateTypeDependents(schema); + expect(errors).toEqual(['"timeline_title" cannot be an empty string']); + }); + + test('You cannot have timeline_title with an empty timeline_id', () => { + const schema: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + timeline_id: '', + timeline_title: 'some-title', + }; + const errors = createRuleValidateTypeDependents(schema); + expect(errors).toEqual(['"timeline_id" cannot be an empty string']); + }); + + test('You cannot have timeline_title without timeline_id', () => { + const schema: CreateRulesSchema = { + ...getCreateRulesSchemaMock(), + timeline_title: 'some-title', + }; + delete schema.timeline_id; + const errors = createRuleValidateTypeDependents(schema); + expect(errors).toEqual(['when "timeline_title" exists, "timeline_id" must also exist']); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_type_dependents.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_type_dependents.ts new file mode 100644 index 0000000000000..aad2a2c4a9206 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/create_rules_type_dependents.ts @@ -0,0 +1,105 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { CreateRulesSchema } from './create_rules_schema'; + +export const validateAnomalyThreshold = (rule: CreateRulesSchema): string[] => { + if (rule.type === 'machine_learning') { + if (rule.anomaly_threshold == null) { + return ['when "type" is "machine_learning" anomaly_threshold is required']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateQuery = (rule: CreateRulesSchema): string[] => { + if (rule.type === 'machine_learning') { + if (rule.query != null) { + return ['when "type" is "machine_learning", "query" cannot be set']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateLanguage = (rule: CreateRulesSchema): string[] => { + if (rule.type === 'machine_learning') { + if (rule.language != null) { + return ['when "type" is "machine_learning", "language" cannot be set']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateSavedId = (rule: CreateRulesSchema): string[] => { + if (rule.type === 'saved_query') { + if (rule.saved_id == null) { + return ['when "type" is "saved_query", "saved_id" is required']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateMachineLearningJobId = (rule: CreateRulesSchema): string[] => { + if (rule.type === 'machine_learning') { + if (rule.machine_learning_job_id == null) { + return ['when "type" is "machine_learning", "machine_learning_job_id" is required']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateTimelineId = (rule: CreateRulesSchema): string[] => { + if (rule.timeline_id != null) { + if (rule.timeline_title == null) { + return ['when "timeline_id" exists, "timeline_title" must also exist']; + } else if (rule.timeline_id === '') { + return ['"timeline_id" cannot be an empty string']; + } else { + return []; + } + } + return []; +}; + +export const validateTimelineTitle = (rule: CreateRulesSchema): string[] => { + if (rule.timeline_title != null) { + if (rule.timeline_id == null) { + return ['when "timeline_title" exists, "timeline_id" must also exist']; + } else if (rule.timeline_title === '') { + return ['"timeline_title" cannot be an empty string']; + } else { + return []; + } + } + return []; +}; + +export const createRuleValidateTypeDependents = (schema: CreateRulesSchema): string[] => { + return [ + ...validateAnomalyThreshold(schema), + ...validateQuery(schema), + ...validateLanguage(schema), + ...validateSavedId(schema), + ...validateMachineLearningJobId(schema), + ...validateTimelineId(schema), + ...validateTimelineTitle(schema), + ]; +}; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/export_rules_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/export_rules_schema.test.ts new file mode 100644 index 0000000000000..3e9799a5ad2f9 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/export_rules_schema.test.ts @@ -0,0 +1,159 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + exportRulesQuerySchema, + exportRulesSchema, + ExportRulesSchema, + ExportRulesQuerySchema, + ExportRulesQuerySchemaDecoded, +} from './export_rules_schema'; +import { exactCheck } from '../../../exact_check'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { foldLeftRight, getPaths } from '../../../test_utils'; +import { left } from 'fp-ts/lib/Either'; + +describe('create rules schema', () => { + describe('exportRulesSchema', () => { + test('null value or absent values validate', () => { + const payload: Partial = null; + + const decoded = exportRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('empty object does not validate', () => { + const payload = {}; + + const decoded = exportRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + // TODO: Change formatter to display a better value than [object Object] + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "objects"', + 'Invalid value "[object Object]" supplied to ""', + ]); + expect(message.schema).toEqual(payload); + }); + + test('empty object array does validate', () => { + const payload: ExportRulesSchema = { objects: [] }; + + const decoded = exportRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('array with rule_id validates', () => { + const payload: ExportRulesSchema = { objects: [{ rule_id: 'test-1' }] }; + + const decoded = exportRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('array with id does not validate as we do not allow that on purpose since we export rule_id', () => { + const payload: Omit & { objects: [{ id: string }] } = { + objects: [{ id: '4a7ff83d-3055-4bb2-ba68-587b9c6c15a4' }], + }; + + const decoded = exportRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + // TODO: Change formatter to display a better value than [object Object] + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "objects,rule_id"', + 'Invalid value "[object Object]" supplied to ""', + ]); + expect(message.schema).toEqual({}); + }); + }); + + describe('exportRulesQuerySchema', () => { + test('default value for file_name is export.ndjson and default for exclude_export_details is false', () => { + const payload: Partial = {}; + + const decoded = exportRulesQuerySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ExportRulesQuerySchemaDecoded = { + file_name: 'export.ndjson', + exclude_export_details: false, + }; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(expected); + }); + + test('file_name validates', () => { + const payload: ExportRulesQuerySchema = { + file_name: 'test.ndjson', + }; + + const decoded = exportRulesQuerySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ExportRulesQuerySchemaDecoded = { + file_name: 'test.ndjson', + exclude_export_details: false, + }; + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(expected); + }); + + test('file_name does not validate with a number', () => { + const payload: Omit & { file_name: number } = { + file_name: 10, + }; + + const decoded = exportRulesQuerySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "10" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('exclude_export_details validates with a boolean true', () => { + const payload: ExportRulesQuerySchema = { + exclude_export_details: true, + }; + + const decoded = exportRulesQuerySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ExportRulesQuerySchemaDecoded = { + exclude_export_details: true, + file_name: 'export.ndjson', + }; + expect(message.schema).toEqual(expected); + }); + + test('exclude_export_details does not validate with a string', () => { + const payload: Omit & { + exclude_export_details: string; + } = { + exclude_export_details: 'invalid string', + }; + + const decoded = exportRulesQuerySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "invalid string" supplied to ""', + ]); + expect(message.schema).toEqual({}); + }); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/export_rules_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/export_rules_schema.ts new file mode 100644 index 0000000000000..75fa2da92b787 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/export_rules_schema.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; + +/* eslint-disable @typescript-eslint/camelcase */ +import { rule_id, FileName, ExcludeExportDetails } from '../common/schemas'; +/* eslint-enable @typescript-eslint/camelcase */ + +import { DefaultExportFileName } from '../types/default_export_file_name'; +import { DefaultStringBooleanFalse } from '../types/default_string_boolean_false'; + +const objects = t.array(t.exact(t.type({ rule_id }))); +export const exportRulesSchema = t.union([t.exact(t.type({ objects })), t.null]); +export type ExportRulesSchema = t.TypeOf; +export type ExportRulesSchemaDecoded = ExportRulesSchema; + +export const exportRulesQuerySchema = t.exact( + t.partial({ file_name: DefaultExportFileName, exclude_export_details: DefaultStringBooleanFalse }) +); + +export type ExportRulesQuerySchema = t.TypeOf; + +export type ExportRulesQuerySchemaDecoded = Omit< + ExportRulesQuerySchema, + 'file_name' | 'exclude_export_details' +> & { + file_name: FileName; + exclude_export_details: ExcludeExportDetails; +}; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rule_statuses_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rule_statuses_schema.ts new file mode 100644 index 0000000000000..1969d9d798d23 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rule_statuses_schema.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; + +export const findRulesStatusesSchema = t.exact( + t.type({ + ids: t.array(t.string), + }) +); + +export type FindRulesStatusesSchema = t.TypeOf; + +export type FindRulesStatusesSchemaDecoded = FindRulesStatusesSchema; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rule_type_dependents.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rule_type_dependents.test.ts new file mode 100644 index 0000000000000..e86e67e47e460 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rule_type_dependents.test.ts @@ -0,0 +1,45 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { FindRulesSchema } from './find_rules_schema'; +import { findRuleValidateTypeDependents } from './find_rules_type_dependents'; + +describe('find_rules_type_dependents', () => { + test('You can have an empty sort_field and empty sort_order', () => { + const schema: FindRulesSchema = {}; + const errors = findRuleValidateTypeDependents(schema); + expect(errors).toEqual([]); + }); + + test('You can have both a sort_field and and a sort_order', () => { + const schema: FindRulesSchema = { + sort_field: 'some field', + sort_order: 'asc', + }; + const errors = findRuleValidateTypeDependents(schema); + expect(errors).toEqual([]); + }); + + test('You cannot have sort_field without sort_order', () => { + const schema: FindRulesSchema = { + sort_field: 'some field', + }; + const errors = findRuleValidateTypeDependents(schema); + expect(errors).toEqual([ + 'when "sort_order" and "sort_field" must exist together or not at all', + ]); + }); + + test('You cannot have sort_order without sort_field', () => { + const schema: FindRulesSchema = { + sort_order: 'asc', + }; + const errors = findRuleValidateTypeDependents(schema); + expect(errors).toEqual([ + 'when "sort_order" and "sort_field" must exist together or not at all', + ]); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rules_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rules_schema.test.ts new file mode 100644 index 0000000000000..46e6ee82055a5 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rules_schema.test.ts @@ -0,0 +1,198 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { exactCheck } from '../../../exact_check'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { foldLeftRight, getPaths } from '../../../test_utils'; +import { left } from 'fp-ts/lib/Either'; +import { FindRulesSchema, findRulesSchema } from './find_rules_schema'; + +describe('find_rules_schema', () => { + test('empty objects do validate', () => { + const payload: FindRulesSchema = {}; + + const decoded = findRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual({ + page: 1, + per_page: 20, + }); + }); + + test('all values validate', () => { + const payload: FindRulesSchema = { + per_page: 5, + page: 1, + sort_field: 'some field', + fields: ['field 1', 'field 2'], + filter: 'some filter', + sort_order: 'asc', + }; + + const decoded = findRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('made up parameters do not validate', () => { + const payload: Partial & { madeUp: string } = { madeUp: 'invalid value' }; + + const decoded = findRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "madeUp"']); + expect(message.schema).toEqual({}); + }); + + test('per_page validates', () => { + const payload: FindRulesSchema = { + per_page: 5, + }; + + const decoded = findRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as FindRulesSchema).per_page).toEqual(payload.per_page); + }); + + test('page validates', () => { + const payload: FindRulesSchema = { + page: 5, + }; + + const decoded = findRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as FindRulesSchema).page).toEqual(payload.page); + }); + + test('sort_field validates', () => { + const payload: FindRulesSchema = { + sort_field: 'value', + }; + + const decoded = findRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as FindRulesSchema).sort_field).toEqual('value'); + }); + + test('fields validates with a string', () => { + const payload: FindRulesSchema = { + fields: ['some value'], + }; + + const decoded = findRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as FindRulesSchema).fields).toEqual(payload.fields); + }); + + test('fields validates with multiple strings', () => { + const payload: FindRulesSchema = { + fields: ['some value 1', 'some value 2'], + }; + + const decoded = findRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as FindRulesSchema).fields).toEqual(payload.fields); + }); + + test('fields does not validate with a number', () => { + const payload: Omit & { fields: number } = { + fields: 5, + }; + + const decoded = findRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to "fields"']); + expect(message.schema).toEqual({}); + }); + + test('per_page has a default of 20', () => { + const payload: FindRulesSchema = {}; + + const decoded = findRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as FindRulesSchema).per_page).toEqual(20); + }); + + test('page has a default of 1', () => { + const payload: FindRulesSchema = {}; + + const decoded = findRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as FindRulesSchema).page).toEqual(1); + }); + + test('filter works with a string', () => { + const payload: FindRulesSchema = { + filter: 'some value 1', + }; + + const decoded = findRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as FindRulesSchema).filter).toEqual(payload.filter); + }); + + test('filter does not work with a number', () => { + const payload: Omit & { filter: number } = { + filter: 5, + }; + + const decoded = findRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to "filter"']); + expect(message.schema).toEqual({}); + }); + + test('sort_order validates with desc and sort_field', () => { + const payload: FindRulesSchema = { + sort_order: 'desc', + sort_field: 'some field', + }; + + const decoded = findRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as FindRulesSchema).sort_order).toEqual(payload.sort_order); + expect((message.schema as FindRulesSchema).sort_field).toEqual(payload.sort_field); + }); + + test('sort_order does not validate with a string other than asc and desc', () => { + const payload: Omit & { sort_order: string } = { + sort_order: 'some other string', + sort_field: 'some field', + }; + + const decoded = findRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "some other string" supplied to "sort_order"', + ]); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rules_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rules_schema.ts new file mode 100644 index 0000000000000..87076803c9582 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rules_schema.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; + +/* eslint-disable @typescript-eslint/camelcase */ +import { queryFilter, fields, sort_field, sort_order, PerPage, Page } from '../common/schemas'; +import { DefaultPerPage } from '../types/default_per_page'; +import { DefaultPage } from '../types/default_page'; +/* eslint-enable @typescript-eslint/camelcase */ + +export const findRulesSchema = t.exact( + t.partial({ + fields, + filter: queryFilter, + per_page: DefaultPerPage, // defaults to "20" if not sent in during decode + page: DefaultPage, // defaults to "1" if not sent in during decode + sort_field, + sort_order, + }) +); + +export type FindRulesSchema = t.TypeOf; +export type FindRulesSchemaDecoded = Omit & { + per_page: PerPage; + page: Page; +}; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rules_type_dependents.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rules_type_dependents.ts new file mode 100644 index 0000000000000..6916f102e4f57 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/find_rules_type_dependents.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { FindRulesSchema } from './find_rules_schema'; + +export const validateSortOrder = (find: FindRulesSchema): string[] => { + if (find.sort_order != null || find.sort_field != null) { + if (find.sort_order == null || find.sort_field == null) { + return ['when "sort_order" and "sort_field" must exist together or not at all']; + } else { + return []; + } + } else { + return []; + } +}; + +export const findRuleValidateTypeDependents = (schema: FindRulesSchema): string[] => { + return [...validateSortOrder(schema)]; +}; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_schema.mock.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_schema.mock.ts new file mode 100644 index 0000000000000..92fab202c9ddc --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_schema.mock.ts @@ -0,0 +1,44 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ImportRulesSchema, ImportRulesSchemaDecoded } from './import_rules_schema'; +import { DEFAULT_MAX_SIGNALS } from '../../../constants'; + +export const getImportRulesSchemaMock = (): ImportRulesSchema => ({ + description: 'some description', + name: 'Query with a rule id', + query: 'user.name: root or user.name: admin', + severity: 'high', + type: 'query', + risk_score: 55, + language: 'kuery', + rule_id: 'rule-1', +}); + +export const getImportRulesSchemaDecodedMock = (): ImportRulesSchemaDecoded => ({ + description: 'some description', + name: 'Query with a rule id', + query: 'user.name: root or user.name: admin', + severity: 'high', + type: 'query', + risk_score: 55, + language: 'kuery', + references: [], + actions: [], + enabled: true, + false_positives: [], + from: 'now-6m', + interval: '5m', + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + to: 'now', + threat: [], + throttle: null, + version: 1, + exceptions_list: [], + rule_id: 'rule-1', + immutable: false, +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_schema.test.ts new file mode 100644 index 0000000000000..be2c3e046fe91 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_schema.test.ts @@ -0,0 +1,1579 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { exactCheck } from '../../../exact_check'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { foldLeftRight, getPaths } from '../../../test_utils'; +import { left } from 'fp-ts/lib/Either'; +import { + ImportRulesSchema, + importRulesSchema, + ImportRulesSchemaDecoded, + importRulesQuerySchema, + ImportRulesQuerySchema, + importRulesPayloadSchema, + ImportRulesPayloadSchema, +} from './import_rules_schema'; +import { + getImportRulesSchemaMock, + getImportRulesSchemaDecodedMock, +} from './import_rules_schema.mock'; +import { DEFAULT_MAX_SIGNALS } from '../../../constants'; + +describe('import rules schema', () => { + test('empty objects do not validate', () => { + const payload: Partial = {}; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "description"', + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + 'Invalid value "undefined" supplied to "rule_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('made up values do not validate', () => { + const payload: ImportRulesSchema & { madeUp: string } = { + ...getImportRulesSchemaMock(), + madeUp: 'hi', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "madeUp"']); + expect(message.schema).toEqual({}); + }); + + test('[rule_id] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "description"', + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity, type] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity, type, interval] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity, type, interval, index] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + interval: '5m', + index: ['index-1'], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity, type, query, index, interval] does validate', () => { + const payload: ImportRulesSchema = { + rule_id: 'rule-1', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + query: 'some query', + index: ['index-1'], + interval: '5m', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + rule_id: 'rule-1', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + query: 'some query', + index: ['index-1'], + interval: '5m', + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + version: 1, + exceptions_list: [], + immutable: false, + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, query, language] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, query, language, risk_score] does validate', () => { + const payload: ImportRulesSchema = { + rule_id: 'rule-1', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + rule_id: 'rule-1', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + version: 1, + exceptions_list: [], + immutable: false, + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, query, language, risk_score, output_index] does validate', () => { + const payload: ImportRulesSchema = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + version: 1, + exceptions_list: [], + immutable: false, + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score] does validate', () => { + const payload: ImportRulesSchema = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + risk_score: 50, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + risk_score: 50, + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + version: 1, + exceptions_list: [], + immutable: false, + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, output_index] does validate', () => { + const payload: ImportRulesSchema = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + version: 1, + exceptions_list: [], + immutable: false, + }; + expect(message.schema).toEqual(expected); + }); + + test('You can send in an empty array to threat', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + threat: [], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + ...getImportRulesSchemaDecodedMock(), + threat: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, output_index, threat] does validate', () => { + const payload: ImportRulesSchema = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + threat: [ + { + framework: 'someFramework', + tactic: { + id: 'fakeId', + name: 'fakeName', + reference: 'fakeRef', + }, + technique: [ + { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + ], + }, + ], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + immutable: false, + threat: [ + { + framework: 'someFramework', + tactic: { + id: 'fakeId', + name: 'fakeName', + reference: 'fakeRef', + }, + technique: [ + { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + ], + }, + ], + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + throttle: null, + version: 1, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('allows references to be sent as valid', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + references: ['index-1'], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + ...getImportRulesSchemaDecodedMock(), + references: ['index-1'], + }; + expect(message.schema).toEqual(expected); + }); + + test('defaults references to an array if it is not sent in', () => { + const { references, ...noReferences } = getImportRulesSchemaMock(); + const decoded = importRulesSchema.decode(noReferences); + const checked = exactCheck(noReferences, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + ...getImportRulesSchemaDecodedMock(), + references: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('references cannot be numbers', () => { + const payload: Omit & { references: number[] } = { + ...getImportRulesSchemaMock(), + references: [5], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('indexes cannot be numbers', () => { + const payload: Omit & { index: number[] } = { + ...getImportRulesSchemaMock(), + index: [5], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to "index"']); + expect(message.schema).toEqual({}); + }); + + test('defaults interval to 5 min', () => { + const { interval, ...noInterval } = getImportRulesSchemaMock(); + const payload: ImportRulesSchema = { + ...noInterval, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { interval: expectedInterval, ...expectedNoInterval } = getImportRulesSchemaDecodedMock(); + const expected: ImportRulesSchemaDecoded = { + ...expectedNoInterval, + interval: '5m', + }; + expect(message.schema).toEqual(expected); + }); + + test('defaults max signals to 100', () => { + const { max_signals, ...noMaxSignals } = getImportRulesSchemaMock(); + const payload: ImportRulesSchema = { + ...noMaxSignals, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { + max_signals: expectedMaxSignals, + ...expectedNoMaxSignals + } = getImportRulesSchemaDecodedMock(); + const expected: ImportRulesSchemaDecoded = { + ...expectedNoMaxSignals, + max_signals: 100, + }; + expect(message.schema).toEqual(expected); + }); + + test('saved_query type can have filters with it', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + filters: [], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + ...getImportRulesSchemaDecodedMock(), + filters: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('filters cannot be a string', () => { + const payload: Omit & { filters: string } = { + ...getImportRulesSchemaMock(), + filters: 'some string', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "some string" supplied to "filters"', + ]); + expect(message.schema).toEqual({}); + }); + + test('language validates with kuery', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + language: 'kuery', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + ...getImportRulesSchemaDecodedMock(), + language: 'kuery', + }; + expect(message.schema).toEqual(expected); + }); + + test('language validates with lucene', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + language: 'lucene', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + ...getImportRulesSchemaDecodedMock(), + language: 'lucene', + }; + expect(message.schema).toEqual(expected); + }); + + test('language does not validate with something made up', () => { + const payload: Omit & { language: string } = { + ...getImportRulesSchemaMock(), + language: 'something-made-up', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "something-made-up" supplied to "language"', + ]); + expect(message.schema).toEqual({}); + }); + + test('max_signals cannot be negative', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + max_signals: -1, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "-1" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('max_signals cannot be zero', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + max_signals: 0, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "0" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('max_signals can be 1', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + max_signals: 1, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + ...getImportRulesSchemaDecodedMock(), + max_signals: 1, + }; + expect(message.schema).toEqual(expected); + }); + + test('You can optionally send in an array of tags', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + tags: ['tag_1', 'tag_2'], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + ...getImportRulesSchemaDecodedMock(), + tags: ['tag_1', 'tag_2'], + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot send in an array of tags that are numbers', () => { + const payload: Omit & { tags: number[] } = { + ...getImportRulesSchemaMock(), + tags: [0, 1, 2], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "0" supplied to ""', + 'Invalid value "1" supplied to ""', + 'Invalid value "2" supplied to ""', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of threat that are missing "framework"', () => { + const payload: Omit & { + threat: Array>>; + } = { + ...getImportRulesSchemaMock(), + threat: [ + { + tactic: { + id: 'fakeId', + name: 'fakeName', + reference: 'fakeRef', + }, + technique: [ + { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + ], + }, + ], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "framework"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of threat that are missing "tactic"', () => { + const payload: Omit & { + threat: Array>>; + } = { + ...getImportRulesSchemaMock(), + threat: [ + { + framework: 'fake', + technique: [ + { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + ], + }, + ], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "tactic"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of threat that are missing "technique"', () => { + const payload: Omit & { + threat: Array>>; + } = { + ...getImportRulesSchemaMock(), + threat: [ + { + framework: 'fake', + tactic: { + id: 'fakeId', + name: 'fakeName', + reference: 'fakeRef', + }, + }, + ], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "technique"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You can optionally send in an array of false positives', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + false_positives: ['false_1', 'false_2'], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + ...getImportRulesSchemaDecodedMock(), + false_positives: ['false_1', 'false_2'], + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot send in an array of false positives that are numbers', () => { + const payload: Omit & { false_positives: number[] } = { + ...getImportRulesSchemaMock(), + false_positives: [5, 4], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "5" supplied to ""', + 'Invalid value "4" supplied to ""', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot set the immutable to a number when trying to create a rule', () => { + const payload: Omit & { immutable: number } = { + ...getImportRulesSchemaMock(), + immutable: 5, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to "immutable"']); + expect(message.schema).toEqual({}); + }); + + test('You can optionally set the immutable to be false', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + immutable: false, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getImportRulesSchemaDecodedMock()); + }); + + test('You cannot set the immutable to be true', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + immutable: true, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "true" supplied to "immutable"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot set the immutable to be a number', () => { + const payload: Omit & { immutable: number } = { + ...getImportRulesSchemaMock(), + immutable: 5, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to "immutable"']); + expect(message.schema).toEqual({}); + }); + + test('You cannot set the risk_score to 101', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + risk_score: 101, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "101" supplied to "risk_score"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot set the risk_score to -1', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + risk_score: -1, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "-1" supplied to "risk_score"']); + expect(message.schema).toEqual({}); + }); + + test('You can set the risk_score to 0', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + risk_score: 0, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + ...getImportRulesSchemaDecodedMock(), + risk_score: 0, + }; + expect(message.schema).toEqual(expected); + }); + + test('You can set the risk_score to 100', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + risk_score: 100, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + ...getImportRulesSchemaDecodedMock(), + risk_score: 100, + }; + expect(message.schema).toEqual(expected); + }); + + test('You can set meta to any object you want', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + meta: { + somethingMadeUp: { somethingElse: true }, + }, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + ...getImportRulesSchemaDecodedMock(), + meta: { + somethingMadeUp: { somethingElse: true }, + }, + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot create meta as a string', () => { + const payload: Omit & { meta: string } = { + ...getImportRulesSchemaMock(), + meta: 'should not work', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "should not work" supplied to "meta"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You can omit the query string when filters are present', () => { + const { query, ...noQuery } = getImportRulesSchemaMock(); + const payload: ImportRulesSchema = { + ...noQuery, + filters: [], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { query: expectedQuery, ...expectedNoQuery } = getImportRulesSchemaDecodedMock(); + const expected: ImportRulesSchemaDecoded = { + ...expectedNoQuery, + filters: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('validates with timeline_id and timeline_title', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + timeline_id: 'timeline-id', + timeline_title: 'timeline-title', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + ...getImportRulesSchemaDecodedMock(), + timeline_id: 'timeline-id', + timeline_title: 'timeline-title', + }; + expect(message.schema).toEqual(expected); + }); + + test('rule_id is required and you cannot get by with just id', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + id: 'c4e80a0d-e20f-4efc-84c1-08112da5a612', + }; + delete payload.rule_id; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "rule_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it validates with created_at, updated_at, created_by, updated_by values', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + created_at: '2020-01-09T06:15:24.749Z', + updated_at: '2020-01-09T06:15:24.749Z', + created_by: 'Braden Hassanabad', + updated_by: 'Evan Hassanabad', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + ...getImportRulesSchemaDecodedMock(), + created_at: '2020-01-09T06:15:24.749Z', + updated_at: '2020-01-09T06:15:24.749Z', + created_by: 'Braden Hassanabad', + updated_by: 'Evan Hassanabad', + }; + expect(message.schema).toEqual(expected); + }); + + test('it does not validate with epoch strings for created_at', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + created_at: '1578550728650', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1578550728650" supplied to "created_at"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it does not validate with epoch strings for updated_at', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + updated_at: '1578550728650', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "1578550728650" supplied to "updated_at"', + ]); + expect(message.schema).toEqual({}); + }); + + describe('importRulesQuerySchema', () => { + test('overwrite gets a default value of false', () => { + const payload: ImportRulesQuerySchema = {}; + + const decoded = importRulesQuerySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual({ + overwrite: false, + }); + }); + + test('overwrite validates with a boolean true', () => { + const payload: ImportRulesQuerySchema = { overwrite: true }; + + const decoded = importRulesQuerySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual({ + overwrite: true, + }); + }); + + test('overwrite does not validate with a weird string', () => { + const payload: Omit & { overwrite: string } = { + overwrite: 'invalid-string', + }; + + const decoded = importRulesQuerySchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "invalid-string" supplied to ""', + ]); + expect(message.schema).toEqual({}); + }); + }); + + describe('importRulesPayloadSchema', () => { + test('does not validate with an empty object', () => { + const payload = {}; + + const decoded = importRulesPayloadSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "file"', + ]); + expect(message.schema).toEqual({}); + }); + + test('does not validate with a made string', () => { + const payload: Omit & { madeUpKey: string } = { + madeUpKey: 'madeupstring', + }; + + const decoded = importRulesPayloadSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "file"', + ]); + expect(message.schema).toEqual({}); + }); + + test('does validate with a file object', () => { + const payload: ImportRulesPayloadSchema = { file: {} }; + + const decoded = importRulesPayloadSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + }); + + test('The default for "from" will be "now-6m"', () => { + const { from, ...noFrom } = getImportRulesSchemaMock(); + const payload: ImportRulesSchema = { + ...noFrom, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { from: expectedFrom, ...expectedNoFrom } = getImportRulesSchemaDecodedMock(); + const expected: ImportRulesSchemaDecoded = { + ...expectedNoFrom, + from: 'now-6m', + }; + expect(message.schema).toEqual(expected); + }); + + test('The default for "to" will be "now"', () => { + const { to, ...noTo } = getImportRulesSchemaMock(); + const payload: ImportRulesSchema = { + ...noTo, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { to: expectedTo, ...expectedNoTo } = getImportRulesSchemaDecodedMock(); + const expected: ImportRulesSchemaDecoded = { + ...expectedNoTo, + to: 'now', + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot set the severity to a value other than low, medium, high, or critical', () => { + const payload: Omit & { severity: string } = { + ...getImportRulesSchemaMock(), + severity: 'junk', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "junk" supplied to "severity"']); + expect(message.schema).toEqual({}); + }); + + test('The default for "actions" will be an empty array', () => { + const { actions, ...noActions } = getImportRulesSchemaMock(); + const payload: ImportRulesSchema = { + ...noActions, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { actions: expectedActions, ...expectedNoActions } = getImportRulesSchemaDecodedMock(); + const expected: ImportRulesSchemaDecoded = { + ...expectedNoActions, + actions: [], + }; + expect(message.schema).toEqual(expected); + }); + test('You cannot send in an array of actions that are missing "group"', () => { + const payload: Omit = { + ...getImportRulesSchemaMock(), + actions: [{ id: 'id', action_type_id: 'action_type_id', params: {} }], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "group"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are missing "id"', () => { + const payload: Omit = { + ...getImportRulesSchemaMock(), + actions: [{ group: 'group', action_type_id: 'action_type_id', params: {} }], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are missing "action_type_id"', () => { + const payload: Omit = { + ...getImportRulesSchemaMock(), + actions: [{ group: 'group', id: 'id', params: {} }], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "action_type_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are missing "params"', () => { + const payload: Omit = { + ...getImportRulesSchemaMock(), + actions: [{ group: 'group', id: 'id', action_type_id: 'action_type_id' }], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "params"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are including "actionTypeId"', () => { + const payload: Omit = { + ...getImportRulesSchemaMock(), + actions: [ + { + group: 'group', + id: 'id', + actionTypeId: 'actionTypeId', + params: {}, + }, + ], + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "action_type_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('The default for "throttle" will be null', () => { + const { throttle, ...noThrottle } = getImportRulesSchemaMock(); + const payload: ImportRulesSchema = { + ...noThrottle, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { throttle: expectedThrottle, ...expectedNoThrottle } = getImportRulesSchemaDecodedMock(); + const expected: ImportRulesSchemaDecoded = { + ...expectedNoThrottle, + throttle: null, + }; + expect(message.schema).toEqual(expected); + }); + + describe('note', () => { + test('You can set note to a string', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + note: '# documentation markdown here', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + ...getImportRulesSchemaDecodedMock(), + note: '# documentation markdown here', + }; + expect(message.schema).toEqual(expected); + }); + + test('You can set note to an empty string', () => { + const payload: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + note: '', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + ...getImportRulesSchemaDecodedMock(), + note: '', + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot create note as an object', () => { + const payload: Omit & { note: {} } = { + ...getImportRulesSchemaMock(), + note: { + somethingHere: 'something else', + }, + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + // TODO: Fix/Change the formatErrors to be better able to handle objects + 'Invalid value "[object Object]" supplied to "note"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note] does validate', () => { + const payload: ImportRulesSchema = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + risk_score: 50, + note: '# some markdown', + }; + + const decoded = importRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: ImportRulesSchemaDecoded = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + risk_score: 50, + note: '# some markdown', + references: [], + actions: [], + enabled: true, + false_positives: [], + immutable: false, + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + version: 1, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + }); + + // TODO: The exception_list tests are skipped and empty until we re-integrate it from the lists plugin + describe.skip('exception_list', () => { + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and exceptions_list] does validate', () => {}); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and empty exceptions_list] does validate', () => {}); + + test('rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and invalid exceptions_list] does NOT validate', () => {}); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and non-existent exceptions_list] does validate with empty exceptions_list', () => {}); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_schema.ts new file mode 100644 index 0000000000000..a2110263e8e51 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_schema.ts @@ -0,0 +1,180 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; + +/* eslint-disable @typescript-eslint/camelcase */ +import { + description, + anomaly_threshold, + filters, + RuleId, + index, + output_index, + saved_id, + timeline_id, + timeline_title, + meta, + machine_learning_job_id, + risk_score, + MaxSignals, + name, + severity, + Tags, + To, + type, + Threat, + ThrottleOrNull, + note, + Version, + References, + Actions, + Enabled, + FalsePositives, + From, + Interval, + language, + query, + rule_id, + id, + created_at, + updated_at, + created_by, + updated_by, +} from '../common/schemas'; +/* eslint-enable @typescript-eslint/camelcase */ + +import { DefaultStringArray } from '../types/default_string_array'; +import { DefaultActionsArray } from '../types/default_actions_array'; +import { DefaultBooleanTrue } from '../types/default_boolean_true'; +import { DefaultFromString } from '../types/default_from_string'; +import { DefaultIntervalString } from '../types/default_interval_string'; +import { DefaultMaxSignalsNumber } from '../types/default_max_signals_number'; +import { DefaultToString } from '../types/default_to_string'; +import { DefaultThreatArray } from '../types/default_threat_array'; +import { DefaultThrottleNull } from '../types/default_throttle_null'; +import { DefaultVersionNumber } from '../types/default_version_number'; +import { ListsDefaultArray, ListsDefaultArraySchema } from '../types/lists_default_array'; +import { OnlyFalseAllowed } from '../types/only_false_allowed'; +import { DefaultStringBooleanFalse } from '../types/default_string_boolean_false'; + +/** + * Differences from this and the createRulesSchema are + * - rule_id is required + * - id is optional (but ignored in the import code - rule_id is exclusively used for imports) + * - immutable is optional but if it is any value other than false it will be rejected + * - created_at is optional (but ignored in the import code) + * - updated_at is optional (but ignored in the import code) + * - created_by is optional (but ignored in the import code) + * - updated_by is optional (but ignored in the import code) + */ +export const importRulesSchema = t.intersection([ + t.exact( + t.type({ + description, + risk_score, + name, + severity, + type, + rule_id, + }) + ), + t.exact( + t.partial({ + id, // defaults to undefined if not set during decode + actions: DefaultActionsArray, // defaults to empty actions array if not set during decode + anomaly_threshold, // defaults to undefined if not set during decode + enabled: DefaultBooleanTrue, // defaults to true if not set during decode + false_positives: DefaultStringArray, // defaults to empty string array if not set during decode + filters, // defaults to undefined if not set during decode + from: DefaultFromString, // defaults to "now-6m" if not set during decode + index, // defaults to undefined if not set during decode + immutable: OnlyFalseAllowed, // defaults to "false" if not set during decode + interval: DefaultIntervalString, // defaults to "5m" if not set during decode + query, // defaults to undefined if not set during decode + language, // defaults to undefined if not set during decode + // TODO: output_index: This should be removed eventually + output_index, // defaults to "undefined" if not set during decode + saved_id, // defaults to "undefined" if not set during decode + timeline_id, // defaults to "undefined" if not set during decode + timeline_title, // defaults to "undefined" if not set during decode + meta, // defaults to "undefined" if not set during decode + machine_learning_job_id, // defaults to "undefined" if not set during decode + max_signals: DefaultMaxSignalsNumber, // defaults to DEFAULT_MAX_SIGNALS (100) if not set during decode + tags: DefaultStringArray, // defaults to empty string array if not set during decode + to: DefaultToString, // defaults to "now" if not set during decode + threat: DefaultThreatArray, // defaults to empty array if not set during decode + throttle: DefaultThrottleNull, // defaults to "null" if not set during decode + references: DefaultStringArray, // defaults to empty array of strings if not set during decode + note, // defaults to "undefined" if not set during decode + version: DefaultVersionNumber, // defaults to 1 if not set during decode + exceptions_list: ListsDefaultArray, // defaults to empty array if not set during decode + created_at, // defaults "undefined" if not set during decode + updated_at, // defaults "undefined" if not set during decode + created_by, // defaults "undefined" if not set during decode + updated_by, // defaults "undefined" if not set during decode + }) + ), +]); + +export type ImportRulesSchema = t.TypeOf; + +// This type is used after a decode since some things are defaults after a decode. +export type ImportRulesSchemaDecoded = Omit< + ImportRulesSchema, + | 'references' + | 'actions' + | 'enabled' + | 'false_positives' + | 'from' + | 'interval' + | 'max_signals' + | 'tags' + | 'to' + | 'threat' + | 'throttle' + | 'version' + | 'exceptions_list' + | 'rule_id' + | 'immutable' +> & { + references: References; + actions: Actions; + enabled: Enabled; + false_positives: FalsePositives; + from: From; + interval: Interval; + max_signals: MaxSignals; + tags: Tags; + to: To; + threat: Threat; + throttle: ThrottleOrNull; + version: Version; + exceptions_list: ListsDefaultArraySchema; + rule_id: RuleId; + immutable: false; +}; + +export const importRulesQuerySchema = t.exact( + t.partial({ + overwrite: DefaultStringBooleanFalse, + }) +); + +export type ImportRulesQuerySchema = t.TypeOf; +export type ImportRulesQuerySchemaDecoded = Omit & { + overwrite: boolean; +}; + +export const importRulesPayloadSchema = t.exact( + t.type({ + file: t.object, + }) +); + +export type ImportRulesPayloadSchema = t.TypeOf; + +export type ImportRulesPayloadSchemaDecoded = ImportRulesPayloadSchema; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_type_dependents.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_type_dependents.test.ts new file mode 100644 index 0000000000000..f9b989c81e533 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_type_dependents.test.ts @@ -0,0 +1,68 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { getImportRulesSchemaMock } from './import_rules_schema.mock'; +import { ImportRulesSchema } from './import_rules_schema'; +import { importRuleValidateTypeDependents } from './import_rules_type_dependents'; + +describe('import_rules_type_dependents', () => { + test('saved_id is required when type is saved_query and will not validate without out', () => { + const schema: ImportRulesSchema = { ...getImportRulesSchemaMock(), type: 'saved_query' }; + delete schema.saved_id; + const errors = importRuleValidateTypeDependents(schema); + expect(errors).toEqual(['when "type" is "saved_query", "saved_id" is required']); + }); + + test('saved_id is required when type is saved_query and validates with it', () => { + const schema: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + type: 'saved_query', + saved_id: '123', + }; + const errors = importRuleValidateTypeDependents(schema); + expect(errors).toEqual([]); + }); + + test('You cannot omit timeline_title when timeline_id is present', () => { + const schema: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + timeline_id: '123', + }; + delete schema.timeline_title; + const errors = importRuleValidateTypeDependents(schema); + expect(errors).toEqual(['when "timeline_id" exists, "timeline_title" must also exist']); + }); + + test('You cannot have empty string for timeline_title when timeline_id is present', () => { + const schema: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + timeline_id: '123', + timeline_title: '', + }; + const errors = importRuleValidateTypeDependents(schema); + expect(errors).toEqual(['"timeline_title" cannot be an empty string']); + }); + + test('You cannot have timeline_title with an empty timeline_id', () => { + const schema: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + timeline_id: '', + timeline_title: 'some-title', + }; + const errors = importRuleValidateTypeDependents(schema); + expect(errors).toEqual(['"timeline_id" cannot be an empty string']); + }); + + test('You cannot have timeline_title without timeline_id', () => { + const schema: ImportRulesSchema = { + ...getImportRulesSchemaMock(), + timeline_title: 'some-title', + }; + delete schema.timeline_id; + const errors = importRuleValidateTypeDependents(schema); + expect(errors).toEqual(['when "timeline_title" exists, "timeline_id" must also exist']); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_type_dependents.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_type_dependents.ts new file mode 100644 index 0000000000000..59191a4fe3121 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/import_rules_type_dependents.ts @@ -0,0 +1,105 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ImportRulesSchema } from './import_rules_schema'; + +export const validateAnomalyThreshold = (rule: ImportRulesSchema): string[] => { + if (rule.type === 'machine_learning') { + if (rule.anomaly_threshold == null) { + return ['when "type" is "machine_learning" anomaly_threshold is required']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateQuery = (rule: ImportRulesSchema): string[] => { + if (rule.type === 'machine_learning') { + if (rule.query != null) { + return ['when "type" is "machine_learning", "query" cannot be set']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateLanguage = (rule: ImportRulesSchema): string[] => { + if (rule.type === 'machine_learning') { + if (rule.language != null) { + return ['when "type" is "machine_learning", "language" cannot be set']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateSavedId = (rule: ImportRulesSchema): string[] => { + if (rule.type === 'saved_query') { + if (rule.saved_id == null) { + return ['when "type" is "saved_query", "saved_id" is required']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateMachineLearningJobId = (rule: ImportRulesSchema): string[] => { + if (rule.type === 'machine_learning') { + if (rule.machine_learning_job_id == null) { + return ['when "type" is "machine_learning", "machine_learning_job_id" is required']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateTimelineId = (rule: ImportRulesSchema): string[] => { + if (rule.timeline_id != null) { + if (rule.timeline_title == null) { + return ['when "timeline_id" exists, "timeline_title" must also exist']; + } else if (rule.timeline_id === '') { + return ['"timeline_id" cannot be an empty string']; + } else { + return []; + } + } + return []; +}; + +export const validateTimelineTitle = (rule: ImportRulesSchema): string[] => { + if (rule.timeline_title != null) { + if (rule.timeline_id == null) { + return ['when "timeline_title" exists, "timeline_id" must also exist']; + } else if (rule.timeline_title === '') { + return ['"timeline_title" cannot be an empty string']; + } else { + return []; + } + } + return []; +}; + +export const importRuleValidateTypeDependents = (schema: ImportRulesSchema): string[] => { + return [ + ...validateAnomalyThreshold(schema), + ...validateQuery(schema), + ...validateLanguage(schema), + ...validateSavedId(schema), + ...validateMachineLearningJobId(schema), + ...validateTimelineId(schema), + ...validateTimelineTitle(schema), + ]; +}; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rule_type_dependents.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rule_type_dependents.test.ts new file mode 100644 index 0000000000000..a388e69332072 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rule_type_dependents.test.ts @@ -0,0 +1,81 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { getPatchRulesSchemaMock } from './patch_rules_schema.mock'; +import { PatchRulesSchema } from './patch_rules_schema'; +import { patchRuleValidateTypeDependents } from './patch_rules_type_dependents'; + +describe('patch_rules_type_dependents', () => { + test('saved_id is required when type is saved_query and validates with it', () => { + const schema: PatchRulesSchema = { + ...getPatchRulesSchemaMock(), + type: 'saved_query', + saved_id: '123', + }; + const errors = patchRuleValidateTypeDependents(schema); + expect(errors).toEqual([]); + }); + + test('You cannot omit timeline_title when timeline_id is present', () => { + const schema: PatchRulesSchema = { + ...getPatchRulesSchemaMock(), + timeline_id: '123', + }; + delete schema.timeline_title; + const errors = patchRuleValidateTypeDependents(schema); + expect(errors).toEqual(['when "timeline_id" exists, "timeline_title" must also exist']); + }); + + test('You cannot have empty string for timeline_title when timeline_id is present', () => { + const schema: PatchRulesSchema = { + ...getPatchRulesSchemaMock(), + timeline_id: '123', + timeline_title: '', + }; + const errors = patchRuleValidateTypeDependents(schema); + expect(errors).toEqual(['"timeline_title" cannot be an empty string']); + }); + + test('You cannot have timeline_title with an empty timeline_id', () => { + const schema: PatchRulesSchema = { + ...getPatchRulesSchemaMock(), + timeline_id: '', + timeline_title: 'some-title', + }; + const errors = patchRuleValidateTypeDependents(schema); + expect(errors).toEqual(['"timeline_id" cannot be an empty string']); + }); + + test('You cannot have timeline_title without timeline_id', () => { + const schema: PatchRulesSchema = { + ...getPatchRulesSchemaMock(), + timeline_title: 'some-title', + }; + delete schema.timeline_id; + const errors = patchRuleValidateTypeDependents(schema); + expect(errors).toEqual(['when "timeline_title" exists, "timeline_id" must also exist']); + }); + + test('You cannot have both an id and a rule_id', () => { + const schema: PatchRulesSchema = { + ...getPatchRulesSchemaMock(), + id: 'some-id', + rule_id: 'some-rule-id', + }; + const errors = patchRuleValidateTypeDependents(schema); + expect(errors).toEqual(['both "id" and "rule_id" cannot exist, choose one or the other']); + }); + + test('You must set either an id or a rule_id', () => { + const schema: PatchRulesSchema = { + ...getPatchRulesSchemaMock(), + }; + delete schema.id; + delete schema.rule_id; + const errors = patchRuleValidateTypeDependents(schema); + expect(errors).toEqual(['either "id" or "rule_id" must be set']); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_bulk_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_bulk_schema.test.ts new file mode 100644 index 0000000000000..7b86c02e5c475 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_bulk_schema.test.ts @@ -0,0 +1,101 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { patchRulesBulkSchema, PatchRulesBulkSchema } from './patch_rules_bulk_schema'; +import { exactCheck } from '../../../exact_check'; +import { foldLeftRight } from '../../../test_utils'; +import { formatErrors } from '../../../format_errors'; +import { PatchRulesSchema } from './patch_rules_schema'; + +// only the basics of testing are here. +// see: patch_rules_schema.test.ts for the bulk of the validation tests +// this just wraps patchRulesSchema in an array +describe('patch_rules_bulk_schema', () => { + test('can take an empty array and validate it', () => { + const payload: PatchRulesBulkSchema = []; + + const decoded = patchRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(output.errors).toEqual([]); + expect(output.schema).toEqual([]); + }); + + test('made up values do not validate for a single element', () => { + const payload: Array<{ madeUp: string }> = [{ madeUp: 'hi' }]; + + const decoded = patchRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual(['invalid keys "madeUp"']); + expect(output.schema).toEqual({}); + }); + + test('single array of [id] does validate', () => { + const payload: PatchRulesBulkSchema = [{ id: '4125761e-51da-4de9-a0c8-42824f532ddb' }]; + + const decoded = patchRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect(output.schema).toEqual(payload); + }); + + test('two arrays of [id] validate', () => { + const payload: PatchRulesBulkSchema = [ + { id: '4125761e-51da-4de9-a0c8-42824f532ddb' }, + { id: '192f403d-b285-4251-9e8b-785fcfcf22e8' }, + ]; + + const decoded = patchRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect(output.schema).toEqual(payload); + }); + + test('can set "note" to be a string', () => { + const payload: PatchRulesBulkSchema = [ + { id: '4125761e-51da-4de9-a0c8-42824f532ddb' }, + { note: 'hi' }, + ]; + + const decoded = patchRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect(output.schema).toEqual(payload); + }); + + test('can set "note" to be an empty string', () => { + const payload: PatchRulesBulkSchema = [ + { id: '4125761e-51da-4de9-a0c8-42824f532ddb' }, + { note: '' }, + ]; + + const decoded = patchRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect(output.schema).toEqual(payload); + }); + + test('cannot set "note" to be anything other than a string', () => { + const payload: Array & { note?: object }> = [ + { id: '4125761e-51da-4de9-a0c8-42824f532ddb' }, + { note: { someprop: 'some value here' } }, + ]; + + const decoded = patchRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + // TODO: Fix the formatter to give something better than [object Object] + expect(formatErrors(output.errors)).toEqual([ + 'Invalid value "[object Object]" supplied to "note"', + ]); + expect(output.schema).toEqual({}); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_bulk_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_bulk_schema.ts new file mode 100644 index 0000000000000..272e36751e37b --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_bulk_schema.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; + +import { patchRulesSchema, PatchRulesSchemaDecoded } from './patch_rules_schema'; + +export const patchRulesBulkSchema = t.array(patchRulesSchema); +export type PatchRulesBulkSchema = t.TypeOf; + +export type PatchRulesBulkSchemaDecoded = PatchRulesSchemaDecoded[]; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_schema.mock.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_schema.mock.ts new file mode 100644 index 0000000000000..7b4f632cdebf0 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_schema.mock.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { PatchRulesSchema, PatchRulesSchemaDecoded } from './patch_rules_schema'; + +export const getPatchRulesSchemaMock = (): PatchRulesSchema => ({ + description: 'some description', + name: 'Query with a rule id', + query: 'user.name: root or user.name: admin', + severity: 'high', + type: 'query', + risk_score: 55, + language: 'kuery', + rule_id: 'rule-1', +}); + +export const getPatchRulesSchemaDecodedMock = (): PatchRulesSchemaDecoded => + getPatchRulesSchemaMock(); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_schema.test.ts new file mode 100644 index 0000000000000..921e07a29609c --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_schema.test.ts @@ -0,0 +1,1153 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { patchRulesSchema, PatchRulesSchema, PatchRulesSchemaDecoded } from './patch_rules_schema'; +import { getPatchRulesSchemaMock, getPatchRulesSchemaDecodedMock } from './patch_rules_schema.mock'; +import { exactCheck } from '../../../exact_check'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { foldLeftRight, getPaths } from '../../../test_utils'; +import { left } from 'fp-ts/lib/Either'; + +describe('patch_rules_schema', () => { + test('made up values do not validate', () => { + const payload: PatchRulesSchema & { madeUp: string } = { + ...getPatchRulesSchemaMock(), + madeUp: 'hi', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "madeUp"']); + expect(message.schema).toEqual({}); + }); + + test('[id] does validate', () => { + const payload: PatchRulesSchema = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id] does validate', () => { + const payload: PatchRulesSchema = { + rule_id: 'rule-1', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + rule_id: 'rule-1', + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description] does validate', () => { + const payload: PatchRulesSchema = { + rule_id: 'rule-1', + description: 'some description', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + rule_id: 'rule-1', + description: 'some description', + }; + expect(message.schema).toEqual(expected); + }); + + test('[id, description] does validate', () => { + const payload: PatchRulesSchema = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + description: 'some description', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + description: 'some description', + }; + expect(message.schema).toEqual(expected); + }); + + test('[id, risk_score] does validate', () => { + const payload: PatchRulesSchema = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + risk_score: 10, + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + risk_score: 10, + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from] does validate', () => { + const payload: PatchRulesSchema = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to] does validate', () => { + const payload: PatchRulesSchema = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + }; + expect(message.schema).toEqual(expected); + }); + + test('[id, description, from, to] does validate', () => { + const payload: PatchRulesSchema = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + description: 'some description', + from: 'now-5m', + to: 'now', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + description: 'some description', + from: 'now-5m', + to: 'now', + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, name] does validate', () => { + const payload: PatchRulesSchema = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + }; + expect(message.schema).toEqual(expected); + }); + + test('[id, description, from, to, name] does validate', () => { + const payload: PatchRulesSchema = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, name, severity] does validate', () => { + const payload: PatchRulesSchema = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + }; + expect(message.schema).toEqual(expected); + }); + + test('[id, description, from, to, name, severity] does validate', () => { + const payload: PatchRulesSchema = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, name, severity, type] does validate', () => { + const payload: PatchRulesSchema = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + }; + expect(message.schema).toEqual(expected); + }); + + test('[id, description, from, to, name, severity, type] does validate', () => { + const payload: PatchRulesSchema = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, name, severity, type, interval] does validate', () => { + const payload: PatchRulesSchema = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + }; + expect(message.schema).toEqual(expected); + }); + + test('[id, description, from, to, name, severity, type, interval] does validate', () => { + const payload: PatchRulesSchema = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, query] does validate', () => { + const payload: PatchRulesSchema = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + }; + expect(message.schema).toEqual(expected); + }); + + test('[id, description, from, to, index, name, severity, interval, type, query, language] does validate', () => { + const payload: PatchRulesSchema = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, query, language] does validate', () => { + const payload: PatchRulesSchema = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + }; + expect(message.schema).toEqual(expected); + }); + + test('[id, description, from, to, index, name, severity, type, filters] does validate', () => { + const payload: PatchRulesSchema = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + filters: [], + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + filters: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, type, filters] does validate', () => { + const payload: PatchRulesSchema = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + filters: [], + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + filters: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('allows references to be sent as a valid value to patch with', () => { + const payload: PatchRulesSchema = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + references: ['index-1'], + query: 'some query', + language: 'kuery', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + references: ['index-1'], + query: 'some query', + language: 'kuery', + }; + expect(message.schema).toEqual(expected); + }); + + test('does not default references to an array', () => { + const payload: PatchRulesSchema = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as PatchRulesSchemaDecoded).references).toEqual(undefined); + }); + + test('does not default interval', () => { + const payload: PatchRulesSchema = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as PatchRulesSchemaDecoded).interval).toEqual(undefined); + }); + + test('does not default max_signals', () => { + const payload: PatchRulesSchema = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as PatchRulesSchemaDecoded).max_signals).toEqual(undefined); + }); + + test('references cannot be numbers', () => { + const payload: Omit & { references: number[] } = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + references: [5], + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to "references"']); + expect(message.schema).toEqual({}); + }); + + test('indexes cannot be numbers', () => { + const payload: Omit & { index: number[] } = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + index: [5], + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to "index"']); + expect(message.schema).toEqual({}); + }); + + test('saved_id is not required when type is saved_query and will validate without it', () => { + const payload: PatchRulesSchema = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + type: 'saved_query', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + type: 'saved_query', + }; + expect(message.schema).toEqual(expected); + }); + + test('saved_id validates with type:saved_query', () => { + const payload: PatchRulesSchema = { + ...getPatchRulesSchemaMock(), + type: 'saved_query', + saved_id: 'some id', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + ...getPatchRulesSchemaDecodedMock(), + type: 'saved_query', + saved_id: 'some id', + }; + expect(message.schema).toEqual(expected); + }); + + test('saved_query type can have filters with it', () => { + const payload: PatchRulesSchema = { + ...getPatchRulesSchemaMock(), + saved_id: 'some id', + filters: [], + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + ...getPatchRulesSchemaDecodedMock(), + saved_id: 'some id', + filters: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('language validates with kuery', () => { + const payload: PatchRulesSchema = { + ...getPatchRulesSchemaMock(), + query: 'some query', + language: 'kuery', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + ...getPatchRulesSchemaDecodedMock(), + query: 'some query', + language: 'kuery', + }; + expect(message.schema).toEqual(expected); + }); + + test('language validates with lucene', () => { + const payload: PatchRulesSchema = { + ...getPatchRulesSchemaMock(), + query: 'some query', + language: 'lucene', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const expected: PatchRulesSchemaDecoded = { + ...getPatchRulesSchemaDecodedMock(), + query: 'some query', + language: 'lucene', + }; + expect(message.schema).toEqual(expected); + }); + + test('language does not validate with something made up', () => { + const payload: Omit & { language: string } = { + ...getPatchRulesSchemaMock(), + query: 'some query', + language: 'something-made-up', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "something-made-up" supplied to "language"', + ]); + expect(message.schema).toEqual({}); + }); + + test('max_signals cannot be negative', () => { + const payload: PatchRulesSchema = { + ...getPatchRulesSchemaMock(), + query: 'some query', + max_signals: -1, + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "-1" supplied to "max_signals"', + ]); + expect(message.schema).toEqual({}); + }); + + test('max_signals cannot be zero', () => { + const payload: PatchRulesSchema = { + ...getPatchRulesSchemaMock(), + query: 'some query', + max_signals: 0, + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "0" supplied to "max_signals"']); + expect(message.schema).toEqual({}); + }); + + test('max_signals can be 1', () => { + const payload: PatchRulesSchema = { + ...getPatchRulesSchemaMock(), + query: 'some query', + max_signals: 1, + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + ...getPatchRulesSchemaDecodedMock(), + query: 'some query', + max_signals: 1, + }; + expect(message.schema).toEqual(expected); + }); + + test('meta can be patched', () => { + const payload: PatchRulesSchema = { + ...getPatchRulesSchemaMock(), + meta: { whateverYouWant: 'anything_at_all' }, + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + ...getPatchRulesSchemaDecodedMock(), + meta: { whateverYouWant: 'anything_at_all' }, + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot patch meta as a string', () => { + const payload: Omit & { meta: string } = { + ...getPatchRulesSchemaMock(), + meta: 'should not work', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "should not work" supplied to "meta"', + ]); + expect(message.schema).toEqual({}); + }); + + test('filters cannot be a string', () => { + const payload: Omit & { filters: string } = { + ...getPatchRulesSchemaMock(), + filters: 'should not work', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "should not work" supplied to "filters"', + ]); + expect(message.schema).toEqual({}); + }); + + test('threat is not defaulted to empty array on patch', () => { + const payload: PatchRulesSchema = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as PatchRulesSchemaDecoded).threat).toEqual(undefined); + }); + + test('threat is not defaulted to undefined on patch with empty array', () => { + const payload: PatchRulesSchema = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + threat: [], + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect((message.schema as PatchRulesSchemaDecoded).threat).toEqual([]); + }); + + test('threat is valid when updated with all sub-objects', () => { + const threat: PatchRulesSchema['threat'] = [ + { + framework: 'fake', + tactic: { + id: 'fakeId', + name: 'fakeName', + reference: 'fakeRef', + }, + technique: [ + { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + ], + }, + ]; + const payload: PatchRulesSchema = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + threat, + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('threat is invalid when updated with missing property framework', () => { + const threat: Omit = [ + { + tactic: { + id: 'fakeId', + name: 'fakeName', + reference: 'fakeRef', + }, + technique: [ + { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + ], + }, + ]; + const payload: Omit = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + threat, + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "threat,framework"', + ]); + expect(message.schema).toEqual({}); + }); + + test('threat is invalid when updated with missing tactic sub-object', () => { + const threat: Omit = [ + { + framework: 'fake', + technique: [ + { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + ], + }, + ]; + + const payload: Omit = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + threat, + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "threat,tactic"', + ]); + expect(message.schema).toEqual({}); + }); + + test('threat is invalid when updated with missing technique', () => { + const threat: Omit = [ + { + framework: 'fake', + tactic: { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + }, + ]; + + const payload: Omit = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + threat, + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "threat,technique"', + ]); + expect(message.schema).toEqual({}); + }); + + test('validates with timeline_id and timeline_title', () => { + const payload: PatchRulesSchema = { + ...getPatchRulesSchemaMock(), + timeline_id: 'some-id', + timeline_title: 'some-title', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + ...getPatchRulesSchemaDecodedMock(), + timeline_id: 'some-id', + timeline_title: 'some-title', + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot set the severity to a value other than low, medium, high, or critical', () => { + const payload: Omit & { severity: string } = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + severity: 'junk', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "junk" supplied to "severity"']); + expect(message.schema).toEqual({}); + }); + + describe('note', () => { + test('[rule_id, description, from, to, index, name, severity, interval, type, note] does validate', () => { + const payload: PatchRulesSchema = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + note: '# some documentation markdown', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + note: '# some documentation markdown', + }; + expect(message.schema).toEqual(expected); + }); + + test('note can be patched', () => { + const payload: PatchRulesSchema = { + rule_id: 'rule-1', + note: '# new documentation markdown', + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: PatchRulesSchemaDecoded = { + rule_id: 'rule-1', + note: '# new documentation markdown', + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot patch note as an object', () => { + const payload: Omit & { note: object } = { + id: 'b8f95e17-681f-407f-8a5e-b832a77d3831', + note: { + someProperty: 'something else here', + }, + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + // TODO: Change the formatter to output something more readable than [object Object] + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "[object Object]" supplied to "note"', + ]); + expect(message.schema).toEqual({}); + }); + }); + + test('You cannot send in an array of actions that are missing "group"', () => { + const payload: Omit = { + ...getPatchRulesSchemaMock(), + actions: [{ id: 'id', action_type_id: 'action_type_id', params: {} }], + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "actions,group"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are missing "id"', () => { + const payload: Omit = { + ...getPatchRulesSchemaMock(), + actions: [{ group: 'group', action_type_id: 'action_type_id', params: {} }], + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "actions,id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are missing "params"', () => { + const payload: Omit = { + ...getPatchRulesSchemaMock(), + actions: [{ group: 'group', id: 'id', action_type_id: 'action_type_id' }], + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "actions,params"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are including "actionTypeId"', () => { + const payload: Omit = { + ...getPatchRulesSchemaMock(), + actions: [ + { + group: 'group', + id: 'id', + actionTypeId: 'actionTypeId', + params: {}, + }, + ], + }; + + const decoded = patchRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "actions,action_type_id"', + ]); + expect(message.schema).toEqual({}); + }); + + // TODO: The exception_list tests are skipped and empty until we re-integrate it from the lists plugin + describe.skip('exception_list', () => { + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and exceptions_list] does validate', () => {}); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and empty exceptions_list] does validate', () => {}); + + test('rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and invalid exceptions_list] does NOT validate', () => {}); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and non-existent exceptions_list] does validate with empty exceptions_list', () => {}); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_schema.ts new file mode 100644 index 0000000000000..605e0272bbb4c --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_schema.ts @@ -0,0 +1,90 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; + +/* eslint-disable @typescript-eslint/camelcase */ +import { + description, + anomaly_threshold, + filters, + index, + output_index, + saved_id, + timeline_id, + timeline_title, + meta, + machine_learning_job_id, + risk_score, + rule_id, + name, + severity, + type, + note, + version, + actions, + false_positives, + interval, + max_signals, + from, + enabled, + tags, + threat, + throttle, + references, + to, + language, + listAndOrUndefined, + query, + id, +} from '../common/schemas'; +/* eslint-enable @typescript-eslint/camelcase */ + +/** + * All of the patch elements should default to undefined if not set + */ +export const patchRulesSchema = t.exact( + t.partial({ + description, + risk_score, + name, + severity, + type, + id, + actions, + anomaly_threshold, + enabled, + false_positives, + filters, + from, + rule_id, + index, + interval, + query, + language, + // TODO: output_index: This should be removed eventually + output_index, + saved_id, + timeline_id, + timeline_title, + meta, + machine_learning_job_id, + max_signals, + tags, + to, + threat, + throttle, + references, + note, + version, + exceptions_list: listAndOrUndefined, + }) +); + +export type PatchRulesSchema = t.TypeOf; + +// This type is used after a decode since some things are defaults after a decode. +export type PatchRulesSchemaDecoded = PatchRulesSchema; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_type_dependents.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_type_dependents.ts new file mode 100644 index 0000000000000..554cdb822762f --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/patch_rules_type_dependents.ts @@ -0,0 +1,77 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { PatchRulesSchema } from './patch_rules_schema'; + +export const validateQuery = (rule: PatchRulesSchema): string[] => { + if (rule.type === 'machine_learning') { + if (rule.query != null) { + return ['when "type" is "machine_learning", "query" cannot be set']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateLanguage = (rule: PatchRulesSchema): string[] => { + if (rule.type === 'machine_learning') { + if (rule.language != null) { + return ['when "type" is "machine_learning", "language" cannot be set']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateTimelineId = (rule: PatchRulesSchema): string[] => { + if (rule.timeline_id != null) { + if (rule.timeline_title == null) { + return ['when "timeline_id" exists, "timeline_title" must also exist']; + } else if (rule.timeline_id === '') { + return ['"timeline_id" cannot be an empty string']; + } else { + return []; + } + } + return []; +}; + +export const validateTimelineTitle = (rule: PatchRulesSchema): string[] => { + if (rule.timeline_title != null) { + if (rule.timeline_id == null) { + return ['when "timeline_title" exists, "timeline_id" must also exist']; + } else if (rule.timeline_title === '') { + return ['"timeline_title" cannot be an empty string']; + } else { + return []; + } + } + return []; +}; + +export const validateId = (rule: PatchRulesSchema): string[] => { + if (rule.id != null && rule.rule_id != null) { + return ['both "id" and "rule_id" cannot exist, choose one or the other']; + } else if (rule.id == null && rule.rule_id == null) { + return ['either "id" or "rule_id" must be set']; + } else { + return []; + } +}; + +export const patchRuleValidateTypeDependents = (schema: PatchRulesSchema): string[] => { + return [ + ...validateId(schema), + ...validateQuery(schema), + ...validateLanguage(schema), + ...validateTimelineId(schema), + ...validateTimelineTitle(schema), + ]; +}; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_bulk_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_bulk_schema.test.ts new file mode 100644 index 0000000000000..4728f7dd84cbd --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_bulk_schema.test.ts @@ -0,0 +1,103 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { queryRulesBulkSchema, QueryRulesBulkSchema } from './query_rules_bulk_schema'; +import { exactCheck } from '../../../exact_check'; +import { foldLeftRight } from '../../../test_utils'; +import { formatErrors } from '../../../format_errors'; + +// only the basics of testing are here. +// see: query_rules_schema.test.ts for the bulk of the validation tests +// this just wraps queryRulesSchema in an array +describe('query_rules_bulk_schema', () => { + test('can take an empty array and validate it', () => { + const payload: QueryRulesBulkSchema = []; + + const decoded = queryRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect(output.schema).toEqual([]); + }); + + test('non uuid being supplied to id does not validate', () => { + const payload: QueryRulesBulkSchema = [ + { + id: '1', + }, + ]; + + const decoded = queryRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual(['Invalid value "1" supplied to "id"']); + expect(output.schema).toEqual({}); + }); + + test('both rule_id and id being supplied do validate', () => { + const payload: QueryRulesBulkSchema = [ + { + rule_id: '1', + id: 'c1e1b359-7ac1-4e96-bc81-c683c092436f', + }, + ]; + + const decoded = queryRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect(output.schema).toEqual(payload); + }); + + test('only id validates with two elements', () => { + const payload: QueryRulesBulkSchema = [ + { id: 'c1e1b359-7ac1-4e96-bc81-c683c092436f' }, + { id: 'c1e1b359-7ac1-4e96-bc81-c683c092436f' }, + ]; + + const decoded = queryRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect(output.schema).toEqual(payload); + }); + + test('only rule_id validates', () => { + const payload: QueryRulesBulkSchema = [{ rule_id: 'c1e1b359-7ac1-4e96-bc81-c683c092436f' }]; + + const decoded = queryRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect(output.schema).toEqual(payload); + }); + + test('only rule_id validates with two elements', () => { + const payload: QueryRulesBulkSchema = [ + { rule_id: 'c1e1b359-7ac1-4e96-bc81-c683c092436f' }, + { rule_id: '2' }, + ]; + + const decoded = queryRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect(output.schema).toEqual(payload); + }); + + test('both id and rule_id validates with two separate elements', () => { + const payload: QueryRulesBulkSchema = [ + { id: 'c1e1b359-7ac1-4e96-bc81-c683c092436f' }, + { rule_id: '2' }, + ]; + + const decoded = queryRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect(output.schema).toEqual(payload); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_bulk_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_bulk_schema.ts new file mode 100644 index 0000000000000..a5611bdc2f12f --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_bulk_schema.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; + +import { queryRulesSchema, QueryRulesSchemaDecoded } from './query_rules_schema'; + +export const queryRulesBulkSchema = t.array(queryRulesSchema); +export type QueryRulesBulkSchema = t.TypeOf; + +export type QueryRulesBulkSchemaDecoded = QueryRulesSchemaDecoded[]; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_schema.test.ts new file mode 100644 index 0000000000000..c9cb6f310961a --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_schema.test.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { queryRulesSchema, QueryRulesSchema } from './query_rules_schema'; +import { exactCheck } from '../../../exact_check'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { foldLeftRight, getPaths } from '../../../test_utils'; +import { left } from 'fp-ts/lib/Either'; + +describe('query_rules_schema', () => { + test('empty objects do validate', () => { + const payload: Partial = {}; + + const decoded = queryRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/query_rules_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_schema.ts similarity index 54% rename from x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/query_rules_schema.ts rename to x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_schema.ts index 86a731699d1ea..cb8f21128b052 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/query_rules_schema.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_schema.ts @@ -4,13 +4,18 @@ * you may not use this file except in compliance with the Elastic License. */ -import Joi from 'joi'; +import * as t from 'io-ts'; /* eslint-disable @typescript-eslint/camelcase */ -import { rule_id, id } from './schemas'; +import { rule_id, id } from '../common/schemas'; /* eslint-enable @typescript-eslint/camelcase */ -export const queryRulesSchema = Joi.object({ - rule_id, - id, -}).xor('id', 'rule_id'); +export const queryRulesSchema = t.exact( + t.partial({ + rule_id, + id, + }) +); + +export type QueryRulesSchema = t.TypeOf; +export type QueryRulesSchemaDecoded = QueryRulesSchema; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_type_dependents.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_type_dependents.test.ts new file mode 100644 index 0000000000000..ad7f368d4eede --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_type_dependents.test.ts @@ -0,0 +1,25 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { QueryRulesSchema } from './query_rules_schema'; +import { queryRuleValidateTypeDependents } from './query_rules_type_dependents'; + +describe('query_rules_type_dependents', () => { + test('You cannot have both an id and a rule_id', () => { + const schema: QueryRulesSchema = { + id: 'some-id', + rule_id: 'some-rule-id', + }; + const errors = queryRuleValidateTypeDependents(schema); + expect(errors).toEqual(['both "id" and "rule_id" cannot exist, choose one or the other']); + }); + + test('You must set either an id or a rule_id', () => { + const schema: QueryRulesSchema = {}; + const errors = queryRuleValidateTypeDependents(schema); + expect(errors).toEqual(['either "id" or "rule_id" must be set']); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_type_dependents.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_type_dependents.ts new file mode 100644 index 0000000000000..f3e602dff0f06 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_rules_type_dependents.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { QueryRulesSchema } from './query_rules_schema'; + +export const validateId = (rule: QueryRulesSchema): string[] => { + if (rule.id != null && rule.rule_id != null) { + return ['both "id" and "rule_id" cannot exist, choose one or the other']; + } else if (rule.id == null && rule.rule_id == null) { + return ['either "id" or "rule_id" must be set']; + } else { + return []; + } +}; + +export const queryRuleValidateTypeDependents = (schema: QueryRulesSchema): string[] => { + return [...validateId(schema)]; +}; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_signals_index_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_signals_index_schema.test.ts new file mode 100644 index 0000000000000..23e5fa7e721b0 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_signals_index_schema.test.ts @@ -0,0 +1,94 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { QuerySignalsSchema, querySignalsSchema } from './query_signals_index_schema'; +import { exactCheck } from '../../../exact_check'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { foldLeftRight, getPaths } from '../../../test_utils'; +import { left } from 'fp-ts/lib/Either'; + +describe('query, aggs, size, _source and track_total_hits on signals index', () => { + test('query, aggs, size, _source and track_total_hits simultaneously', () => { + const payload: QuerySignalsSchema = { + query: {}, + aggs: {}, + size: 1, + track_total_hits: true, + _source: ['field'], + }; + + const decoded = querySignalsSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('query, only', () => { + const payload: QuerySignalsSchema = { + query: {}, + }; + + const decoded = querySignalsSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('aggs only', () => { + const payload: QuerySignalsSchema = { + aggs: {}, + }; + + const decoded = querySignalsSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('size only', () => { + const payload: QuerySignalsSchema = { + size: 1, + }; + + const decoded = querySignalsSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('track_total_hits only', () => { + const payload: QuerySignalsSchema = { + track_total_hits: true, + }; + + const decoded = querySignalsSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('_source only', () => { + const payload: QuerySignalsSchema = { + _source: ['field'], + }; + + const decoded = querySignalsSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_signals_index_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_signals_index_schema.ts new file mode 100644 index 0000000000000..3a050c9208f77 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/query_signals_index_schema.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { PositiveIntegerGreaterThanZero } from '../types/positive_integer_greater_than_zero'; + +export const querySignalsSchema = t.exact( + t.partial({ + query: t.object, + aggs: t.object, + size: PositiveIntegerGreaterThanZero, + track_total_hits: t.boolean, + _source: t.array(t.string), + }) +); + +export type QuerySignalsSchema = t.TypeOf; +export type QuerySignalsSchemaDecoded = QuerySignalsSchema; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/set_signal_status_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/set_signal_status_schema.test.ts new file mode 100644 index 0000000000000..dc889892ba83e --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/set_signal_status_schema.test.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { setSignalsStatusSchema, SetSignalsStatusSchema } from './set_signal_status_schema'; +import { exactCheck } from '../../../exact_check'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { foldLeftRight, getPaths } from '../../../test_utils'; +import { left } from 'fp-ts/lib/Either'; + +describe('set signal status schema', () => { + test('signal_ids and status is valid', () => { + const payload: SetSignalsStatusSchema = { + signal_ids: ['somefakeid'], + status: 'open', + }; + + const decoded = setSignalsStatusSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('query and status is valid', () => { + const payload: SetSignalsStatusSchema = { + query: {}, + status: 'open', + }; + + const decoded = setSignalsStatusSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('signal_ids and missing status is invalid', () => { + const payload: Omit = { + signal_ids: ['somefakeid'], + }; + + const decoded = setSignalsStatusSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "status"', + ]); + expect(message.schema).toEqual({}); + }); + + test('query and missing status is invalid', () => { + const payload: Omit = { + query: {}, + }; + + const decoded = setSignalsStatusSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "status"', + ]); + expect(message.schema).toEqual({}); + }); + + test('signal_ids is present but status has wrong value', () => { + const payload: Omit & { status: 'fakeVal' } = { + query: {}, + status: 'fakeVal', + }; + + const decoded = setSignalsStatusSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "fakeVal" supplied to "status"', + ]); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/set_signal_status_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/set_signal_status_schema.ts new file mode 100644 index 0000000000000..0e922aeaf8cdf --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/set_signal_status_schema.ts @@ -0,0 +1,24 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; + +/* eslint-disable @typescript-eslint/camelcase */ +import { signal_ids, signal_status_query, status } from '../common/schemas'; +/* eslint-enable @typescript-eslint/camelcase */ + +export const setSignalsStatusSchema = t.intersection([ + t.type({ + status, + }), + t.partial({ + signal_ids, + query: signal_status_query, + }), +]); + +export type SetSignalsStatusSchema = t.TypeOf; +export type SetSignalsStatusSchemaDecoded = SetSignalsStatusSchema; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/set_signal_status_type_dependents.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/set_signal_status_type_dependents.test.ts new file mode 100644 index 0000000000000..b79af2fef5c97 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/set_signal_status_type_dependents.test.ts @@ -0,0 +1,46 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { setSignalStatusValidateTypeDependents } from './set_signal_status_type_dependents'; +import { SetSignalsStatusSchema } from './set_signal_status_schema'; + +describe('update_rules_type_dependents', () => { + test('You can have just a "signals_id"', () => { + const schema: SetSignalsStatusSchema = { + status: 'open', + signal_ids: ['some-id'], + }; + const errors = setSignalStatusValidateTypeDependents(schema); + expect(errors).toEqual([]); + }); + + test('You can have just a "query"', () => { + const schema: SetSignalsStatusSchema = { + status: 'open', + query: {}, + }; + const errors = setSignalStatusValidateTypeDependents(schema); + expect(errors).toEqual([]); + }); + + test('You cannot have both a "signals_id" and a "query"', () => { + const schema: SetSignalsStatusSchema = { + status: 'open', + query: {}, + signal_ids: ['some-id'], + }; + const errors = setSignalStatusValidateTypeDependents(schema); + expect(errors).toEqual(['both "signal_ids" and "query" cannot exist, choose one or the other']); + }); + + test('You must set either an "signals_id" and a "query"', () => { + const schema: SetSignalsStatusSchema = { + status: 'open', + }; + const errors = setSignalStatusValidateTypeDependents(schema); + expect(errors).toEqual(['either "signal_ids" or "query" must be set']); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/set_signal_status_type_dependents.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/set_signal_status_type_dependents.ts new file mode 100644 index 0000000000000..c495860fa72bf --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/set_signal_status_type_dependents.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { SetSignalsStatusSchema } from './set_signal_status_schema'; + +export const validateId = (signalStatus: SetSignalsStatusSchema): string[] => { + if (signalStatus.signal_ids != null && signalStatus.query != null) { + return ['both "signal_ids" and "query" cannot exist, choose one or the other']; + } else if (signalStatus.signal_ids == null && signalStatus.query == null) { + return ['either "signal_ids" or "query" must be set']; + } else { + return []; + } +}; + +export const setSignalStatusValidateTypeDependents = (schema: SetSignalsStatusSchema): string[] => { + return [...validateId(schema)]; +}; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_bulk_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_bulk_schema.test.ts new file mode 100644 index 0000000000000..edc652ce3b3f4 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_bulk_schema.test.ts @@ -0,0 +1,277 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { updateRulesBulkSchema, UpdateRulesBulkSchema } from './update_rules_bulk_schema'; +import { exactCheck } from '../../../exact_check'; +import { foldLeftRight } from '../../../test_utils'; +import { formatErrors } from '../../../format_errors'; +import { + getUpdateRulesSchemaMock, + getUpdateRulesSchemaDecodedMock, +} from './update_rules_schema.mock'; +import { UpdateRulesSchema } from './update_rules_schema'; + +// only the basics of testing are here. +// see: update_rules_schema.test.ts for the bulk of the validation tests +// this just wraps updateRulesSchema in an array +describe('update_rules_bulk_schema', () => { + test('can take an empty array and validate it', () => { + const payload: UpdateRulesBulkSchema = []; + + const decoded = updateRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(output.errors).toEqual([]); + expect(output.schema).toEqual([]); + }); + + test('made up values do not validate for a single element', () => { + const payload: Array<{ madeUp: string }> = [{ madeUp: 'hi' }]; + + const decoded = updateRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([ + 'Invalid value "undefined" supplied to "description"', + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(output.schema).toEqual({}); + }); + + test('single array element does validate', () => { + const payload: UpdateRulesBulkSchema = [getUpdateRulesSchemaMock()]; + + const decoded = updateRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect(output.schema).toEqual([getUpdateRulesSchemaDecodedMock()]); + }); + + test('two array elements do validate', () => { + const payload: UpdateRulesBulkSchema = [getUpdateRulesSchemaMock(), getUpdateRulesSchemaMock()]; + + const decoded = updateRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect(output.schema).toEqual([ + getUpdateRulesSchemaDecodedMock(), + getUpdateRulesSchemaDecodedMock(), + ]); + }); + + test('single array element with a missing value (risk_score) will not validate', () => { + const singleItem = getUpdateRulesSchemaMock(); + delete singleItem.risk_score; + const payload: UpdateRulesBulkSchema = [singleItem]; + + const decoded = updateRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(output.schema).toEqual({}); + }); + + test('two array elements where the first is valid but the second is invalid (risk_score) will not validate', () => { + const singleItem = getUpdateRulesSchemaMock(); + const secondItem = getUpdateRulesSchemaMock(); + delete secondItem.risk_score; + const payload: UpdateRulesBulkSchema = [singleItem, secondItem]; + + const decoded = updateRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(output.schema).toEqual({}); + }); + + test('two array elements where the first is invalid (risk_score) but the second is valid will not validate', () => { + const singleItem = getUpdateRulesSchemaMock(); + const secondItem = getUpdateRulesSchemaMock(); + delete singleItem.risk_score; + const payload: UpdateRulesBulkSchema = [singleItem, secondItem]; + + const decoded = updateRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(output.schema).toEqual({}); + }); + + test('two array elements where both are invalid (risk_score) will not validate', () => { + const singleItem = getUpdateRulesSchemaMock(); + const secondItem = getUpdateRulesSchemaMock(); + delete singleItem.risk_score; + delete secondItem.risk_score; + const payload: UpdateRulesBulkSchema = [singleItem, secondItem]; + + const decoded = updateRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(output.schema).toEqual({}); + }); + + test('two array elements where the first is invalid (extra key and value) but the second is valid will not validate', () => { + const singleItem: UpdateRulesSchema & { madeUpValue: string } = { + ...getUpdateRulesSchemaMock(), + madeUpValue: 'something', + }; + const secondItem = getUpdateRulesSchemaMock(); + const payload: UpdateRulesBulkSchema = [singleItem, secondItem]; + + const decoded = updateRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual(['invalid keys "madeUpValue"']); + expect(output.schema).toEqual({}); + }); + + test('two array elements where the second is invalid (extra key and value) but the first is valid will not validate', () => { + const singleItem: UpdateRulesSchema = getUpdateRulesSchemaMock(); + const secondItem: UpdateRulesSchema & { madeUpValue: string } = { + ...getUpdateRulesSchemaMock(), + madeUpValue: 'something', + }; + const payload: UpdateRulesBulkSchema = [singleItem, secondItem]; + + const decoded = updateRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual(['invalid keys "madeUpValue"']); + expect(output.schema).toEqual({}); + }); + + test('two array elements where both are invalid (extra key and value) will not validate', () => { + const singleItem: UpdateRulesSchema & { madeUpValue: string } = { + ...getUpdateRulesSchemaMock(), + madeUpValue: 'something', + }; + const secondItem: UpdateRulesSchema & { madeUpValue: string } = { + ...getUpdateRulesSchemaMock(), + madeUpValue: 'something', + }; + const payload: UpdateRulesBulkSchema = [singleItem, secondItem]; + + const decoded = updateRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual(['invalid keys "madeUpValue,madeUpValue"']); + expect(output.schema).toEqual({}); + }); + + test('The default for "from" will be "now-6m"', () => { + const { from, ...withoutFrom } = getUpdateRulesSchemaMock(); + const payload: UpdateRulesBulkSchema = [withoutFrom]; + + const decoded = updateRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect((output.schema as UpdateRulesBulkSchema)[0].from).toEqual('now-6m'); + }); + + test('The default for "to" will be "now"', () => { + const { to, ...withoutTo } = getUpdateRulesSchemaMock(); + const payload: UpdateRulesBulkSchema = [withoutTo]; + + const decoded = updateRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect((output.schema as UpdateRulesBulkSchema)[0].to).toEqual('now'); + }); + + test('You cannot set the severity to a value other than low, medium, high, or critical', () => { + const badSeverity = { ...getUpdateRulesSchemaMock(), severity: 'madeup' }; + const payload = [badSeverity]; + + const decoded = updateRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual(['Invalid value "madeup" supplied to "severity"']); + expect(output.schema).toEqual({}); + }); + + test('You can set "note" to a string', () => { + const payload: UpdateRulesBulkSchema = [ + { ...getUpdateRulesSchemaMock(), note: '# test markdown' }, + ]; + + const decoded = updateRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect(output.schema).toEqual([ + { ...getUpdateRulesSchemaDecodedMock(), note: '# test markdown' }, + ]); + }); + + test('You can set "note" to an empty string', () => { + const payload: UpdateRulesBulkSchema = [{ ...getUpdateRulesSchemaMock(), note: '' }]; + + const decoded = updateRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect(output.schema).toEqual([{ ...getUpdateRulesSchemaDecodedMock(), note: '' }]); + }); + + test('You can set "note" to anything other than string', () => { + const payload = [ + { + ...getUpdateRulesSchemaMock(), + note: { + something: 'some object', + }, + }, + ]; + + const decoded = updateRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + // TODO: We should change the formatter used to better print objects + expect(formatErrors(output.errors)).toEqual([ + 'Invalid value "[object Object]" supplied to "note"', + ]); + expect(output.schema).toEqual({}); + }); + + test('The default for "actions" will be an empty array', () => { + const { actions, ...withoutActions } = getUpdateRulesSchemaMock(); + const payload: UpdateRulesBulkSchema = [withoutActions]; + + const decoded = updateRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect((output.schema as UpdateRulesBulkSchema)[0].actions).toEqual([]); + }); + + test('The default for "throttle" will be null', () => { + const { throttle, ...withoutThrottle } = getUpdateRulesSchemaMock(); + const payload: UpdateRulesBulkSchema = [withoutThrottle]; + + const decoded = updateRulesBulkSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const output = foldLeftRight(checked); + expect(formatErrors(output.errors)).toEqual([]); + expect((output.schema as UpdateRulesBulkSchema)[0].throttle).toEqual(null); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_bulk_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_bulk_schema.ts new file mode 100644 index 0000000000000..429103c7df13e --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_bulk_schema.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; + +import { updateRulesSchema, UpdateRulesSchemaDecoded } from './update_rules_schema'; + +export const updateRulesBulkSchema = t.array(updateRulesSchema); +export type UpdateRulesBulkSchema = t.TypeOf; + +export type UpdateRulesBulkSchemaDecoded = UpdateRulesSchemaDecoded[]; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_schema.mock.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_schema.mock.ts new file mode 100644 index 0000000000000..b8a99115ba7d5 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_schema.mock.ts @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { UpdateRulesSchema, UpdateRulesSchemaDecoded } from './update_rules_schema'; +import { DEFAULT_MAX_SIGNALS } from '../../../constants'; + +export const getUpdateRulesSchemaMock = (): UpdateRulesSchema => ({ + description: 'some description', + name: 'Query with a rule id', + query: 'user.name: root or user.name: admin', + severity: 'high', + type: 'query', + risk_score: 55, + language: 'kuery', + rule_id: 'rule-1', +}); + +export const getUpdateRulesSchemaDecodedMock = (): UpdateRulesSchemaDecoded => ({ + description: 'some description', + name: 'Query with a rule id', + query: 'user.name: root or user.name: admin', + severity: 'high', + type: 'query', + risk_score: 55, + language: 'kuery', + references: [], + actions: [], + enabled: true, + false_positives: [], + from: 'now-6m', + interval: '5m', + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + to: 'now', + threat: [], + throttle: null, + exceptions_list: [], + rule_id: 'rule-1', +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_schema.test.ts new file mode 100644 index 0000000000000..e60522e1964f4 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_schema.test.ts @@ -0,0 +1,1387 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + updateRulesSchema, + UpdateRulesSchema, + UpdateRulesSchemaDecoded, +} from './update_rules_schema'; +import { exactCheck } from '../../../exact_check'; +import { foldLeftRight, getPaths } from '../../../test_utils'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { + getUpdateRulesSchemaMock, + getUpdateRulesSchemaDecodedMock, +} from './update_rules_schema.mock'; +import { DEFAULT_MAX_SIGNALS } from '../../../constants'; + +describe('update rules schema', () => { + test('empty objects do not validate', () => { + const payload: Partial = {}; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "description"', + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('made up values do not validate', () => { + const payload: UpdateRulesSchema & { madeUp: string } = { + ...getUpdateRulesSchemaMock(), + madeUp: 'hi', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "madeUp"']); + expect(message.schema).toEqual({}); + }); + + test('[rule_id] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "description"', + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "name"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "severity"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + 'Invalid value "undefined" supplied to "type"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity, type] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity, type, interval] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity, type, interval, index] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + interval: '5m', + index: ['index-1'], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, name, severity, type, query, index, interval] does validate', () => { + const payload: UpdateRulesSchema = { + rule_id: 'rule-1', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + query: 'some query', + index: ['index-1'], + interval: '5m', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + rule_id: 'rule-1', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + name: 'some-name', + severity: 'low', + type: 'query', + query: 'some query', + index: ['index-1'], + interval: '5m', + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, query, language] does not validate', () => { + const payload: Partial = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "risk_score"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, query, language, risk_score] does validate', () => { + const payload: UpdateRulesSchema = { + rule_id: 'rule-1', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + rule_id: 'rule-1', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, query, language, risk_score, output_index] does validate', () => { + const payload: UpdateRulesSchema = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + query: 'some query', + language: 'kuery', + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score] does validate', () => { + const payload: UpdateRulesSchema = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + risk_score: 50, + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + risk_score: 50, + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, output_index] does validate', () => { + const payload: UpdateRulesSchema = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('You can send in an empty array to threat', () => { + const payload: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + threat: [], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + ...getUpdateRulesSchemaDecodedMock(), + threat: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, output_index, threat] does validate', () => { + const payload: UpdateRulesSchema = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + threat: [ + { + framework: 'someFramework', + tactic: { + id: 'fakeId', + name: 'fakeName', + reference: 'fakeRef', + }, + technique: [ + { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + ], + }, + ], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + rule_id: 'rule-1', + output_index: '.siem-signals', + risk_score: 50, + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + threat: [ + { + framework: 'someFramework', + tactic: { + id: 'fakeId', + name: 'fakeName', + reference: 'fakeRef', + }, + technique: [ + { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + ], + }, + ], + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + throttle: null, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('allows references to be sent as valid', () => { + const payload: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + references: ['index-1'], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + ...getUpdateRulesSchemaDecodedMock(), + references: ['index-1'], + }; + expect(message.schema).toEqual(expected); + }); + + test('defaults references to an array if it is not sent in', () => { + const { references, ...noReferences } = getUpdateRulesSchemaMock(); + const decoded = updateRulesSchema.decode(noReferences); + const checked = exactCheck(noReferences, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + ...getUpdateRulesSchemaDecodedMock(), + references: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('references cannot be numbers', () => { + const payload: Omit & { references: number[] } = { + ...getUpdateRulesSchemaMock(), + references: [5], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('indexes cannot be numbers', () => { + const payload: Omit & { index: number[] } = { + ...getUpdateRulesSchemaMock(), + index: [5], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to "index"']); + expect(message.schema).toEqual({}); + }); + + test('defaults interval to 5 min', () => { + const { interval, ...noInterval } = getUpdateRulesSchemaMock(); + const payload: UpdateRulesSchema = { + ...noInterval, + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { interval: expectedInterval, ...expectedNoInterval } = getUpdateRulesSchemaDecodedMock(); + const expected: UpdateRulesSchemaDecoded = { + ...expectedNoInterval, + interval: '5m', + }; + expect(message.schema).toEqual(expected); + }); + + test('defaults max signals to 100', () => { + const { max_signals, ...noMaxSignals } = getUpdateRulesSchemaMock(); + const payload: UpdateRulesSchema = { + ...noMaxSignals, + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { + max_signals: expectedMaxSignals, + ...expectedNoMaxSignals + } = getUpdateRulesSchemaDecodedMock(); + const expected: UpdateRulesSchemaDecoded = { + ...expectedNoMaxSignals, + max_signals: 100, + }; + expect(message.schema).toEqual(expected); + }); + + test('saved_query type can have filters with it', () => { + const payload: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + filters: [], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + ...getUpdateRulesSchemaDecodedMock(), + filters: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('filters cannot be a string', () => { + const payload: Omit & { filters: string } = { + ...getUpdateRulesSchemaMock(), + filters: 'some string', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "some string" supplied to "filters"', + ]); + expect(message.schema).toEqual({}); + }); + + test('language validates with kuery', () => { + const payload: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + language: 'kuery', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + ...getUpdateRulesSchemaDecodedMock(), + language: 'kuery', + }; + expect(message.schema).toEqual(expected); + }); + + test('language validates with lucene', () => { + const payload: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + language: 'lucene', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + ...getUpdateRulesSchemaDecodedMock(), + language: 'lucene', + }; + expect(message.schema).toEqual(expected); + }); + + test('language does not validate with something made up', () => { + const payload: Omit & { language: string } = { + ...getUpdateRulesSchemaMock(), + language: 'something-made-up', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "something-made-up" supplied to "language"', + ]); + expect(message.schema).toEqual({}); + }); + + test('max_signals cannot be negative', () => { + const payload: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + max_signals: -1, + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "-1" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('max_signals cannot be zero', () => { + const payload: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + max_signals: 0, + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "0" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('max_signals can be 1', () => { + const payload: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + max_signals: 1, + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + ...getUpdateRulesSchemaDecodedMock(), + max_signals: 1, + }; + expect(message.schema).toEqual(expected); + }); + + test('You can optionally send in an array of tags', () => { + const payload: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + tags: ['tag_1', 'tag_2'], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + ...getUpdateRulesSchemaDecodedMock(), + tags: ['tag_1', 'tag_2'], + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot send in an array of tags that are numbers', () => { + const payload: Omit & { tags: number[] } = { + ...getUpdateRulesSchemaMock(), + tags: [0, 1, 2], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "0" supplied to ""', + 'Invalid value "1" supplied to ""', + 'Invalid value "2" supplied to ""', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of threat that are missing "framework"', () => { + const payload: Omit & { + threat: Array>>; + } = { + ...getUpdateRulesSchemaMock(), + threat: [ + { + tactic: { + id: 'fakeId', + name: 'fakeName', + reference: 'fakeRef', + }, + technique: [ + { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + ], + }, + ], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "framework"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of threat that are missing "tactic"', () => { + const payload: Omit & { + threat: Array>>; + } = { + ...getUpdateRulesSchemaMock(), + threat: [ + { + framework: 'fake', + technique: [ + { + id: 'techniqueId', + name: 'techniqueName', + reference: 'techniqueRef', + }, + ], + }, + ], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "tactic"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of threat that are missing "technique"', () => { + const payload: Omit & { + threat: Array>>; + } = { + ...getUpdateRulesSchemaMock(), + threat: [ + { + framework: 'fake', + tactic: { + id: 'fakeId', + name: 'fakeName', + reference: 'fakeRef', + }, + }, + ], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "technique"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You can optionally send in an array of false positives', () => { + const payload: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + false_positives: ['false_1', 'false_2'], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + ...getUpdateRulesSchemaDecodedMock(), + false_positives: ['false_1', 'false_2'], + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot send in an array of false positives that are numbers', () => { + const payload: Omit & { false_positives: number[] } = { + ...getUpdateRulesSchemaMock(), + false_positives: [5, 4], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "5" supplied to ""', + 'Invalid value "4" supplied to ""', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot set the immutable to a number when trying to update a rule', () => { + const payload: Omit & { immutable: number } = { + ...getUpdateRulesSchemaMock(), + immutable: 5, + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "immutable"']); + expect(message.schema).toEqual({}); + }); + + test('You cannot set the risk_score to 101', () => { + const payload: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + risk_score: 101, + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "101" supplied to "risk_score"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot set the risk_score to -1', () => { + const payload: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + risk_score: -1, + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "-1" supplied to "risk_score"']); + expect(message.schema).toEqual({}); + }); + + test('You can set the risk_score to 0', () => { + const payload: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + risk_score: 0, + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + ...getUpdateRulesSchemaDecodedMock(), + risk_score: 0, + }; + expect(message.schema).toEqual(expected); + }); + + test('You can set the risk_score to 100', () => { + const payload: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + risk_score: 100, + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + ...getUpdateRulesSchemaDecodedMock(), + risk_score: 100, + }; + expect(message.schema).toEqual(expected); + }); + + test('You can set meta to any object you want', () => { + const payload: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + meta: { + somethingMadeUp: { somethingElse: true }, + }, + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + ...getUpdateRulesSchemaDecodedMock(), + meta: { + somethingMadeUp: { somethingElse: true }, + }, + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot update meta as a string', () => { + const payload: Omit & { meta: string } = { + ...getUpdateRulesSchemaMock(), + meta: 'should not work', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "should not work" supplied to "meta"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You can omit the query string when filters are present', () => { + const { query, ...noQuery } = getUpdateRulesSchemaMock(); + const payload: UpdateRulesSchema = { + ...noQuery, + filters: [], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { query: expectedQuery, ...expectedNoQuery } = getUpdateRulesSchemaDecodedMock(); + const expected: UpdateRulesSchemaDecoded = { + ...expectedNoQuery, + filters: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('validates with timeline_id and timeline_title', () => { + const payload: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + timeline_id: 'timeline-id', + timeline_title: 'timeline-title', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + ...getUpdateRulesSchemaDecodedMock(), + timeline_id: 'timeline-id', + timeline_title: 'timeline-title', + }; + expect(message.schema).toEqual(expected); + }); + + test('The default for "from" will be "now-6m"', () => { + const { from, ...noFrom } = getUpdateRulesSchemaMock(); + const payload: UpdateRulesSchema = { + ...noFrom, + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { from: expectedFrom, ...expectedNoFrom } = getUpdateRulesSchemaDecodedMock(); + const expected: UpdateRulesSchemaDecoded = { + ...expectedNoFrom, + from: 'now-6m', + }; + expect(message.schema).toEqual(expected); + }); + + test('The default for "to" will be "now"', () => { + const { to, ...noTo } = getUpdateRulesSchemaMock(); + const payload: UpdateRulesSchema = { + ...noTo, + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { to: expectedTo, ...expectedNoTo } = getUpdateRulesSchemaDecodedMock(); + const expected: UpdateRulesSchemaDecoded = { + ...expectedNoTo, + to: 'now', + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot set the severity to a value other than low, medium, high, or critical', () => { + const payload: Omit & { severity: string } = { + ...getUpdateRulesSchemaMock(), + severity: 'junk', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "junk" supplied to "severity"']); + expect(message.schema).toEqual({}); + }); + + test('The default for "actions" will be an empty array', () => { + const { actions, ...noActions } = getUpdateRulesSchemaMock(); + const payload: UpdateRulesSchema = { + ...noActions, + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { actions: expectedActions, ...expectedNoActions } = getUpdateRulesSchemaDecodedMock(); + const expected: UpdateRulesSchemaDecoded = { + ...expectedNoActions, + actions: [], + }; + expect(message.schema).toEqual(expected); + }); + + test('You cannot send in an array of actions that are missing "group"', () => { + const payload: Omit = { + ...getUpdateRulesSchemaMock(), + actions: [{ id: 'id', action_type_id: 'action_type_id', params: {} }], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "group"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are missing "id"', () => { + const payload: Omit = { + ...getUpdateRulesSchemaMock(), + actions: [{ group: 'group', action_type_id: 'action_type_id', params: {} }], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "undefined" supplied to "id"']); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are missing "action_type_id"', () => { + const payload: Omit = { + ...getUpdateRulesSchemaMock(), + actions: [{ group: 'group', id: 'id', params: {} }], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "action_type_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are missing "params"', () => { + const payload: Omit = { + ...getUpdateRulesSchemaMock(), + actions: [{ group: 'group', id: 'id', action_type_id: 'action_type_id' }], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "params"', + ]); + expect(message.schema).toEqual({}); + }); + + test('You cannot send in an array of actions that are including "actionTypeId"', () => { + const payload: Omit = { + ...getUpdateRulesSchemaMock(), + actions: [ + { + group: 'group', + id: 'id', + actionTypeId: 'actionTypeId', + params: {}, + }, + ], + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "action_type_id"', + ]); + expect(message.schema).toEqual({}); + }); + + test('The default for "throttle" will be null', () => { + const { throttle, ...noThrottle } = getUpdateRulesSchemaMock(); + const payload: UpdateRulesSchema = { + ...noThrottle, + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + + const { throttle: expectedThrottle, ...expectedNoThrottle } = getUpdateRulesSchemaDecodedMock(); + const expected: UpdateRulesSchemaDecoded = { + ...expectedNoThrottle, + throttle: null, + }; + expect(message.schema).toEqual(expected); + }); + + describe('note', () => { + test('You can set note to a string', () => { + const payload: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + note: '# documentation markdown here', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + ...getUpdateRulesSchemaDecodedMock(), + note: '# documentation markdown here', + }; + expect(message.schema).toEqual(expected); + }); + + test('You can set note to an empty string', () => { + const payload: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + note: '', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + ...getUpdateRulesSchemaDecodedMock(), + note: '', + }; + expect(message.schema).toEqual(expected); + }); + + // Note: If you're looking to remove `note`, omit `note` entirely + test('You cannot set note to null', () => { + const payload: Omit & { note: null } = { + ...getUpdateRulesSchemaMock(), + note: null, + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['Invalid value "null" supplied to "note"']); + expect(message.schema).toEqual({}); + }); + + test('You cannot set note as an object', () => { + const payload: Omit & { note: {} } = { + ...getUpdateRulesSchemaMock(), + note: { + somethingHere: 'something else', + }, + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([ + // TODO: Fix/Change the formatErrors to be better able to handle objects + 'Invalid value "[object Object]" supplied to "note"', + ]); + expect(message.schema).toEqual({}); + }); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note] does validate', () => { + const payload: UpdateRulesSchema = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + risk_score: 50, + note: '# some markdown', + }; + + const decoded = updateRulesSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + const expected: UpdateRulesSchemaDecoded = { + rule_id: 'rule-1', + description: 'some description', + from: 'now-5m', + to: 'now', + index: ['index-1'], + name: 'some-name', + severity: 'low', + interval: '5m', + type: 'query', + risk_score: 50, + note: '# some markdown', + references: [], + actions: [], + enabled: true, + false_positives: [], + max_signals: DEFAULT_MAX_SIGNALS, + tags: [], + threat: [], + throttle: null, + exceptions_list: [], + }; + expect(message.schema).toEqual(expected); + }); + }); + + // TODO: The exception_list tests are skipped and empty until we re-integrate it from the lists plugin + describe.skip('exception_list', () => { + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and exceptions_list] does validate', () => {}); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and empty exceptions_list] does validate', () => {}); + + test('rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and invalid exceptions_list] does NOT validate', () => {}); + + test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and non-existent exceptions_list] does validate with empty exceptions_list', () => {}); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_schema.ts new file mode 100644 index 0000000000000..504233f95986f --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_schema.ts @@ -0,0 +1,140 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; + +/* eslint-disable @typescript-eslint/camelcase */ +import { + description, + anomaly_threshold, + filters, + RuleId, + index, + output_index, + saved_id, + timeline_id, + timeline_title, + meta, + machine_learning_job_id, + risk_score, + rule_id, + MaxSignals, + name, + severity, + Tags, + To, + type, + Threat, + ThrottleOrNull, + note, + version, + References, + Actions, + Enabled, + FalsePositives, + From, + Interval, + language, + query, + id, +} from '../common/schemas'; +/* eslint-enable @typescript-eslint/camelcase */ + +import { DefaultStringArray } from '../types/default_string_array'; +import { DefaultActionsArray } from '../types/default_actions_array'; +import { DefaultBooleanTrue } from '../types/default_boolean_true'; +import { DefaultFromString } from '../types/default_from_string'; +import { DefaultIntervalString } from '../types/default_interval_string'; +import { DefaultMaxSignalsNumber } from '../types/default_max_signals_number'; +import { DefaultToString } from '../types/default_to_string'; +import { DefaultThreatArray } from '../types/default_threat_array'; +import { DefaultThrottleNull } from '../types/default_throttle_null'; +import { ListsDefaultArray, ListsDefaultArraySchema } from '../types/lists_default_array'; + +/** + * This almost identical to the create_rules_schema except for a few details. + * - The version will not be defaulted to a 1. If it is not given then its default will become the previous version auto-incremented + * This does break idempotency slightly as calls repeatedly without it will increment the number. If the version number is passed in + * this will update the rule's version number. + * - id is on here because you can pass in an id to update using it instead of rule_id. + */ +export const updateRulesSchema = t.intersection([ + t.exact( + t.type({ + description, + risk_score, + name, + severity, + type, + }) + ), + t.exact( + t.partial({ + id, // defaults to "undefined" if not set during decode + actions: DefaultActionsArray, // defaults to empty actions array if not set during decode + anomaly_threshold, // defaults to undefined if not set during decode + enabled: DefaultBooleanTrue, // defaults to true if not set during decode + false_positives: DefaultStringArray, // defaults to empty string array if not set during decode + filters, // defaults to undefined if not set during decode + from: DefaultFromString, // defaults to "now-6m" if not set during decode + rule_id, // defaults to "undefined" if not set during decode + index, // defaults to undefined if not set during decode + interval: DefaultIntervalString, // defaults to "5m" if not set during decode + query, // defaults to undefined if not set during decode + language, // defaults to undefined if not set during decode + // TODO: output_index: This should be removed eventually + output_index, // defaults to "undefined" if not set during decode + saved_id, // defaults to "undefined" if not set during decode + timeline_id, // defaults to "undefined" if not set during decode + timeline_title, // defaults to "undefined" if not set during decode + meta, // defaults to "undefined" if not set during decode + machine_learning_job_id, // defaults to "undefined" if not set during decode + max_signals: DefaultMaxSignalsNumber, // defaults to DEFAULT_MAX_SIGNALS (100) if not set during decode + tags: DefaultStringArray, // defaults to empty string array if not set during decode + to: DefaultToString, // defaults to "now" if not set during decode + threat: DefaultThreatArray, // defaults to empty array if not set during decode + throttle: DefaultThrottleNull, // defaults to "null" if not set during decode + references: DefaultStringArray, // defaults to empty array of strings if not set during decode + note, // defaults to "undefined" if not set during decode + version, // defaults to "undefined" if not set during decode + exceptions_list: ListsDefaultArray, // defaults to empty array if not set during decode + }) + ), +]); + +export type UpdateRulesSchema = t.TypeOf; + +// This type is used after a decode since some things are defaults after a decode. +export type UpdateRulesSchemaDecoded = Omit< + UpdateRulesSchema, + | 'references' + | 'actions' + | 'enabled' + | 'false_positives' + | 'from' + | 'interval' + | 'max_signals' + | 'tags' + | 'to' + | 'threat' + | 'throttle' + | 'exceptions_list' + | 'rule_id' +> & { + references: References; + actions: Actions; + enabled: Enabled; + false_positives: FalsePositives; + from: From; + interval: Interval; + max_signals: MaxSignals; + tags: Tags; + to: To; + threat: Threat; + throttle: ThrottleOrNull; + exceptions_list: ListsDefaultArraySchema; + rule_id: RuleId; +}; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_type_dependents.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_type_dependents.test.ts new file mode 100644 index 0000000000000..a63c8243cb5f1 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_type_dependents.test.ts @@ -0,0 +1,88 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { getUpdateRulesSchemaMock } from './update_rules_schema.mock'; +import { UpdateRulesSchema } from './update_rules_schema'; +import { updateRuleValidateTypeDependents } from './update_rules_type_dependents'; + +describe('update_rules_type_dependents', () => { + test('saved_id is required when type is saved_query and will not validate without out', () => { + const schema: UpdateRulesSchema = { ...getUpdateRulesSchemaMock(), type: 'saved_query' }; + delete schema.saved_id; + const errors = updateRuleValidateTypeDependents(schema); + expect(errors).toEqual(['when "type" is "saved_query", "saved_id" is required']); + }); + + test('saved_id is required when type is saved_query and validates with it', () => { + const schema: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + type: 'saved_query', + saved_id: '123', + }; + const errors = updateRuleValidateTypeDependents(schema); + expect(errors).toEqual([]); + }); + + test('You cannot omit timeline_title when timeline_id is present', () => { + const schema: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + timeline_id: '123', + }; + delete schema.timeline_title; + const errors = updateRuleValidateTypeDependents(schema); + expect(errors).toEqual(['when "timeline_id" exists, "timeline_title" must also exist']); + }); + + test('You cannot have empty string for timeline_title when timeline_id is present', () => { + const schema: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + timeline_id: '123', + timeline_title: '', + }; + const errors = updateRuleValidateTypeDependents(schema); + expect(errors).toEqual(['"timeline_title" cannot be an empty string']); + }); + + test('You cannot have timeline_title with an empty timeline_id', () => { + const schema: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + timeline_id: '', + timeline_title: 'some-title', + }; + const errors = updateRuleValidateTypeDependents(schema); + expect(errors).toEqual(['"timeline_id" cannot be an empty string']); + }); + + test('You cannot have timeline_title without timeline_id', () => { + const schema: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + timeline_title: 'some-title', + }; + delete schema.timeline_id; + const errors = updateRuleValidateTypeDependents(schema); + expect(errors).toEqual(['when "timeline_title" exists, "timeline_id" must also exist']); + }); + + test('You cannot have both an id and a rule_id', () => { + const schema: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + id: 'some-id', + rule_id: 'some-rule-id', + }; + const errors = updateRuleValidateTypeDependents(schema); + expect(errors).toEqual(['both "id" and "rule_id" cannot exist, choose one or the other']); + }); + + test('You must set either an id or a rule_id', () => { + const schema: UpdateRulesSchema = { + ...getUpdateRulesSchemaMock(), + }; + delete schema.id; + delete schema.rule_id; + const errors = updateRuleValidateTypeDependents(schema); + expect(errors).toEqual(['either "id" or "rule_id" must be set']); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_type_dependents.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_type_dependents.ts new file mode 100644 index 0000000000000..9204f727b2660 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/request/update_rules_type_dependents.ts @@ -0,0 +1,116 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { UpdateRulesSchema } from './update_rules_schema'; + +export const validateAnomalyThreshold = (rule: UpdateRulesSchema): string[] => { + if (rule.type === 'machine_learning') { + if (rule.anomaly_threshold == null) { + return ['when "type" is "machine_learning" anomaly_threshold is required']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateQuery = (rule: UpdateRulesSchema): string[] => { + if (rule.type === 'machine_learning') { + if (rule.query != null) { + return ['when "type" is "machine_learning", "query" cannot be set']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateLanguage = (rule: UpdateRulesSchema): string[] => { + if (rule.type === 'machine_learning') { + if (rule.language != null) { + return ['when "type" is "machine_learning", "language" cannot be set']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateSavedId = (rule: UpdateRulesSchema): string[] => { + if (rule.type === 'saved_query') { + if (rule.saved_id == null) { + return ['when "type" is "saved_query", "saved_id" is required']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateMachineLearningJobId = (rule: UpdateRulesSchema): string[] => { + if (rule.type === 'machine_learning') { + if (rule.machine_learning_job_id == null) { + return ['when "type" is "machine_learning", "machine_learning_job_id" is required']; + } else { + return []; + } + } else { + return []; + } +}; + +export const validateTimelineId = (rule: UpdateRulesSchema): string[] => { + if (rule.timeline_id != null) { + if (rule.timeline_title == null) { + return ['when "timeline_id" exists, "timeline_title" must also exist']; + } else if (rule.timeline_id === '') { + return ['"timeline_id" cannot be an empty string']; + } else { + return []; + } + } + return []; +}; + +export const validateTimelineTitle = (rule: UpdateRulesSchema): string[] => { + if (rule.timeline_title != null) { + if (rule.timeline_id == null) { + return ['when "timeline_title" exists, "timeline_id" must also exist']; + } else if (rule.timeline_title === '') { + return ['"timeline_title" cannot be an empty string']; + } else { + return []; + } + } + return []; +}; + +export const validateId = (rule: UpdateRulesSchema): string[] => { + if (rule.id != null && rule.rule_id != null) { + return ['both "id" and "rule_id" cannot exist, choose one or the other']; + } else if (rule.id == null && rule.rule_id == null) { + return ['either "id" or "rule_id" must be set']; + } else { + return []; + } +}; + +export const updateRuleValidateTypeDependents = (schema: UpdateRulesSchema): string[] => { + return [ + ...validateId(schema), + ...validateAnomalyThreshold(schema), + ...validateQuery(schema), + ...validateLanguage(schema), + ...validateSavedId(schema), + ...validateMachineLearningJobId(schema), + ...validateTimelineId(schema), + ...validateTimelineTitle(schema), + ]; +}; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/deafult_boolean_true.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/deafult_boolean_true.test.ts new file mode 100644 index 0000000000000..a2deaf626624f --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/deafult_boolean_true.test.ts @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DefaultBooleanTrue } from './default_boolean_true'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '../../../test_utils'; + +describe('default_boolean_true', () => { + test('it should validate a boolean false', () => { + const payload = false; + const decoded = DefaultBooleanTrue.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate a boolean true', () => { + const payload = true; + const decoded = DefaultBooleanTrue.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should not validate a number', () => { + const payload = 5; + const decoded = DefaultBooleanTrue.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should return a default true', () => { + const payload = null; + const decoded = DefaultBooleanTrue.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(true); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/deafult_from_string.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/deafult_from_string.test.ts new file mode 100644 index 0000000000000..d68d447ca4454 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/deafult_from_string.test.ts @@ -0,0 +1,39 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DefaultFromString } from './default_from_string'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '../../../test_utils'; + +describe('default_from_string', () => { + test('it should validate a from string', () => { + const payload = 'now-20m'; + const decoded = DefaultFromString.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should not validate a number', () => { + const payload = 5; + const decoded = DefaultFromString.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should return a default of "now-6m"', () => { + const payload = null; + const decoded = DefaultFromString.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual('now-6m'); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_actions_array.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_actions_array.test.ts new file mode 100644 index 0000000000000..645eade71916f --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_actions_array.test.ts @@ -0,0 +1,54 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DefaultActionsArray } from './default_actions_array'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '../../../test_utils'; +import { Actions } from '../common/schemas'; + +describe('default_actions_array', () => { + test('it should validate an empty array', () => { + const payload: string[] = []; + const decoded = DefaultActionsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate an array of actions', () => { + const payload: Actions = [ + { id: '123', group: 'group', action_type_id: 'action_type_id', params: {} }, + ]; + const decoded = DefaultActionsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should not validate an array with a number', () => { + const payload = [ + { id: '123', group: 'group', action_type_id: 'action_type_id', params: {} }, + 5, + ]; + const decoded = DefaultActionsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should return a default array entry', () => { + const payload = null; + const decoded = DefaultActionsArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual([]); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_actions_array.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_actions_array.ts new file mode 100644 index 0000000000000..ce3eb7fa7da83 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_actions_array.ts @@ -0,0 +1,22 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { actions, Actions } from '../common/schemas'; + +/** + * Types the DefaultStringArray as: + * - If null or undefined, then a default action array will be set + */ +export const DefaultActionsArray = new t.Type( + 'DefaultActionsArray', + actions.is, + (input): Either => (input == null ? t.success([]) : actions.decode(input)), + t.identity +); + +export type DefaultActionsArrayC = typeof DefaultActionsArray; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_false.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_false.test.ts new file mode 100644 index 0000000000000..1697928b17e0c --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_false.test.ts @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DefaultBooleanFalse } from './default_boolean_false'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '../../../test_utils'; + +describe('default_boolean_false', () => { + test('it should validate a boolean false', () => { + const payload = false; + const decoded = DefaultBooleanFalse.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate a boolean true', () => { + const payload = true; + const decoded = DefaultBooleanFalse.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should not validate a number', () => { + const payload = 5; + const decoded = DefaultBooleanFalse.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should return a default false', () => { + const payload = null; + const decoded = DefaultBooleanFalse.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(false); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_false.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_false.ts new file mode 100644 index 0000000000000..624b9802f680c --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_false.ts @@ -0,0 +1,22 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; + +/** + * Types the DefaultBooleanFalse as: + * - If null or undefined, then a default false will be set + */ +export const DefaultBooleanFalse = new t.Type( + 'DefaultBooleanFalse', + t.boolean.is, + (input): Either => + input == null ? t.success(false) : t.boolean.decode(input), + t.identity +); + +export type DefaultBooleanFalseC = typeof DefaultBooleanFalse; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_true.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_true.ts new file mode 100644 index 0000000000000..58c912a0a8650 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_boolean_true.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; + +/** + * Types the DefaultBooleanTrue as: + * - If null or undefined, then a default true will be set + */ +export const DefaultBooleanTrue = new t.Type( + 'DefaultBooleanTrue', + t.boolean.is, + (input): Either => (input == null ? t.success(true) : t.boolean.decode(input)), + t.identity +); + +export type DefaultBooleanTrueC = typeof DefaultBooleanTrue; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_empty_string.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_empty_string.test.ts new file mode 100644 index 0000000000000..386d4c55905cd --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_empty_string.test.ts @@ -0,0 +1,39 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DefaultEmptyString } from './default_empty_string'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '../../../test_utils'; + +describe('default_empty_string', () => { + test('it should validate a regular string', () => { + const payload = 'some string'; + const decoded = DefaultEmptyString.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should not validate a number', () => { + const payload = 5; + const decoded = DefaultEmptyString.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should return a default of ""', () => { + const payload = null; + const decoded = DefaultEmptyString.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(''); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_empty_string.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_empty_string.ts new file mode 100644 index 0000000000000..6216d0c1111b0 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_empty_string.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; + +/** + * Types the DefaultEmptyString as: + * - If null or undefined, then a default of an empty string "" will be used + */ +export const DefaultEmptyString = new t.Type( + 'DefaultEmptyString', + t.string.is, + (input): Either => (input == null ? t.success('') : t.string.decode(input)), + t.identity +); + +export type DefaultEmptyStringC = typeof DefaultEmptyString; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_export_file_name.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_export_file_name.test.ts new file mode 100644 index 0000000000000..328cd738d7de0 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_export_file_name.test.ts @@ -0,0 +1,39 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DefaultExportFileName } from './default_export_file_name'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '../../../test_utils'; + +describe('default_export_file_name', () => { + test('it should validate a regular string', () => { + const payload = 'some string'; + const decoded = DefaultExportFileName.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should not validate a number', () => { + const payload = 5; + const decoded = DefaultExportFileName.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should return a default of "export.ndjson"', () => { + const payload = null; + const decoded = DefaultExportFileName.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual('export.ndjson'); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_export_file_name.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_export_file_name.ts new file mode 100644 index 0000000000000..41dfdee1e0da0 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_export_file_name.ts @@ -0,0 +1,22 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; + +/** + * Types the DefaultExportFileName as: + * - If null or undefined, then a default of "export.ndjson" will be used + */ +export const DefaultExportFileName = new t.Type( + 'DefaultExportFileName', + t.string.is, + (input): Either => + input == null ? t.success('export.ndjson') : t.string.decode(input), + t.identity +); + +export type DefaultExportFileNameC = typeof DefaultExportFileName; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_from_string.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_from_string.ts new file mode 100644 index 0000000000000..4217532de954e --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_from_string.ts @@ -0,0 +1,22 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; + +/** + * Types the DefaultFromString as: + * - If null or undefined, then a default of the string "now-6m" will be used + */ +export const DefaultFromString = new t.Type( + 'DefaultFromString', + t.string.is, + (input): Either => + input == null ? t.success('now-6m') : t.string.decode(input), + t.identity +); + +export type DefaultFromStringC = typeof DefaultFromString; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_interval_string.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_interval_string.test.ts new file mode 100644 index 0000000000000..9720178a4ae9b --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_interval_string.test.ts @@ -0,0 +1,39 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DefaultIntervalString } from './default_interval_string'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '../../../test_utils'; + +describe('default_interval_string', () => { + test('it should validate a interval string', () => { + const payload = '20m'; + const decoded = DefaultIntervalString.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should not validate a number', () => { + const payload = 5; + const decoded = DefaultIntervalString.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should return a default of "5m"', () => { + const payload = null; + const decoded = DefaultIntervalString.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual('5m'); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_interval_string.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_interval_string.ts new file mode 100644 index 0000000000000..579e7591fdb03 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_interval_string.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; + +/** + * Types the DefaultIntervalString as: + * - If null or undefined, then a default of the string "5m" will be used + */ +export const DefaultIntervalString = new t.Type( + 'DefaultIntervalString', + t.string.is, + (input): Either => (input == null ? t.success('5m') : t.string.decode(input)), + t.identity +); + +export type DefaultIntervalStringC = typeof DefaultIntervalString; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_language_string.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_language_string.test.ts new file mode 100644 index 0000000000000..e3da8dbd280ab --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_language_string.test.ts @@ -0,0 +1,40 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DefaultLanguageString } from './default_language_string'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '../../../test_utils'; +import { Language } from '../common/schemas'; + +describe('default_language_string', () => { + test('it should validate a string', () => { + const payload: Language = 'lucene'; + const decoded = DefaultLanguageString.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should not validate a number', () => { + const payload = 5; + const decoded = DefaultLanguageString.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should return a default of "kuery"', () => { + const payload = null; + const decoded = DefaultLanguageString.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual('kuery'); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_language_string.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_language_string.ts new file mode 100644 index 0000000000000..248e15d56dfd7 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_language_string.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { language } from '../common/schemas'; + +/** + * Types the DefaultLanguageString as: + * - If null or undefined, then a default of the string "kuery" will be used + */ +export const DefaultLanguageString = new t.Type( + 'DefaultLanguageString', + t.string.is, + (input): Either => + input == null ? t.success('kuery') : language.decode(input), + t.identity +); + +export type DefaultLanguageStringC = typeof DefaultLanguageString; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_max_signals_number.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_max_signals_number.test.ts new file mode 100644 index 0000000000000..a6f137c3f2113 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_max_signals_number.test.ts @@ -0,0 +1,58 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DefaultMaxSignalsNumber } from './default_max_signals_number'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '../../../test_utils'; +import { DEFAULT_MAX_SIGNALS } from '../../../constants'; + +describe('default_from_string', () => { + test('it should validate a max signal number', () => { + const payload = 5; + const decoded = DefaultMaxSignalsNumber.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should not validate a string', () => { + const payload = '5'; + const decoded = DefaultMaxSignalsNumber.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should not validate a zero', () => { + const payload = 0; + const decoded = DefaultMaxSignalsNumber.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "0" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should not validate a negative number', () => { + const payload = -1; + const decoded = DefaultMaxSignalsNumber.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "-1" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should return a default of DEFAULT_MAX_SIGNALS', () => { + const payload = null; + const decoded = DefaultMaxSignalsNumber.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(DEFAULT_MAX_SIGNALS); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_max_signals_number.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_max_signals_number.ts new file mode 100644 index 0000000000000..6f0c32c5466f3 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_max_signals_number.ts @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +// eslint-disable-next-line @typescript-eslint/camelcase +import { max_signals } from '../common/schemas'; +import { DEFAULT_MAX_SIGNALS } from '../../../constants'; + +/** + * Types the default max signal: + * - Natural Number (positive integer and not a float), + * - greater than 1 + * - If undefined then it will use DEFAULT_MAX_SIGNALS (100) as the default + */ +export const DefaultMaxSignalsNumber: DefaultMaxSignalsNumberC = new t.Type< + number, + number, + unknown +>( + 'DefaultMaxSignals', + t.number.is, + (input): Either => { + return input == null ? t.success(DEFAULT_MAX_SIGNALS) : max_signals.decode(input); + }, + t.identity +); + +export type DefaultMaxSignalsNumberC = t.Type; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_page.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_page.test.ts new file mode 100644 index 0000000000000..1d1d43667c710 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_page.test.ts @@ -0,0 +1,75 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DefaultPage } from './default_page'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '../../../test_utils'; + +describe('default_page', () => { + test('it should validate a regular number greater than zero', () => { + const payload = 5; + const decoded = DefaultPage.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate a string of a number', () => { + const payload = '5'; + const decoded = DefaultPage.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(5); + }); + + test('it should not validate a junk string', () => { + const payload = 'invalid-string'; + const decoded = DefaultPage.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "NaN" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should not validate an empty string', () => { + const payload = ''; + const decoded = DefaultPage.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "NaN" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should not validate a zero', () => { + const payload = 0; + const decoded = DefaultPage.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "0" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should not validate a negative number', () => { + const payload = -1; + const decoded = DefaultPage.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "-1" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should return a default of 20', () => { + const payload = null; + const decoded = DefaultPage.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(1); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_page.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_page.ts new file mode 100644 index 0000000000000..95e3b42f3e138 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_page.ts @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { PositiveIntegerGreaterThanZero } from './positive_integer_greater_than_zero'; + +/** + * Types the DefaultPerPage as: + * - If a string this will convert the string to a number + * - If null or undefined, then a default of 1 will be used + * - If the number is 0 or less this will not validate as it has to be a positive number greater than zero + */ +export const DefaultPage = new t.Type( + 'DefaultPerPage', + t.number.is, + (input): Either => { + if (input == null) { + return t.success(1); + } else if (typeof input === 'string') { + return PositiveIntegerGreaterThanZero.decode(parseInt(input, 10)); + } else { + return PositiveIntegerGreaterThanZero.decode(input); + } + }, + t.identity +); + +export type DefaultPageC = typeof DefaultPage; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_per_page.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_per_page.test.ts new file mode 100644 index 0000000000000..3ecbae6ed43f5 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_per_page.test.ts @@ -0,0 +1,75 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DefaultPerPage } from './default_per_page'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '../../../test_utils'; + +describe('default_per_page', () => { + test('it should validate a regular number greater than zero', () => { + const payload = 5; + const decoded = DefaultPerPage.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate a string of a number', () => { + const payload = '5'; + const decoded = DefaultPerPage.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(5); + }); + + test('it should not validate a junk string', () => { + const payload = 'invalid-string'; + const decoded = DefaultPerPage.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "NaN" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should not validate an empty string', () => { + const payload = ''; + const decoded = DefaultPerPage.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "NaN" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should not validate a zero', () => { + const payload = 0; + const decoded = DefaultPerPage.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "0" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should not validate a negative number', () => { + const payload = -1; + const decoded = DefaultPerPage.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "-1" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should return a default of 20', () => { + const payload = null; + const decoded = DefaultPerPage.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(20); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_per_page.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_per_page.ts new file mode 100644 index 0000000000000..f96f280f6af11 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_per_page.ts @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { PositiveIntegerGreaterThanZero } from './positive_integer_greater_than_zero'; + +/** + * Types the DefaultPerPage as: + * - If a string this will convert the string to a number + * - If null or undefined, then a default of 20 will be used + * - If the number is 0 or less this will not validate as it has to be a positive number greater than zero + */ +export const DefaultPerPage = new t.Type( + 'DefaultPerPage', + t.number.is, + (input): Either => { + if (input == null) { + return t.success(20); + } else if (typeof input === 'string') { + return PositiveIntegerGreaterThanZero.decode(parseInt(input, 10)); + } else { + return PositiveIntegerGreaterThanZero.decode(input); + } + }, + t.identity +); + +export type DefaultPerPageC = typeof DefaultPerPage; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_array.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_array.test.ts new file mode 100644 index 0000000000000..83142c8d65777 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_array.test.ts @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DefaultStringArray } from './default_string_array'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '../../../test_utils'; + +describe('default_string_array', () => { + test('it should validate an empty array', () => { + const payload: string[] = []; + const decoded = DefaultStringArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate an array of strings', () => { + const payload = ['value 1', 'value 2']; + const decoded = DefaultStringArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should not validate an array with a number', () => { + const payload = ['value 1', 5]; + const decoded = DefaultStringArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should return a default array entry', () => { + const payload = null; + const decoded = DefaultStringArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual([]); + }); +}); diff --git a/x-pack/plugins/lists/common/schemas/types/default_string_array.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_array.ts similarity index 75% rename from x-pack/plugins/lists/common/schemas/types/default_string_array.ts rename to x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_array.ts index c6ebffa379903..1f043cfd1b8e5 100644 --- a/x-pack/plugins/lists/common/schemas/types/default_string_array.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_array.ts @@ -7,16 +7,16 @@ import * as t from 'io-ts'; import { Either } from 'fp-ts/lib/Either'; -export type DefaultStringArrayC = t.Type; - /** * Types the DefaultStringArray as: * - If null or undefined, then a default array will be set */ -export const DefaultStringArray: DefaultStringArrayC = new t.Type( - 'DefaultArray', +export const DefaultStringArray = new t.Type( + 'DefaultStringArray', t.array(t.string).is, (input): Either => input == null ? t.success([]) : t.array(t.string).decode(input), t.identity ); + +export type DefaultStringArrayC = typeof DefaultStringArray; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_boolean_false.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_boolean_false.test.ts new file mode 100644 index 0000000000000..1941a642e8baf --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_boolean_false.test.ts @@ -0,0 +1,93 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '../../../test_utils'; +import { DefaultStringBooleanFalse } from './default_string_boolean_false'; + +describe('default_string_boolean_false', () => { + test('it should validate a boolean false', () => { + const payload = false; + const decoded = DefaultStringBooleanFalse.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate a boolean true', () => { + const payload = true; + const decoded = DefaultStringBooleanFalse.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should not validate a number', () => { + const payload = 5; + const decoded = DefaultStringBooleanFalse.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should return a default false', () => { + const payload = null; + const decoded = DefaultStringBooleanFalse.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(false); + }); + + test('it should return a default false when given a string of "false"', () => { + const payload = 'false'; + const decoded = DefaultStringBooleanFalse.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(false); + }); + + test('it should return a default true when given a string of "true"', () => { + const payload = 'true'; + const decoded = DefaultStringBooleanFalse.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(true); + }); + + test('it should return a default true when given a string of "TruE"', () => { + const payload = 'TruE'; + const decoded = DefaultStringBooleanFalse.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(true); + }); + + test('it should not work with a strong of junk "junk"', () => { + const payload = 'junk'; + const decoded = DefaultStringBooleanFalse.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "junk" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should not work with an empty string', () => { + const payload = ''; + const decoded = DefaultStringBooleanFalse.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to ""']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_boolean_false.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_boolean_false.ts new file mode 100644 index 0000000000000..48a40d4b9ceec --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_string_boolean_false.ts @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; + +/** + * Types the DefaultStringBooleanFalse as: + * - If a string this will convert the string to a boolean + * - If null or undefined, then a default false will be set + */ +export const DefaultStringBooleanFalse = new t.Type( + 'DefaultStringBooleanFalse', + t.boolean.is, + (input): Either => { + if (input == null) { + return t.success(false); + } else if (typeof input === 'string' && input.toLowerCase() === 'true') { + return t.success(true); + } else if (typeof input === 'string' && input.toLowerCase() === 'false') { + return t.success(false); + } else { + return t.boolean.decode(input); + } + }, + t.identity +); + +export type DefaultStringBooleanFalseC = typeof DefaultStringBooleanFalse; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_threat_array.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_threat_array.test.ts new file mode 100644 index 0000000000000..9819da0b8d463 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_threat_array.test.ts @@ -0,0 +1,62 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DefaultThreatArray } from './default_threat_array'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '../../../test_utils'; +import { Threat } from '../common/schemas'; + +describe('default_threat_null', () => { + test('it should validate an empty array', () => { + const payload: Threat = []; + const decoded = DefaultThreatArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate an array of threats', () => { + const payload: Threat = [ + { + framework: 'MITRE ATTACK', + technique: [{ reference: 'https://test.com', name: 'Audio Capture', id: 'T1123' }], + tactic: { reference: 'https://test.com', name: 'Collection', id: 'TA000999' }, + }, + ]; + const decoded = DefaultThreatArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should not validate an array with a number', () => { + const payload = [ + { + framework: 'MITRE ATTACK', + technique: [{ reference: 'https://test.com', name: 'Audio Capture', id: 'T1123' }], + tactic: { reference: 'https://test.com', name: 'Collection', id: 'TA000999' }, + }, + 5, + ]; + const decoded = DefaultThreatArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should return a default empty array if not provided a value', () => { + const payload = null; + const decoded = DefaultThreatArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual([]); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_threat_array.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_threat_array.ts new file mode 100644 index 0000000000000..da0611e24bc7e --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_threat_array.ts @@ -0,0 +1,22 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { Threat, threat } from '../common/schemas'; + +/** + * Types the DefaultThreatArray as: + * - If null or undefined, then an empty array will be set + */ +export const DefaultThreatArray = new t.Type( + 'DefaultThreatArray', + threat.is, + (input): Either => (input == null ? t.success([]) : threat.decode(input)), + t.identity +); + +export type DefaultThreatArrayC = typeof DefaultThreatArray; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_throttle_null.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_throttle_null.test.ts new file mode 100644 index 0000000000000..304fd65647c3c --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_throttle_null.test.ts @@ -0,0 +1,40 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DefaultThrottleNull } from './default_throttle_null'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '../../../test_utils'; +import { Throttle } from '../common/schemas'; + +describe('default_throttle_null', () => { + test('it should validate a throttle string', () => { + const payload: Throttle = 'some string'; + const decoded = DefaultThrottleNull.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should not validate an array with a number', () => { + const payload = 5; + const decoded = DefaultThrottleNull.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should return a default "null" if not provided a value', () => { + const payload = undefined; + const decoded = DefaultThrottleNull.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(null); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_throttle_null.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_throttle_null.ts new file mode 100644 index 0000000000000..fd31594323f4d --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_throttle_null.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { ThrottleOrNull, throttle } from '../common/schemas'; + +/** + * Types the DefaultThrottleNull as: + * - If null or undefined, then a null will be set + */ +export const DefaultThrottleNull = new t.Type( + 'DefaultThreatNull', + throttle.is, + (input): Either => + input == null ? t.success(null) : throttle.decode(input), + t.identity +); + +export type DefaultThrottleNullC = typeof DefaultThrottleNull; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_to_string.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_to_string.test.ts new file mode 100644 index 0000000000000..3e22d57cedf99 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_to_string.test.ts @@ -0,0 +1,39 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DefaultToString } from './default_to_string'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '../../../test_utils'; + +describe('default_to_string', () => { + test('it should validate a to string', () => { + const payload = 'now-5m'; + const decoded = DefaultToString.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should not validate a number', () => { + const payload = 5; + const decoded = DefaultToString.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should return a default of "now"', () => { + const payload = null; + const decoded = DefaultToString.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual('now'); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_to_string.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_to_string.ts new file mode 100644 index 0000000000000..163bcf8c4e5b2 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_to_string.ts @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; + +/** + * Types the DefaultToString as: + * - If null or undefined, then a default of the string "now" will be used + */ +export const DefaultToString = new t.Type( + 'DefaultFromString', + t.string.is, + (input): Either => (input == null ? t.success('now') : t.string.decode(input)), + t.identity +); + +export type DefaultToStringC = typeof DefaultToString; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_uuid.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_uuid.test.ts new file mode 100644 index 0000000000000..7dab8869d5d87 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_uuid.test.ts @@ -0,0 +1,41 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DefaultUuid } from './default_uuid'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '../../../test_utils'; + +describe('default_uuid', () => { + test('it should validate a regular string', () => { + const payload = '1'; + const decoded = DefaultUuid.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should not validate a number', () => { + const payload = 5; + const decoded = DefaultUuid.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should return a default of a uuid', () => { + const payload = null; + const decoded = DefaultUuid.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toMatch( + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i + ); + }); +}); diff --git a/x-pack/plugins/lists/common/schemas/types/default_uuid.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_uuid.ts similarity index 84% rename from x-pack/plugins/lists/common/schemas/types/default_uuid.ts rename to x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_uuid.ts index 4fb4133d7353f..b0c328a93ff03 100644 --- a/x-pack/plugins/lists/common/schemas/types/default_uuid.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_uuid.ts @@ -10,17 +10,17 @@ import uuid from 'uuid'; import { NonEmptyString } from './non_empty_string'; -export type DefaultUuidC = t.Type; - /** * Types the DefaultUuid as: * - If null or undefined, then a default string uuid.v4() will be * created otherwise it will be checked just against an empty string */ -export const DefaultUuid: DefaultUuidC = new t.Type( +export const DefaultUuid = new t.Type( 'DefaultUuid', t.string.is, (input): Either => input == null ? t.success(uuid.v4()) : NonEmptyString.decode(input), t.identity ); + +export type DefaultUuidC = typeof DefaultUuid; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_version_number.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_version_number.test.ts new file mode 100644 index 0000000000000..65697d8830b66 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_version_number.test.ts @@ -0,0 +1,57 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { DefaultVersionNumber } from './default_version_number'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '../../../test_utils'; + +describe('default_version_number', () => { + test('it should validate a version number', () => { + const payload = 5; + const decoded = DefaultVersionNumber.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should not validate a 0', () => { + const payload = 0; + const decoded = DefaultVersionNumber.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "0" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should not validate a -1', () => { + const payload = -1; + const decoded = DefaultVersionNumber.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "-1" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should not validate a string', () => { + const payload = '5'; + const decoded = DefaultVersionNumber.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should return a default of 1', () => { + const payload = null; + const decoded = DefaultVersionNumber.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(1); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_version_number.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_version_number.ts new file mode 100644 index 0000000000000..4a310329660df --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/default_version_number.ts @@ -0,0 +1,22 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; +import { version, Version } from '../common/schemas'; + +/** + * Types the DefaultVersionNumber as: + * - If null or undefined, then a default of the number 1 will be used + */ +export const DefaultVersionNumber = new t.Type( + 'DefaultVersionNumber', + version.is, + (input): Either => (input == null ? t.success(1) : version.decode(input)), + t.identity +); + +export type DefaultVersionNumberC = typeof DefaultVersionNumber; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/iso_date_string.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/iso_date_string.ts index d63c18154c5d4..4e12a45f21d0b 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/iso_date_string.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/iso_date_string.ts @@ -7,13 +7,11 @@ import * as t from 'io-ts'; import { Either } from 'fp-ts/lib/Either'; -export type IsoDateStringC = t.Type; - /** * Types the IsoDateString as: * - A string that is an ISOString */ -export const IsoDateString: IsoDateStringC = new t.Type( +export const IsoDateString = new t.Type( 'IsoDateString', t.string.is, (input, context): Either => { @@ -34,3 +32,5 @@ export const IsoDateString: IsoDateStringC = new t.Type }, t.identity ); + +export type IsoDateStringC = typeof IsoDateString; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists_default_array.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists_default_array.ts index 8244f4a29e193..8cdd865469112 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists_default_array.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists_default_array.ts @@ -13,7 +13,6 @@ import { list_values_operator as listOperator, } from '../common/schemas'; -export type ListsDefaultArrayC = t.Type; export type List = t.TypeOf; export type ListValues = t.TypeOf; export type ListOperator = t.TypeOf; @@ -22,7 +21,7 @@ export type ListOperator = t.TypeOf; * Types the ListsDefaultArray as: * - If null or undefined, then a default array will be set for the list */ -export const ListsDefaultArray: ListsDefaultArrayC = new t.Type( +export const ListsDefaultArray = new t.Type( 'listsWithDefaultArray', t.array(listAnd).is, (input): Either => @@ -30,4 +29,6 @@ export const ListsDefaultArray: ListsDefaultArrayC = new t.Type; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_string.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_string.test.ts new file mode 100644 index 0000000000000..0a88b87421e70 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_string.test.ts @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { NonEmptyString } from './non_empty_string'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { foldLeftRight, getPaths } from '../../../test_utils'; + +describe('non_empty_string', () => { + test('it should validate a regular string', () => { + const payload = '1'; + const decoded = NonEmptyString.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should not validate a number', () => { + const payload = 5; + const decoded = NonEmptyString.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should not validate an empty string', () => { + const payload = ''; + const decoded = NonEmptyString.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should not validate empty spaces', () => { + const payload = ' '; + const decoded = NonEmptyString.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value " " supplied to ""']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/plugins/lists/common/schemas/types/non_empty_string.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_string.ts similarity index 81% rename from x-pack/plugins/lists/common/schemas/types/non_empty_string.ts rename to x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_string.ts index d1e2094bbcad3..b3fad548932d5 100644 --- a/x-pack/plugins/lists/common/schemas/types/non_empty_string.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/non_empty_string.ts @@ -7,13 +7,11 @@ import * as t from 'io-ts'; import { Either } from 'fp-ts/lib/Either'; -export type NonEmptyStringC = t.Type; - /** * Types the NonEmptyString as: * - A string that is not empty */ -export const NonEmptyString: NonEmptyStringC = new t.Type( +export const NonEmptyString = new t.Type( 'NonEmptyString', t.string.is, (input, context): Either => { @@ -25,3 +23,5 @@ export const NonEmptyString: NonEmptyStringC = new t.Type { + test('it should validate a boolean false as false', () => { + const payload = false; + const decoded = OnlyFalseAllowed.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should not validate a boolean true', () => { + const payload = true; + const decoded = OnlyFalseAllowed.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "true" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should not validate a number', () => { + const payload = 5; + const decoded = OnlyFalseAllowed.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); + expect(message.schema).toEqual({}); + }); + + test('it should return a default false', () => { + const payload = null; + const decoded = OnlyFalseAllowed.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(false); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/only_false_allowed.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/only_false_allowed.ts new file mode 100644 index 0000000000000..b22562e2ab9dc --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/only_false_allowed.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; + +/** + * Types the OnlyFalseAllowed as: + * - If null or undefined, then a default false will be set + * - If true is sent in then this will return an error + * - If false is sent in then this will allow it only false + */ +export const OnlyFalseAllowed = new t.Type( + 'DefaultBooleanTrue', + t.boolean.is, + (input, context): Either => { + if (input == null) { + return t.success(false); + } else { + if (typeof input === 'boolean' && input === false) { + return t.success(false); + } else { + return t.failure(input, context); + } + } + }, + t.identity +); + +export type OnlyFalseAllowedC = typeof OnlyFalseAllowed; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/positive_integer.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/positive_integer.ts index ac98dd6f5d85c..298487a3fae98 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/positive_integer.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/positive_integer.ts @@ -7,14 +7,12 @@ import * as t from 'io-ts'; import { Either } from 'fp-ts/lib/Either'; -export type PositiveIntegerC = t.Type; - /** * Types the positive integer are: * - Natural Number (positive integer and not a float), * - zero or greater */ -export const PositiveInteger: PositiveIntegerC = new t.Type( +export const PositiveInteger = new t.Type( 'PositiveInteger', t.number.is, (input, context): Either => { @@ -24,3 +22,5 @@ export const PositiveInteger: PositiveIntegerC = new t.Type; - /** * Types the positive integer greater than zero is: * - Natural Number (positive integer and not a float), * - 1 or greater */ -export const PositiveIntegerGreaterThanZero: PositiveIntegerGreaterThanZeroC = new t.Type< - number, - number, - unknown ->( +export const PositiveIntegerGreaterThanZero = new t.Type( 'PositiveIntegerGreaterThanZero', t.number.is, (input, context): Either => { @@ -28,3 +22,5 @@ export const PositiveIntegerGreaterThanZero: PositiveIntegerGreaterThanZeroC = n }, t.identity ); + +export type PositiveIntegerGreaterThanZeroC = typeof PositiveIntegerGreaterThanZero; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/references_default_array.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/references_default_array.test.ts index 43e2dbdac1fe1..83142c8d65777 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/references_default_array.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/references_default_array.test.ts @@ -4,15 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ -import { ReferencesDefaultArray } from './references_default_array'; +import { DefaultStringArray } from './default_string_array'; import { pipe } from 'fp-ts/lib/pipeable'; import { left } from 'fp-ts/lib/Either'; import { foldLeftRight, getPaths } from '../../../test_utils'; -describe('references_default_array', () => { +describe('default_string_array', () => { test('it should validate an empty array', () => { const payload: string[] = []; - const decoded = ReferencesDefaultArray.decode(payload); + const decoded = DefaultStringArray.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([]); @@ -21,7 +21,7 @@ describe('references_default_array', () => { test('it should validate an array of strings', () => { const payload = ['value 1', 'value 2']; - const decoded = ReferencesDefaultArray.decode(payload); + const decoded = DefaultStringArray.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([]); @@ -30,7 +30,7 @@ describe('references_default_array', () => { test('it should not validate an array with a number', () => { const payload = ['value 1', 5]; - const decoded = ReferencesDefaultArray.decode(payload); + const decoded = DefaultStringArray.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual(['Invalid value "5" supplied to ""']); @@ -39,7 +39,7 @@ describe('references_default_array', () => { test('it should return a default array entry', () => { const payload = null; - const decoded = ReferencesDefaultArray.decode(payload); + const decoded = DefaultStringArray.decode(payload); const message = pipe(decoded, foldLeftRight); expect(getPaths(left(message.errors))).toEqual([]); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/references_default_array.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/references_default_array.ts index 57a7ed4e4d456..b809181ce8c32 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/references_default_array.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/references_default_array.ts @@ -7,20 +7,16 @@ import * as t from 'io-ts'; import { Either } from 'fp-ts/lib/Either'; -export type ReferencesDefaultArrayC = t.Type; - /** * Types the ReferencesDefaultArray as: * - If null or undefined, then a default array will be set */ -export const ReferencesDefaultArray: ReferencesDefaultArrayC = new t.Type< - string[], - string[], - unknown ->( +export const ReferencesDefaultArray = new t.Type( 'referencesWithDefaultArray', t.array(t.string).is, (input): Either => input == null ? t.success([]) : t.array(t.string).decode(input), t.identity ); + +export type ReferencesDefaultArrayC = typeof ReferencesDefaultArray; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/risk_score.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/risk_score.ts index c44fae3c6f3e7..7f057a6d178e1 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/risk_score.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/risk_score.ts @@ -7,14 +7,12 @@ import * as t from 'io-ts'; import { Either } from 'fp-ts/lib/Either'; -export type RiskScoreC = t.Type; - /** * Types the risk score as: * - Natural Number (positive integer and not a float), * - Between the values [0 and 100] inclusive. */ -export const RiskScore: RiskScoreC = new t.Type( +export const RiskScore = new t.Type( 'RiskScore', t.number.is, (input, context): Either => { @@ -24,3 +22,5 @@ export const RiskScore: RiskScoreC = new t.Type( }, t.identity ); + +export type RiskScoreC = typeof RiskScore; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/uuid.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/uuid.ts index 88e9db5964198..3676aa5686cd6 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/uuid.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/uuid.ts @@ -7,8 +7,6 @@ import * as t from 'io-ts'; import { Either } from 'fp-ts/lib/Either'; -export type UUIDC = t.Type; - const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; /** @@ -16,7 +14,7 @@ const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; * - Natural Number (positive integer and not a float), * - Between the values [0 and 100] inclusive. */ -export const UUID: UUIDC = new t.Type( +export const UUID = new t.Type( 'UUID', t.string.is, (input, context): Either => { @@ -26,3 +24,5 @@ export const UUID: UUIDC = new t.Type( }, t.identity ); + +export type UUIDC = typeof UUID; diff --git a/x-pack/plugins/security_solution/common/exact_check.test.ts b/x-pack/plugins/security_solution/common/exact_check.test.ts index a5701603de0d6..96a1b1266ea9a 100644 --- a/x-pack/plugins/security_solution/common/exact_check.test.ts +++ b/x-pack/plugins/security_solution/common/exact_check.test.ts @@ -86,6 +86,23 @@ describe('exact_check', () => { expect(message.schema).toEqual({ a: 'test' }); }); + test('it will work with decoding a null payload when the schema expects a null', () => { + const someType = t.union([ + t.exact( + t.type({ + a: t.string, + }) + ), + t.null, + ]); + const payload = null; + const decoded = someType.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(null); + }); + test('it should find no differences recursively with two empty objects', () => { const difference = findDifferencesRecursive({}, {}); expect(difference).toEqual([]); @@ -151,4 +168,9 @@ describe('exact_check', () => { ); expect(difference).toEqual(['d']); }); + + test('it should not find any differences when the original and decoded are both null', () => { + const difference = findDifferencesRecursive(null, null); + expect(difference).toEqual([]); + }); }); diff --git a/x-pack/plugins/security_solution/common/exact_check.ts b/x-pack/plugins/security_solution/common/exact_check.ts index 30c5b585a3480..48afc35b56ba1 100644 --- a/x-pack/plugins/security_solution/common/exact_check.ts +++ b/x-pack/plugins/security_solution/common/exact_check.ts @@ -25,7 +25,10 @@ import { isObject, get } from 'lodash/fp'; * @param decoded The decoded either which has either an existing error or the * decoded object which could have additional keys stripped from it. */ -export const exactCheck = (original: T, decoded: Either): Either => { +export const exactCheck = ( + original: unknown, + decoded: Either +): Either => { const onLeft = (errors: t.Errors): Either => left(errors); const onRight = (decodedValue: T): Either => { const differences = findDifferencesRecursive(original, decodedValue); @@ -45,7 +48,11 @@ export const exactCheck = (original: T, decoded: Either): Either }; export const findDifferencesRecursive = (original: T, decodedValue: T): string[] => { - if (decodedValue == null) { + if (decodedValue === null && original === null) { + // both the decodedValue and the original are null which indicates that they are equal + // so do not report differences + return []; + } else if (decodedValue == null) { try { // It is null and painful when the original contains an object or an array // the the decoded value does not have. diff --git a/x-pack/plugins/security_solution/public/alerts/components/rules/step_about_rule/index.test.tsx b/x-pack/plugins/security_solution/public/alerts/components/rules/step_about_rule/index.test.tsx index 3eedbcc97bbd1..5a08b0a20d1fc 100644 --- a/x-pack/plugins/security_solution/public/alerts/components/rules/step_about_rule/index.test.tsx +++ b/x-pack/plugins/security_solution/public/alerts/components/rules/step_about_rule/index.test.tsx @@ -13,6 +13,8 @@ import { StepAboutRule } from '.'; import { mockAboutStepRule } from '../../../pages/detection_engine/rules/all/__mocks__/mock'; import { StepRuleDescription } from '../description_step'; import { stepAboutDefaultValue } from './default_value'; +import { wait } from '@testing-library/react'; +import { AboutStepRule } from '../../../pages/detection_engine/rules/types'; const theme = () => ({ eui: euiDarkVars, darkMode: true }); @@ -57,31 +59,31 @@ describe('StepAboutRuleComponent', () => { ); - const nameInput = wrapper - .find('input[aria-describedby="detectionEngineStepAboutRuleName"]') - .at(0); - nameInput.simulate('change', { target: { value: 'Test name text' } }); + wrapper + .find('[data-test-subj="detectionEngineStepAboutRuleName"] input') + .first() + .simulate('change', { target: { value: 'Test name text' } }); const descriptionInput = wrapper - .find('textarea[aria-describedby="detectionEngineStepAboutRuleDescription"]') - .at(0); - const nextButton = wrapper.find('button[data-test-subj="about-continue"]').at(0); - nextButton.simulate('click'); + .find('[data-test-subj="detectionEngineStepAboutRuleDescription"] textarea') + .first(); + wrapper.find('button[data-test-subj="about-continue"]').first().simulate('click'); expect( - wrapper.find('input[aria-describedby="detectionEngineStepAboutRuleName"]').at(0).props().value + wrapper.find('[data-test-subj="detectionEngineStepAboutRuleName"] input').first().props() + .value ).toEqual('Test name text'); expect(descriptionInput.props().value).toEqual(''); expect( wrapper - .find('EuiFormRow[data-test-subj="detectionEngineStepAboutRuleDescription"] label') - .at(0) + .find('[data-test-subj="detectionEngineStepAboutRuleDescription"] label') + .first() .hasClass('euiFormLabel-isInvalid') ).toBeTruthy(); expect( wrapper - .find('EuiFormRow[data-test-subj="detectionEngineStepAboutRuleDescription"] EuiTextArea') - .at(0) + .find('[data-test-subj="detectionEngineStepAboutRuleDescription"] EuiTextArea') + .first() .prop('isInvalid') ).toBeTruthy(); }); @@ -101,39 +103,40 @@ describe('StepAboutRuleComponent', () => { ); - const descriptionInput = wrapper - .find('textarea[aria-describedby="detectionEngineStepAboutRuleDescription"]') - .at(0); - descriptionInput.simulate('change', { target: { value: 'Test description text' } }); + wrapper + .find('[data-test-subj="detectionEngineStepAboutRuleDescription"] textarea') + .first() + .simulate('change', { target: { value: 'Test description text' } }); const nameInput = wrapper - .find('input[aria-describedby="detectionEngineStepAboutRuleName"]') - .at(0); - const nextButton = wrapper.find('button[data-test-subj="about-continue"]').at(0); - nextButton.simulate('click'); + .find('[data-test-subj="detectionEngineStepAboutRuleName"] input') + .first(); + + wrapper.find('button[data-test-subj="about-continue"]').first().simulate('click'); expect( wrapper - .find('textarea[aria-describedby="detectionEngineStepAboutRuleDescription"]') - .at(0) + .find('[data-test-subj="detectionEngineStepAboutRuleDescription"] textarea') + .first() .props().value ).toEqual('Test description text'); expect(nameInput.props().value).toEqual(''); expect( wrapper - .find('EuiFormRow[data-test-subj="detectionEngineStepAboutRuleName"] label') - .at(0) + .find('[data-test-subj="detectionEngineStepAboutRuleName"] label') + .first() .hasClass('euiFormLabel-isInvalid') ).toBeTruthy(); expect( wrapper - .find('EuiFormRow[data-test-subj="detectionEngineStepAboutRuleName"] EuiFieldText') - .at(0) + .find('[data-test-subj="detectionEngineStepAboutRuleName"] EuiFieldText') + .first() .prop('isInvalid') ).toBeTruthy(); }); - test('it allows user to click continue if "name" and "description" are defined', () => { + test('it allows user to click continue if "name" and "description" are defined', async () => { + const stepDataMock = jest.fn(); const wrapper = mount( { isReadOnlyView={false} isLoading={false} setForm={jest.fn()} - setStepData={jest.fn()} + setStepData={stepDataMock} /> ); - const descriptionInput = wrapper - .find('textarea[aria-describedby="detectionEngineStepAboutRuleDescription"]') - .at(0); - descriptionInput.simulate('change', { target: { value: 'Test description text' } }); + wrapper + .find('[data-test-subj="detectionEngineStepAboutRuleDescription"] textarea') + .first() + .simulate('change', { target: { value: 'Test description text' } }); + + wrapper + .find('[data-test-subj="detectionEngineStepAboutRuleName"] input') + .first() + .simulate('change', { target: { value: 'Test name text' } }); + + wrapper.find('button[data-test-subj="about-continue"]').first().simulate('click').update(); + await wait(); + const expected: Omit = { + description: 'Test description text', + falsePositives: [''], + name: 'Test name text', + note: '', + references: [''], + riskScore: 50, + severity: 'low', + tags: [], + threat: [ + { + framework: 'MITRE ATT&CK', + tactic: { id: 'none', name: 'none', reference: 'none' }, + technique: [], + }, + ], + }; + expect(stepDataMock.mock.calls[1][1]).toEqual(expected); + }); - const nameInput = wrapper - .find('input[aria-describedby="detectionEngineStepAboutRuleName"]') - .at(0); - nameInput.simulate('change', { target: { value: 'Test name text' } }); + test('it allows user to set the risk score as a number (and not a string)', async () => { + const stepDataMock = jest.fn(); + const wrapper = mount( + + + + ); - const nextButton = wrapper.find('button[data-test-subj="about-continue"]').at(0); - nextButton.simulate('click'); + wrapper + .find('[data-test-subj="detectionEngineStepAboutRuleName"] input') + .first() + .simulate('change', { target: { value: 'Test name text' } }); + + wrapper + .find('[data-test-subj="detectionEngineStepAboutRuleDescription"] textarea') + .first() + .simulate('change', { target: { value: 'Test description text' } }); + + wrapper + .find('[data-test-subj="detectionEngineStepAboutRuleRiskScore"] input') + .first() + .simulate('change', { target: { value: '80' } }); + + wrapper.find('[data-test-subj="about-continue"]').first().simulate('click').update(); + await wait(); + const expected: Omit = { + description: 'Test description text', + falsePositives: [''], + name: 'Test name text', + note: '', + references: [''], + riskScore: 80, + severity: 'low', + tags: [], + threat: [ + { + framework: 'MITRE ATT&CK', + tactic: { id: 'none', name: 'none', reference: 'none' }, + technique: [], + }, + ], + }; + expect(stepDataMock.mock.calls[1][1]).toEqual(expected); }); }); diff --git a/x-pack/plugins/security_solution/public/alerts/components/rules/step_about_rule/schema.tsx b/x-pack/plugins/security_solution/public/alerts/components/rules/step_about_rule/schema.tsx index 42ffab10ff469..59ecebaeb9e4e 100644 --- a/x-pack/plugins/security_solution/public/alerts/components/rules/step_about_rule/schema.tsx +++ b/x-pack/plugins/security_solution/public/alerts/components/rules/step_about_rule/schema.tsx @@ -87,6 +87,7 @@ export const schema: FormSchema = { }, riskScore: { type: FIELD_TYPES.RANGE, + serializer: (input: string) => Number(input), label: i18n.translate( 'xpack.securitySolution.detectionEngine.createRule.stepAboutRule.fieldRiskScoreLabel', { diff --git a/x-pack/plugins/security_solution/public/cases/components/add_comment/index.tsx b/x-pack/plugins/security_solution/public/cases/components/add_comment/index.tsx index a57fae8081bea..a830b299d655b 100644 --- a/x-pack/plugins/security_solution/public/cases/components/add_comment/index.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/add_comment/index.tsx @@ -8,6 +8,7 @@ import { EuiButton, EuiLoadingSpinner } from '@elastic/eui'; import React, { useCallback, useEffect } from 'react'; import styled from 'styled-components'; +import { useDispatch } from 'react-redux'; import { CommentRequest } from '../../../../../case/common/api'; import { usePostComment } from '../../containers/use_post_comment'; import { Case } from '../../containers/types'; @@ -18,6 +19,12 @@ import { Form, useForm, UseField } from '../../../shared_imports'; import * as i18n from './translations'; import { schema } from './schema'; +import { + dispatchUpdateTimeline, + queryTimelineById, +} from '../../../timelines/components/open_timeline/helpers'; +import { updateIsLoading as dispatchUpdateIsLoading } from '../../../timelines/store/timeline/actions'; +import { useApolloClient } from '../../../common/utils/apollo_context'; const MySpinner = styled(EuiLoadingSpinner)` position: absolute; @@ -46,6 +53,8 @@ export const AddComment = React.memo( options: { stripEmptyFields: false }, schema, }); + const dispatch = useDispatch(); + const apolloClient = useApolloClient(); const { handleCursorChange, handleOnTimelineChange } = useInsertTimeline( form, 'comment' @@ -62,6 +71,28 @@ export const AddComment = React.memo( // eslint-disable-next-line react-hooks/exhaustive-deps }, [insertQuote]); + const handleTimelineClick = useCallback( + (timelineId: string) => { + queryTimelineById({ + apolloClient, + timelineId, + updateIsLoading: ({ + id: currentTimelineId, + isLoading: isLoadingTimeline, + }: { + id: string; + isLoading: boolean; + }) => + dispatch( + dispatchUpdateIsLoading({ id: currentTimelineId, isLoading: isLoadingTimeline }) + ), + updateTimeline: dispatchUpdateTimeline(dispatch), + }); + }, + // eslint-disable-next-line react-hooks/exhaustive-deps + [apolloClient] + ); + const onSubmit = useCallback(async () => { const { isValid, data } = await form.submit(); if (isValid) { @@ -86,6 +117,7 @@ export const AddComment = React.memo( dataTestSubj: 'add-comment', placeholder: i18n.ADD_COMMENT_HELP_TEXT, onCursorPositionUpdate: handleCursorChange, + onClickTimeline: handleTimelineClick, bottomRightContent: ( export const getCasesColumns = ( actions: Array>, - filterStatus: string -): CasesColumns[] => [ - { - name: i18n.NAME, - render: (theCase: Case) => { - if (theCase.id != null && theCase.title != null) { - const caseDetailsLinkComponent = ( - - {theCase.title} - - ); - return theCase.status === 'open' ? ( - caseDetailsLinkComponent - ) : ( - <> - + filterStatus: string, + isModal: boolean +): CasesColumns[] => { + const columns = [ + { + name: i18n.NAME, + render: (theCase: Case) => { + if (theCase.id != null && theCase.title != null) { + const caseDetailsLinkComponent = !isModal ? ( + + {theCase.title} + + ) : ( + {theCase.title} + ); + return theCase.status === 'open' ? ( + caseDetailsLinkComponent + ) : ( + <> {caseDetailsLinkComponent} - {i18n.CLOSED} - - - ); - } - return getEmptyTagValue(); + + {i18n.CLOSED} + + + ); + } + return getEmptyTagValue(); + }, }, - }, - { - field: 'createdBy', - name: i18n.REPORTER, - render: (createdBy: Case['createdBy']) => { - if (createdBy != null) { - return ( - <> - - - {createdBy.fullName ? createdBy.fullName : createdBy.username ?? ''} - - - ); - } - return getEmptyTagValue(); + { + field: 'createdBy', + name: i18n.REPORTER, + render: (createdBy: Case['createdBy']) => { + if (createdBy != null) { + return ( + <> + + + {createdBy.fullName ? createdBy.fullName : createdBy.username ?? ''} + + + ); + } + return getEmptyTagValue(); + }, + }, + { + field: 'tags', + name: i18n.TAGS, + render: (tags: Case['tags']) => { + if (tags != null && tags.length > 0) { + return ( + + {tags.map((tag: string, i: number) => ( + + {tag} + + ))} + + ); + } + return getEmptyTagValue(); + }, + truncateText: true, }, - }, - { - field: 'tags', - name: i18n.TAGS, - render: (tags: Case['tags']) => { - if (tags != null && tags.length > 0) { - return ( - - {tags.map((tag: string, i: number) => ( - - {tag} - - ))} - - ); - } - return getEmptyTagValue(); + { + align: 'right' as HorizontalAlignment, + field: 'totalComment', + name: i18n.COMMENTS, + sortable: true, + render: (totalComment: Case['totalComment']) => + totalComment != null + ? renderStringField(`${totalComment}`, `case-table-column-commentCount`) + : getEmptyTagValue(), }, - truncateText: true, - }, - { - align: 'right', - field: 'totalComment', - name: i18n.COMMENTS, - sortable: true, - render: (totalComment: Case['totalComment']) => - totalComment != null - ? renderStringField(`${totalComment}`, `case-table-column-commentCount`) - : getEmptyTagValue(), - }, - filterStatus === 'open' - ? { - field: 'createdAt', - name: i18n.OPENED_ON, - sortable: true, - render: (createdAt: Case['createdAt']) => { - if (createdAt != null) { - return ( - - - - ); - } - return getEmptyTagValue(); - }, - } - : { - field: 'closedAt', - name: i18n.CLOSED_ON, - sortable: true, - render: (closedAt: Case['closedAt']) => { - if (closedAt != null) { - return ( - - - - ); - } - return getEmptyTagValue(); + filterStatus === 'open' + ? { + field: 'createdAt', + name: i18n.OPENED_ON, + sortable: true, + render: (createdAt: Case['createdAt']) => { + if (createdAt != null) { + return ( + + + + ); + } + return getEmptyTagValue(); + }, + } + : { + field: 'closedAt', + name: i18n.CLOSED_ON, + sortable: true, + render: (closedAt: Case['closedAt']) => { + if (closedAt != null) { + return ( + + + + ); + } + return getEmptyTagValue(); + }, }, + { + name: i18n.EXTERNAL_INCIDENT, + render: (theCase: Case) => { + if (theCase.id != null) { + return ; + } + return getEmptyTagValue(); }, - { - name: i18n.EXTERNAL_INCIDENT, - render: (theCase: Case) => { - if (theCase.id != null) { - return ; - } - return getEmptyTagValue(); }, - }, - { - name: i18n.INCIDENT_MANAGEMENT_SYSTEM, - render: (theCase: Case) => { - if (theCase.externalService != null) { - return renderStringField( - `${theCase.externalService.connectorName}`, - `case-table-column-connector` - ); - } - return getEmptyTagValue(); + { + name: i18n.INCIDENT_MANAGEMENT_SYSTEM, + render: (theCase: Case) => { + if (theCase.externalService != null) { + return renderStringField( + `${theCase.externalService.connectorName}`, + `case-table-column-connector` + ); + } + return getEmptyTagValue(); + }, + }, + { + name: i18n.ACTIONS, + actions, }, - }, - { - name: i18n.ACTIONS, - actions, - }, -]; + ]; + if (isModal) { + columns.pop(); // remove actions if in modal + } + return columns; +}; interface Props { theCase: Case; diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx index e3f4fee15ce68..bbb96f433d3c8 100644 --- a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx @@ -151,8 +151,22 @@ describe('AllCases', () => { expect(column.find('.euiTableRowCell--hideForDesktop').text()).toEqual(columnName); expect(column.find('span').text()).toEqual(emptyTag); }; - getCasesColumns([], 'open').map((i, key) => i.name != null && checkIt(`${i.name}`, key)); + getCasesColumns([], 'open', false).map((i, key) => i.name != null && checkIt(`${i.name}`, key)); }); + + it('should not render case link or actions on modal=true', () => { + const wrapper = mount( + + + + ); + const checkIt = (columnName: string) => { + expect(columnName).not.toEqual(i18n.ACTIONS); + }; + getCasesColumns([], 'open', true).map((i, key) => i.name != null && checkIt(`${i.name}`)); + expect(wrapper.find(`a[data-test-subj="case-details-link"]`).exists()).toBeFalsy(); + }); + it('should tableHeaderSortButton AllCases', () => { const wrapper = mount( diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.tsx index 32a7c4078071e..d27f383fb94e3 100644 --- a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.tsx @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ - +/* eslint-disable react-hooks/exhaustive-deps */ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { EuiBasicTable, @@ -72,7 +72,6 @@ const ProgressLoader = styled(EuiProgress)` z-index: ${theme.eui.euiZHeader}; `} `; - const getSortField = (field: string): SortFieldCase => { if (field === SortFieldCase.createdAt) { return SortFieldCase.createdAt; @@ -83,368 +82,373 @@ const getSortField = (field: string): SortFieldCase => { }; interface AllCasesProps { + onRowClick?: (id: string) => void; + isModal?: boolean; userCanCrud: boolean; } -export const AllCases = React.memo(({ userCanCrud }) => { - const urlSearch = useGetUrlSearch(navTabs.case); - const { actionLicense } = useGetActionLicense(); - const { - countClosedCases, - countOpenCases, - isLoading: isCasesStatusLoading, - fetchCasesStatus, - } = useGetCasesStatus(); - const { - data, - dispatchUpdateCaseProperty, - filterOptions, - loading, - queryParams, - selectedCases, - refetchCases, - setFilters, - setQueryParams, - setSelectedCases, - } = useGetCases(); +export const AllCases = React.memo( + ({ onRowClick = () => {}, isModal = false, userCanCrud }) => { + const urlSearch = useGetUrlSearch(navTabs.case); + const { actionLicense } = useGetActionLicense(); + const { + countClosedCases, + countOpenCases, + isLoading: isCasesStatusLoading, + fetchCasesStatus, + } = useGetCasesStatus(); + const { + data, + dispatchUpdateCaseProperty, + filterOptions, + loading, + queryParams, + selectedCases, + refetchCases, + setFilters, + setQueryParams, + setSelectedCases, + } = useGetCases(); - // Delete case - const { - dispatchResetIsDeleted, - handleOnDeleteConfirm, - handleToggleModal, - isLoading: isDeleting, - isDeleted, - isDisplayConfirmDeleteModal, - } = useDeleteCases(); - - // Update case - const { - dispatchResetIsUpdated, - isLoading: isUpdating, - isUpdated, - updateBulkStatus, - } = useUpdateCases(); - const [deleteThisCase, setDeleteThisCase] = useState({ - title: '', - id: '', - }); - const [deleteBulk, setDeleteBulk] = useState([]); - const filterRefetch = useRef<() => void>(); - const setFilterRefetch = useCallback( - (refetchFilter: () => void) => { - filterRefetch.current = refetchFilter; - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [filterRefetch.current] - ); - const refreshCases = useCallback( - (dataRefresh = true) => { - if (dataRefresh) refetchCases(); - fetchCasesStatus(); - setSelectedCases([]); - setDeleteBulk([]); - if (filterRefetch.current != null) { - filterRefetch.current(); - } - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [filterOptions, queryParams, filterRefetch.current] - ); + // Delete case + const { + dispatchResetIsDeleted, + handleOnDeleteConfirm, + handleToggleModal, + isLoading: isDeleting, + isDeleted, + isDisplayConfirmDeleteModal, + } = useDeleteCases(); - useEffect(() => { - if (isDeleted) { - refreshCases(); - dispatchResetIsDeleted(); - } - if (isUpdated) { - refreshCases(); - dispatchResetIsUpdated(); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [isDeleted, isUpdated]); - const confirmDeleteModal = useMemo( - () => ( - 0} - onCancel={handleToggleModal} - onConfirm={handleOnDeleteConfirm.bind( - null, - deleteBulk.length > 0 ? deleteBulk : [deleteThisCase] - )} - /> - ), - // eslint-disable-next-line react-hooks/exhaustive-deps - [deleteBulk, deleteThisCase, isDisplayConfirmDeleteModal] - ); + // Update case + const { + dispatchResetIsUpdated, + isLoading: isUpdating, + isUpdated, + updateBulkStatus, + } = useUpdateCases(); + const [deleteThisCase, setDeleteThisCase] = useState({ + title: '', + id: '', + }); + const [deleteBulk, setDeleteBulk] = useState([]); + const filterRefetch = useRef<() => void>(); + const setFilterRefetch = useCallback( + (refetchFilter: () => void) => { + filterRefetch.current = refetchFilter; + }, + [filterRefetch.current] + ); + const refreshCases = useCallback( + (dataRefresh = true) => { + if (dataRefresh) refetchCases(); + fetchCasesStatus(); + setSelectedCases([]); + setDeleteBulk([]); + if (filterRefetch.current != null) { + filterRefetch.current(); + } + }, + [filterOptions, queryParams, filterRefetch.current] + ); - const toggleDeleteModal = useCallback((deleteCase: Case) => { - handleToggleModal(); - setDeleteThisCase(deleteCase); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); + useEffect(() => { + if (isDeleted) { + refreshCases(); + dispatchResetIsDeleted(); + } + if (isUpdated) { + refreshCases(); + dispatchResetIsUpdated(); + } + }, [isDeleted, isUpdated]); + const confirmDeleteModal = useMemo( + () => ( + 0} + onCancel={handleToggleModal} + onConfirm={handleOnDeleteConfirm.bind( + null, + deleteBulk.length > 0 ? deleteBulk : [deleteThisCase] + )} + /> + ), + [deleteBulk, deleteThisCase, isDisplayConfirmDeleteModal] + ); - const toggleBulkDeleteModal = useCallback( - (caseIds: string[]) => { + const toggleDeleteModal = useCallback((deleteCase: Case) => { handleToggleModal(); - if (caseIds.length === 1) { - const singleCase = selectedCases.find((theCase) => theCase.id === caseIds[0]); - if (singleCase) { - return setDeleteThisCase({ id: singleCase.id, title: singleCase.title }); + setDeleteThisCase(deleteCase); + }, []); + + const toggleBulkDeleteModal = useCallback( + (caseIds: string[]) => { + handleToggleModal(); + if (caseIds.length === 1) { + const singleCase = selectedCases.find((theCase) => theCase.id === caseIds[0]); + if (singleCase) { + return setDeleteThisCase({ id: singleCase.id, title: singleCase.title }); + } } - } - const convertToDeleteCases: DeleteCase[] = caseIds.map((id) => ({ id })); - setDeleteBulk(convertToDeleteCases); - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [selectedCases] - ); + const convertToDeleteCases: DeleteCase[] = caseIds.map((id) => ({ id })); + setDeleteBulk(convertToDeleteCases); + }, + [selectedCases] + ); - const handleUpdateCaseStatus = useCallback( - (status: string) => { - updateBulkStatus(selectedCases, status); - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [selectedCases] - ); + const handleUpdateCaseStatus = useCallback( + (status: string) => { + updateBulkStatus(selectedCases, status); + }, + [selectedCases] + ); - const selectedCaseIds = useMemo( - (): string[] => selectedCases.map((caseObj: Case) => caseObj.id), - [selectedCases] - ); + const selectedCaseIds = useMemo( + (): string[] => selectedCases.map((caseObj: Case) => caseObj.id), + [selectedCases] + ); - const getBulkItemsPopoverContent = useCallback( - (closePopover: () => void) => ( - - ), - // eslint-disable-next-line react-hooks/exhaustive-deps - [selectedCaseIds, filterOptions.status, toggleBulkDeleteModal] - ); - const handleDispatchUpdate = useCallback( - (args: Omit) => { - dispatchUpdateCaseProperty({ ...args, refetchCasesStatus: fetchCasesStatus }); - }, - [dispatchUpdateCaseProperty, fetchCasesStatus] - ); + const getBulkItemsPopoverContent = useCallback( + (closePopover: () => void) => ( + + ), + [selectedCaseIds, filterOptions.status, toggleBulkDeleteModal] + ); + const handleDispatchUpdate = useCallback( + (args: Omit) => { + dispatchUpdateCaseProperty({ ...args, refetchCasesStatus: fetchCasesStatus }); + }, + [dispatchUpdateCaseProperty, fetchCasesStatus] + ); - const actions = useMemo( - () => - getActions({ - caseStatus: filterOptions.status, - deleteCaseOnClick: toggleDeleteModal, - dispatchUpdate: handleDispatchUpdate, - }), - [filterOptions.status, toggleDeleteModal, handleDispatchUpdate] - ); + const actions = useMemo( + () => + getActions({ + caseStatus: filterOptions.status, + deleteCaseOnClick: toggleDeleteModal, + dispatchUpdate: handleDispatchUpdate, + }), + [filterOptions.status, toggleDeleteModal, handleDispatchUpdate] + ); - const actionsErrors = useMemo(() => getActionLicenseError(actionLicense), [actionLicense]); + const actionsErrors = useMemo(() => getActionLicenseError(actionLicense), [actionLicense]); - const tableOnChangeCallback = useCallback( - ({ page, sort }: EuiBasicTableOnChange) => { - let newQueryParams = queryParams; - if (sort) { - newQueryParams = { - ...newQueryParams, - sortField: getSortField(sort.field), - sortOrder: sort.direction, - }; - } - if (page) { - newQueryParams = { - ...newQueryParams, - page: page.index + 1, - perPage: page.size, - }; - } - setQueryParams(newQueryParams); - refreshCases(false); - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [queryParams] - ); + const tableOnChangeCallback = useCallback( + ({ page, sort }: EuiBasicTableOnChange) => { + let newQueryParams = queryParams; + if (sort) { + newQueryParams = { + ...newQueryParams, + sortField: getSortField(sort.field), + sortOrder: sort.direction, + }; + } + if (page) { + newQueryParams = { + ...newQueryParams, + page: page.index + 1, + perPage: page.size, + }; + } + setQueryParams(newQueryParams); + refreshCases(false); + }, + [queryParams] + ); - const onFilterChangedCallback = useCallback( - (newFilterOptions: Partial) => { - if (newFilterOptions.status && newFilterOptions.status === 'closed') { - setQueryParams({ sortField: SortFieldCase.closedAt }); - } else if (newFilterOptions.status && newFilterOptions.status === 'open') { - setQueryParams({ sortField: SortFieldCase.createdAt }); - } - setFilters(newFilterOptions); - refreshCases(false); - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [filterOptions, queryParams] - ); + const onFilterChangedCallback = useCallback( + (newFilterOptions: Partial) => { + if (newFilterOptions.status && newFilterOptions.status === 'closed') { + setQueryParams({ sortField: SortFieldCase.closedAt }); + } else if (newFilterOptions.status && newFilterOptions.status === 'open') { + setQueryParams({ sortField: SortFieldCase.createdAt }); + } + setFilters(newFilterOptions); + refreshCases(false); + }, + [filterOptions, queryParams] + ); - const memoizedGetCasesColumns = useMemo( - () => getCasesColumns(userCanCrud ? actions : [], filterOptions.status), - [actions, filterOptions.status, userCanCrud] - ); - const memoizedPagination = useMemo( - () => ({ - pageIndex: queryParams.page - 1, - pageSize: queryParams.perPage, - totalItemCount: data.total, - pageSizeOptions: [5, 10, 15, 20, 25], - }), - [data, queryParams] - ); + const memoizedGetCasesColumns = useMemo( + () => getCasesColumns(userCanCrud ? actions : [], filterOptions.status, isModal), + [actions, filterOptions.status, userCanCrud, isModal] + ); + const memoizedPagination = useMemo( + () => ({ + pageIndex: queryParams.page - 1, + pageSize: queryParams.perPage, + totalItemCount: data.total, + pageSizeOptions: [5, 10, 15, 20, 25], + }), + [data, queryParams] + ); - const sorting: EuiTableSortingType = { - sort: { field: queryParams.sortField, direction: queryParams.sortOrder }, - }; - const euiBasicTableSelectionProps = useMemo>( - () => ({ onSelectionChange: setSelectedCases }), - // eslint-disable-next-line react-hooks/exhaustive-deps - [selectedCases] - ); - const isCasesLoading = useMemo( - () => loading.indexOf('cases') > -1 || loading.indexOf('caseUpdate') > -1, - [loading] - ); - const isDataEmpty = useMemo(() => data.total === 0, [data]); + const sorting: EuiTableSortingType = { + sort: { field: queryParams.sortField, direction: queryParams.sortOrder }, + }; + const euiBasicTableSelectionProps = useMemo>( + () => ({ onSelectionChange: setSelectedCases }), + [selectedCases] + ); + const isCasesLoading = useMemo( + () => loading.indexOf('cases') > -1 || loading.indexOf('caseUpdate') > -1, + [loading] + ); + const isDataEmpty = useMemo(() => data.total === 0, [data]); - return ( - <> - {!isEmpty(actionsErrors) && ( - - )} - - - - - - - - - - } - titleTooltip={!isEmpty(actionsErrors) ? actionsErrors[0].title : ''} - urlSearch={urlSearch} - /> - - - - {i18n.CREATE_TITLE} - - - - - {(isCasesLoading || isDeleting || isUpdating) && !isDataEmpty && ( - - )} - - - {isCasesLoading && isDataEmpty ? ( -
- -
- ) : ( -
- - - - - {i18n.SHOWING_CASES(data.total ?? 0)} - - - - - {i18n.SHOWING_SELECTED_CASES(selectedCases.length)} - - {userCanCrud && ( - - {i18n.BULK_ACTIONS} - - )} - - {i18n.REFRESH} - - - - - {i18n.NO_CASES}} - titleSize="xs" - body={i18n.NO_CASES_BODY} - actions={ - - {i18n.ADD_NEW_CASE} - - } + const TableWrap = useMemo(() => (isModal ? 'span' : Panel), [isModal]); + return ( + <> + {!isEmpty(actionsErrors) && ( + + )} + {!isModal && ( + + + + + + + - } - onChange={tableOnChangeCallback} - pagination={memoizedPagination} - selection={userCanCrud ? euiBasicTableSelectionProps : {}} - sorting={sorting} - /> -
+ + + } + titleTooltip={!isEmpty(actionsErrors) ? actionsErrors[0].title : ''} + urlSearch={urlSearch} + /> + + + + {i18n.CREATE_TITLE} + + + + + )} + {(isCasesLoading || isDeleting || isUpdating) && !isDataEmpty && ( + )} -
- {confirmDeleteModal} - - ); -}); + + + {isCasesLoading && isDataEmpty ? ( +
+ +
+ ) : ( +
+ + + + + {i18n.SHOWING_CASES(data.total ?? 0)} + + + {!isModal && ( + + + {i18n.SHOWING_SELECTED_CASES(selectedCases.length)} + + {userCanCrud && ( + + {i18n.BULK_ACTIONS} + + )} + + {i18n.REFRESH} + + + )} + + + {i18n.NO_CASES}} + titleSize="xs" + body={i18n.NO_CASES_BODY} + actions={ + + {i18n.ADD_NEW_CASE} + + } + /> + } + onChange={tableOnChangeCallback} + pagination={memoizedPagination} + rowProps={(item) => + isModal + ? { + onClick: () => onRowClick(item.id), + } + : {} + } + selection={userCanCrud && !isModal ? euiBasicTableSelectionProps : undefined} + sorting={sorting} + /> +
+ )} +
+ {confirmDeleteModal} + + ); + } +); AllCases.displayName = 'AllCases'; diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.test.tsx new file mode 100644 index 0000000000000..a24cb6a87de74 --- /dev/null +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.test.tsx @@ -0,0 +1,140 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { mount } from 'enzyme'; +import React from 'react'; +import { AllCasesModal } from '.'; +import { TestProviders } from '../../../common/mock'; + +import { useGetCasesMockState, basicCaseId } from '../../containers/mock'; +import { useDeleteCases } from '../../containers/use_delete_cases'; +import { useGetCases } from '../../containers/use_get_cases'; +import { useGetCasesStatus } from '../../containers/use_get_cases_status'; +import { useUpdateCases } from '../../containers/use_bulk_update_case'; +import { EuiTableRow } from '@elastic/eui'; + +jest.mock('../../containers/use_bulk_update_case'); +jest.mock('../../containers/use_delete_cases'); +jest.mock('../../containers/use_get_cases'); +jest.mock('../../containers/use_get_cases_status'); + +const useDeleteCasesMock = useDeleteCases as jest.Mock; +const useGetCasesMock = useGetCases as jest.Mock; +const useGetCasesStatusMock = useGetCasesStatus as jest.Mock; +const useUpdateCasesMock = useUpdateCases as jest.Mock; +jest.mock('../../../common/lib/kibana', () => { + const originalModule = jest.requireActual('../../../common/lib/kibana'); + return { + ...originalModule, + useGetUserSavedObjectPermissions: jest.fn(), + }; +}); + +const onCloseCaseModal = jest.fn(); +const onRowClick = jest.fn(); +const defaultProps = { + onCloseCaseModal, + onRowClick, + showCaseModal: true, +}; +describe('AllCasesModal', () => { + const dispatchResetIsDeleted = jest.fn(); + const dispatchResetIsUpdated = jest.fn(); + const dispatchUpdateCaseProperty = jest.fn(); + const handleOnDeleteConfirm = jest.fn(); + const handleToggleModal = jest.fn(); + const refetchCases = jest.fn(); + const setFilters = jest.fn(); + const setQueryParams = jest.fn(); + const setSelectedCases = jest.fn(); + const updateBulkStatus = jest.fn(); + const fetchCasesStatus = jest.fn(); + + const defaultGetCases = { + ...useGetCasesMockState, + dispatchUpdateCaseProperty, + refetchCases, + setFilters, + setQueryParams, + setSelectedCases, + }; + const defaultDeleteCases = { + dispatchResetIsDeleted, + handleOnDeleteConfirm, + handleToggleModal, + isDeleted: false, + isDisplayConfirmDeleteModal: false, + isLoading: false, + }; + const defaultCasesStatus = { + countClosedCases: 0, + countOpenCases: 5, + fetchCasesStatus, + isError: false, + isLoading: true, + }; + const defaultUpdateCases = { + isUpdated: false, + isLoading: false, + isError: false, + dispatchResetIsUpdated, + updateBulkStatus, + }; + /* eslint-disable no-console */ + // Silence until enzyme fixed to use ReactTestUtils.act() + const originalError = console.error; + beforeAll(() => { + console.error = jest.fn(); + }); + afterAll(() => { + console.error = originalError; + }); + /* eslint-enable no-console */ + beforeEach(() => { + jest.resetAllMocks(); + useUpdateCasesMock.mockImplementation(() => defaultUpdateCases); + useGetCasesMock.mockImplementation(() => defaultGetCases); + useDeleteCasesMock.mockImplementation(() => defaultDeleteCases); + useGetCasesStatusMock.mockImplementation(() => defaultCasesStatus); + }); + + it('renders with unselectable rows', () => { + const wrapper = mount( + + + + ); + expect(wrapper.find(`[data-test-subj='all-cases-modal']`).exists()).toBeTruthy(); + expect(wrapper.find(EuiTableRow).first().prop('isSelectable')).toBeFalsy(); + }); + it('does not render modal if showCaseModal: false', () => { + const wrapper = mount( + + + + ); + expect(wrapper.find(`[data-test-subj='all-cases-modal']`).exists()).toBeFalsy(); + }); + it('onRowClick called when row is clicked', () => { + const wrapper = mount( + + + + ); + const firstRow = wrapper.find(EuiTableRow).first(); + firstRow.simulate('click'); + expect(onRowClick.mock.calls[0][0]).toEqual(basicCaseId); + }); + it('Closing modal calls onCloseCaseModal', () => { + const wrapper = mount( + + + + ); + const modalClose = wrapper.find('.euiModal__closeIcon').first(); + modalClose.simulate('click'); + expect(onCloseCaseModal).toBeCalled(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.tsx new file mode 100644 index 0000000000000..d2ca0f0cd02ee --- /dev/null +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.tsx @@ -0,0 +1,56 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { + EuiModal, + EuiModalBody, + EuiModalHeader, + EuiModalHeaderTitle, + EuiOverlayMask, +} from '@elastic/eui'; +import { useGetUserSavedObjectPermissions } from '../../../common/lib/kibana'; +import { AllCases } from '../all_cases'; +import * as i18n from './translations'; + +interface AllCasesModalProps { + onCloseCaseModal: () => void; + showCaseModal: boolean; + onRowClick: (id: string) => void; +} + +export const AllCasesModalComponent = ({ + onCloseCaseModal, + onRowClick, + showCaseModal, +}: AllCasesModalProps) => { + const userPermissions = useGetUserSavedObjectPermissions(); + let modal; + if (showCaseModal) { + modal = ( + + + + {i18n.SELECT_CASE_TITLE} + + + + + + + ); + } + + return <>{modal}; +}; + +export const AllCasesModal = React.memo(AllCasesModalComponent); + +AllCasesModal.displayName = 'AllCasesModal'; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/find_rules_statuses_schema.ts b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/translations.ts similarity index 57% rename from x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/find_rules_statuses_schema.ts rename to x-pack/plugins/security_solution/public/cases/components/all_cases_modal/translations.ts index 5b8661e69e206..e0f84d8541424 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/find_rules_statuses_schema.ts +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/translations.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import Joi from 'joi'; - -export const findRulesStatusesSchema = Joi.object({ - ids: Joi.array().items(Joi.string()), +import { i18n } from '@kbn/i18n'; +export const SELECT_CASE_TITLE = i18n.translate('xpack.securitySolution.case.caseModal.title', { + defaultMessage: 'Select case to attach timeline', }); diff --git a/x-pack/plugins/security_solution/public/cases/pages/case_details.tsx b/x-pack/plugins/security_solution/public/cases/pages/case_details.tsx index 5dfe12179b990..780de303c02d3 100644 --- a/x-pack/plugins/security_solution/public/cases/pages/case_details.tsx +++ b/x-pack/plugins/security_solution/public/cases/pages/case_details.tsx @@ -10,7 +10,6 @@ import { useParams, Redirect } from 'react-router-dom'; import { WrapperPage } from '../../common/components/wrapper_page'; import { useGetUrlSearch } from '../../common/components/navigation/use_get_url_search'; import { useGetUserSavedObjectPermissions } from '../../common/lib/kibana'; -import { SpyRoute } from '../../common/utils/route/spy_routes'; import { getCaseUrl } from '../../common/components/link_to'; import { navTabs } from '../../app/home/home_navigations'; import { CaseView } from '../components/case_view'; @@ -36,7 +35,6 @@ export const CaseDetailsPage = React.memo(() => { )} - ) : null; }); diff --git a/x-pack/plugins/security_solution/public/common/components/matrix_histogram/__snapshots__/index.test.tsx.snap b/x-pack/plugins/security_solution/public/common/components/matrix_histogram/__snapshots__/index.test.tsx.snap deleted file mode 100644 index c0e0988168384..0000000000000 --- a/x-pack/plugins/security_solution/public/common/components/matrix_histogram/__snapshots__/index.test.tsx.snap +++ /dev/null @@ -1,5 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Matrix Histogram Component not initial load it renders no MatrixLoader 1`] = `"
"`; - -exports[`Matrix Histogram Component on initial load it renders MatrixLoader 1`] = `"
"`; diff --git a/x-pack/plugins/security_solution/public/common/components/matrix_histogram/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/matrix_histogram/index.test.tsx index b45207ab47c7a..52a97e26550ce 100644 --- a/x-pack/plugins/security_solution/public/common/components/matrix_histogram/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/matrix_histogram/index.test.tsx @@ -82,7 +82,6 @@ describe('Matrix Histogram Component', () => { }); describe('on initial load', () => { test('it renders MatrixLoader', () => { - expect(wrapper.html()).toMatchSnapshot(); expect(wrapper.find('MatrixLoader').exists()).toBe(true); }); }); @@ -117,7 +116,6 @@ describe('Matrix Histogram Component', () => { wrapper.update(); }); test('it renders no MatrixLoader', () => { - expect(wrapper.html()).toMatchSnapshot(); expect(wrapper.find(`MatrixLoader`).exists()).toBe(false); }); diff --git a/x-pack/plugins/security_solution/public/common/components/paginated_table/__snapshots__/index.test.tsx.snap b/x-pack/plugins/security_solution/public/common/components/paginated_table/__snapshots__/index.test.tsx.snap index a2c7e72e51a9c..26775608637c0 100644 --- a/x-pack/plugins/security_solution/public/common/components/paginated_table/__snapshots__/index.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/common/components/paginated_table/__snapshots__/index.test.tsx.snap @@ -115,32 +115,28 @@ exports[`Paginated Table Component rendering it renders the default load more ta }, "euiCardSpacing": "16px", "euiCheckBoxSize": "16px", - "euiCodeBlockAdditionBackgroundColor": "#144212", - "euiCodeBlockAdditionColor": "#e6e1dc", - "euiCodeBlockAttributeColor": "#80cbbf", + "euiCodeBlockAdditionColor": "#54b399", + "euiCodeBlockAttributeColor": "inherit", "euiCodeBlockBackgroundColor": "#25262e", - "euiCodeBlockBuiltInColor": "#0086b3", "euiCodeBlockColor": "#dfe5ef", - "euiCodeBlockCommentColor": "#656565", - "euiCodeBlockDeletionBackgroundColor": "#660000", - "euiCodeBlockDeletionColor": "#e6e1dc", - "euiCodeBlockFunctionTitleColor": "#75a5ff", - "euiCodeBlockKeywordColor": "#c792ea", - "euiCodeBlockMetaColor": "#75a5ff", - "euiCodeBlockNameColor": "#e06c75", - "euiCodeBlockNumberColor": "#f77669", - "euiCodeBlockParamsColor": "#eefff7", - "euiCodeBlockRegexpColor": "#009926", - "euiCodeBlockSectionColor": "#ffc66d", + "euiCodeBlockCommentColor": "#8d919a", + "euiCodeBlockDeletionColor": "#ff6666", + "euiCodeBlockFunctionTitleColor": "inherit", + "euiCodeBlockKeywordColor": "#a184c2", + "euiCodeBlockMetaColor": "#8d919a", + "euiCodeBlockNameColor": "#6092c0", + "euiCodeBlockNumberColor": "#54b399", + "euiCodeBlockParamsColor": "inherit", + "euiCodeBlockSectionColor": "#e7664c", "euiCodeBlockSelectedBackgroundColor": "inherit", - "euiCodeBlockSelectorClassColor": "#ffcb68", - "euiCodeBlockSelectorIdColor": "#f77669", - "euiCodeBlockSelectorTagColor": "#c792ea", - "euiCodeBlockStringColor": "#c3e88d", - "euiCodeBlockSymbolColor": "#c792ea", - "euiCodeBlockTagColor": "#abb2bf", - "euiCodeBlockTitleColor": "#75a5ff", - "euiCodeBlockTypeColor": "#da4939", + "euiCodeBlockSelectorClassColor": "inherit", + "euiCodeBlockSelectorIdColor": "inherit", + "euiCodeBlockSelectorTagColor": "inherit", + "euiCodeBlockStringColor": "#d77092", + "euiCodeBlockSymbolColor": "#e7664c", + "euiCodeBlockTagColor": "#6092c0", + "euiCodeBlockTitleColor": "#da8b45", + "euiCodeBlockTypeColor": "#6092c0", "euiCodeFontFamily": "'Roboto Mono', 'Consolas', 'Menlo', 'Courier', monospace", "euiCollapsibleNavGroupDarkBackgroundColor": "#131317", "euiCollapsibleNavGroupDarkHighContrastColor": "#1ba9f5", @@ -230,6 +226,7 @@ exports[`Paginated Table Component rendering it renders the default load more ta "warning": "#ffce7a", }, "euiFilePickerTallHeight": "128px", + "euiFlyoutBorder": "1px solid #343741", "euiFocusBackgroundColor": "#232635", "euiFocusRingAnimStartColor": "rgba(27, 169, 245, 0)", "euiFocusRingAnimStartSize": "6px", diff --git a/x-pack/plugins/security_solution/public/common/components/stat_items/__snapshots__/index.test.tsx.snap b/x-pack/plugins/security_solution/public/common/components/stat_items/__snapshots__/index.test.tsx.snap deleted file mode 100644 index 0d006d18cc49b..0000000000000 --- a/x-pack/plugins/security_solution/public/common/components/stat_items/__snapshots__/index.test.tsx.snap +++ /dev/null @@ -1,958 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Stat Items Component disable charts it renders the default widget 1`] = ` - - - - - -
- -
- -
- -
- -
- -
- HOSTS -
-
-
-
- -
- - - - - - - - -
-
-
-
- -
- - -
- -
- - -
- - -

- - - — - - - -

-
-
-
-
-
-
-
-
-
-
-
-
- -
- -
- -
- -
- - - - - -`; - -exports[`Stat Items Component disable charts it renders the default widget 2`] = ` - - - - - -
- -
- -
- -
- -
- -
- HOSTS -
-
-
-
- -
- - - - - - - - -
-
-
-
- -
- - -
- -
- 0 - - -
- - -

- - - — - - - -

-
-
-
-
-
-
-
-
-
-
-
-
- -
- -
- -
- -
- - - - - -`; - -exports[`Stat Items Component rendering kpis with charts it renders the default widget 1`] = ` - - - - -
- -
- -
- -
- -
- -
- UNIQUE_PRIVATE_IPS -
-
-
-
- -
- - - - - - - - -
-
-
-
- -
- - -
- -
- - -
- -
- -
- - - - -
- - -

- 1,714 - - Source -

-
-
-
-
-
-
- -
- - - - -
- -
- - -
- -
- -
- - - - -
- - -

- 2,359 - - Dest. -

-
-
-
-
-
-
- -
- - -
-
- -
-
- -
- - -
- -
- -
- - - - -
- -
- -
- - -
- -
- -
- -
-
-
- - -`; diff --git a/x-pack/plugins/security_solution/public/common/components/stat_items/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/stat_items/index.test.tsx index f46697834d0e3..d81d23438bfd2 100644 --- a/x-pack/plugins/security_solution/public/common/components/stat_items/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/stat_items/index.test.tsx @@ -91,10 +91,6 @@ describe('Stat Items Component', () => { ), ], ])('disable charts', (wrapper) => { - test('it renders the default widget', () => { - expect(wrapper).toMatchSnapshot(); - }); - test('should render titles', () => { expect(wrapper.find('[data-test-subj="stat-title"]')).toBeTruthy(); }); @@ -180,9 +176,6 @@ describe('Stat Items Component', () => { ); }); - test('it renders the default widget', () => { - expect(wrapper).toMatchSnapshot(); - }); test('should handle multiple titles', () => { expect(wrapper.find('[data-test-subj="stat-title"]')).toHaveLength(2); diff --git a/x-pack/plugins/security_solution/public/common/mock/global_state.ts b/x-pack/plugins/security_solution/public/common/mock/global_state.ts index 4af39ade70d25..3e84e4035e15e 100644 --- a/x-pack/plugins/security_solution/public/common/mock/global_state.ts +++ b/x-pack/plugins/security_solution/public/common/mock/global_state.ts @@ -229,6 +229,7 @@ export const mockGlobalState: State = { status: TimelineStatus.active, }, }, + insertTimeline: null, }, /** * These state's are wrapped in `Immutable`, but for compatibility with the overall app architecture, diff --git a/x-pack/plugins/security_solution/public/common/mock/index.ts b/x-pack/plugins/security_solution/public/common/mock/index.ts index bdad0ab1712ab..30eb4c63f40b8 100644 --- a/x-pack/plugins/security_solution/public/common/mock/index.ts +++ b/x-pack/plugins/security_solution/public/common/mock/index.ts @@ -15,3 +15,4 @@ export * from './test_providers'; export * from './utils'; export * from './mock_ecs'; export * from './timeline_results'; +export * from './kibana_react'; diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/configure_datasource.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/configure_datasource.tsx index ebcb46c3fb5b7..db5196bfc4eb4 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/configure_datasource.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/configure_datasource.tsx @@ -12,30 +12,21 @@ import { LinkToApp } from '../../../../../common/components/endpoint/link_to_app import { CustomConfigureDatasourceContent, CustomConfigureDatasourceProps, - NewDatasource, } from '../../../../../../../ingest_manager/public'; import { getManagementUrl } from '../../../..'; -type DatasourceWithId = NewDatasource & { id: string }; - /** * Exports Endpoint-specific datasource configuration instructions * for use in the Ingest app create / edit datasource config */ export const ConfigureEndpointDatasource = memo( - ({ - from, - datasource, - }: { - from: string; - datasource: CustomConfigureDatasourceProps['datasource']; - }) => { + ({ from, datasourceId }: CustomConfigureDatasourceProps) => { const { services } = useKibana(); let policyUrl = ''; - if (from === 'edit') { + if (from === 'edit' && datasourceId) { policyUrl = getManagementUrl({ name: 'policyDetails', - policyId: (datasource as DatasourceWithId).id, + policyId: datasourceId, }); } diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx index f4c4b36ce153f..d1f7da91bd6fa 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx @@ -68,11 +68,13 @@ export const PolicyDetails = React.memo(() => { } ), body: ( - + + + ), }); } else { @@ -116,7 +118,7 @@ export const PolicyDetails = React.memo(() => { ) : policyApiError ? ( - {policyApiError?.message} + {policyApiError?.message} ) : null} diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/checkbox.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/checkbox.tsx index e5f3b2c7e8b7e..9ceade5d0264c 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/checkbox.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/checkbox.tsx @@ -5,23 +5,25 @@ */ import React, { useCallback, useMemo } from 'react'; -import { EuiCheckbox, htmlIdGenerator } from '@elastic/eui'; +import { EuiCheckbox, EuiCheckboxProps, htmlIdGenerator } from '@elastic/eui'; import { useDispatch } from 'react-redux'; - import { usePolicyDetailsSelector } from '../../policy_hooks'; import { policyConfig } from '../../../store/policy_details/selectors'; import { PolicyDetailsAction } from '../../../store/policy_details'; import { UIPolicyConfig } from '../../../../../../../common/endpoint/types'; +type EventsCheckboxProps = Omit & { + name: string; + setter: (config: UIPolicyConfig, checked: boolean) => UIPolicyConfig; + getter: (config: UIPolicyConfig) => boolean; +}; + export const EventsCheckbox = React.memo(function ({ name, setter, getter, -}: { - name: string; - setter: (config: UIPolicyConfig, checked: boolean) => UIPolicyConfig; - getter: (config: UIPolicyConfig) => boolean; -}) { + ...otherProps +}: EventsCheckboxProps) { const policyDetailsConfig = usePolicyDetailsSelector(policyConfig); const selected = getter(policyDetailsConfig); const dispatch = useDispatch<(action: PolicyDetailsAction) => void>(); @@ -44,6 +46,7 @@ export const EventsCheckbox = React.memo(function ({ label={name} checked={selected} onChange={handleCheckboxChange} + {...otherProps} /> ); }); diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/linux.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/linux.tsx index d0ddd5cb6fe2f..d7bae0d2e6bad 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/linux.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/linux.tsx @@ -73,6 +73,7 @@ export const LinuxEvents = React.memo(() => { setIn(config)(item.os)('events')(item.protectionField)(checked) } diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/mac.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/mac.tsx index e2d6b70d33415..37709ff608857 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/mac.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/mac.tsx @@ -73,6 +73,7 @@ export const MacEvents = React.memo(() => { setIn(config)(item.os)('events')(item.protectionField)(checked) } diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/windows.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/windows.tsx index 23f33cb6fd86f..3c7ecae0d9b4e 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/windows.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/events/windows.tsx @@ -113,6 +113,7 @@ export const WindowsEvents = React.memo(() => { setIn(config)(item.os)('events')(item.protectionField)(checked) } diff --git a/x-pack/plugins/security_solution/public/timelines/components/flyout/header/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/flyout/header/index.tsx index ab8a24889e9bf..8ad32d6e2cad0 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/flyout/header/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/flyout/header/index.tsx @@ -33,14 +33,14 @@ const StatefulFlyoutHeader = React.memo( associateNote, createTimeline, description, - isFavorite, isDataInTimeline, isDatepickerLocked, - title, + isFavorite, noteIds, notesById, status, timelineId, + title, toggleLock, updateDescription, updateIsFavorite, @@ -61,15 +61,15 @@ const StatefulFlyoutHeader = React.memo( isDataInTimeline={isDataInTimeline} isDatepickerLocked={isDatepickerLocked} isFavorite={isFavorite} - title={title} noteIds={noteIds} status={status} timelineId={timelineId} + title={title} toggleLock={toggleLock} updateDescription={updateDescription} updateIsFavorite={updateIsFavorite} - updateTitle={updateTitle} updateNote={updateNote} + updateTitle={updateTitle} usersViewing={usersViewing} /> ); diff --git a/x-pack/plugins/security_solution/public/timelines/components/flyout/header_with_close_button/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/flyout/header_with_close_button/index.test.tsx index 9a52e9cf4e538..e5fc8b68b1cb7 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/flyout/header_with_close_button/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/flyout/header_with_close_button/index.test.tsx @@ -10,6 +10,27 @@ import React from 'react'; import { TestProviders } from '../../../../common/mock'; import { FlyoutHeaderWithCloseButton } from '.'; +jest.mock('react-router-dom', () => ({ + ...jest.requireActual('react-router-dom'), + useHistory: jest.fn(), +})); +jest.mock('../../../../common/lib/kibana', () => ({ + ...jest.requireActual('../../../../common/lib/kibana'), + useKibana: jest.fn().mockReturnValue({ + services: { + application: { + capabilities: { + securitySolution: { + crud: true, + }, + }, + }, + }, + }), + useUiSetting$: jest.fn().mockReturnValue([]), + useGetUserSavedObjectPermissions: jest.fn(), +})); + describe('FlyoutHeaderWithCloseButton', () => { test('renders correctly against snapshot', () => { const EmptyComponent = shallow( diff --git a/x-pack/plugins/security_solution/public/timelines/components/notes/note_card/__snapshots__/note_card_body.test.tsx.snap b/x-pack/plugins/security_solution/public/timelines/components/notes/note_card/__snapshots__/note_card_body.test.tsx.snap index 391aaba17ae3a..22f89ffc6927e 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/notes/note_card/__snapshots__/note_card_body.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/timelines/components/notes/note_card/__snapshots__/note_card_body.test.tsx.snap @@ -115,32 +115,28 @@ exports[`NoteCardBody renders correctly against snapshot 1`] = ` }, "euiCardSpacing": "16px", "euiCheckBoxSize": "16px", - "euiCodeBlockAdditionBackgroundColor": "#144212", - "euiCodeBlockAdditionColor": "#e6e1dc", - "euiCodeBlockAttributeColor": "#80cbbf", + "euiCodeBlockAdditionColor": "#54b399", + "euiCodeBlockAttributeColor": "inherit", "euiCodeBlockBackgroundColor": "#25262e", - "euiCodeBlockBuiltInColor": "#0086b3", "euiCodeBlockColor": "#dfe5ef", - "euiCodeBlockCommentColor": "#656565", - "euiCodeBlockDeletionBackgroundColor": "#660000", - "euiCodeBlockDeletionColor": "#e6e1dc", - "euiCodeBlockFunctionTitleColor": "#75a5ff", - "euiCodeBlockKeywordColor": "#c792ea", - "euiCodeBlockMetaColor": "#75a5ff", - "euiCodeBlockNameColor": "#e06c75", - "euiCodeBlockNumberColor": "#f77669", - "euiCodeBlockParamsColor": "#eefff7", - "euiCodeBlockRegexpColor": "#009926", - "euiCodeBlockSectionColor": "#ffc66d", + "euiCodeBlockCommentColor": "#8d919a", + "euiCodeBlockDeletionColor": "#ff6666", + "euiCodeBlockFunctionTitleColor": "inherit", + "euiCodeBlockKeywordColor": "#a184c2", + "euiCodeBlockMetaColor": "#8d919a", + "euiCodeBlockNameColor": "#6092c0", + "euiCodeBlockNumberColor": "#54b399", + "euiCodeBlockParamsColor": "inherit", + "euiCodeBlockSectionColor": "#e7664c", "euiCodeBlockSelectedBackgroundColor": "inherit", - "euiCodeBlockSelectorClassColor": "#ffcb68", - "euiCodeBlockSelectorIdColor": "#f77669", - "euiCodeBlockSelectorTagColor": "#c792ea", - "euiCodeBlockStringColor": "#c3e88d", - "euiCodeBlockSymbolColor": "#c792ea", - "euiCodeBlockTagColor": "#abb2bf", - "euiCodeBlockTitleColor": "#75a5ff", - "euiCodeBlockTypeColor": "#da4939", + "euiCodeBlockSelectorClassColor": "inherit", + "euiCodeBlockSelectorIdColor": "inherit", + "euiCodeBlockSelectorTagColor": "inherit", + "euiCodeBlockStringColor": "#d77092", + "euiCodeBlockSymbolColor": "#e7664c", + "euiCodeBlockTagColor": "#6092c0", + "euiCodeBlockTitleColor": "#da8b45", + "euiCodeBlockTypeColor": "#6092c0", "euiCodeFontFamily": "'Roboto Mono', 'Consolas', 'Menlo', 'Courier', monospace", "euiCollapsibleNavGroupDarkBackgroundColor": "#131317", "euiCollapsibleNavGroupDarkHighContrastColor": "#1ba9f5", @@ -230,6 +226,7 @@ exports[`NoteCardBody renders correctly against snapshot 1`] = ` "warning": "#ffce7a", }, "euiFilePickerTallHeight": "128px", + "euiFlyoutBorder": "1px solid #343741", "euiFocusBackgroundColor": "#232635", "euiFocusRingAnimStartColor": "rgba(27, 169, 245, 0)", "euiFocusRingAnimStartSize": "6px", diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/index.tsx index 92a8fc9338877..344f10dfdb35e 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/index.tsx @@ -42,6 +42,7 @@ import { } from './types'; import { DEFAULT_SORT_FIELD, DEFAULT_SORT_DIRECTION } from './constants'; import { useTimelineTypes } from './use_timeline_types'; +import { disableTemplate } from '../../../../common/constants'; interface OwnProps { apolloClient: ApolloClient; @@ -52,12 +53,6 @@ interface OwnProps { onOpenTimeline?: (timeline: TimelineModel) => void; } -/** - * CreateTemplateTimelineBtn - * Remove the comment here to enable template timeline - */ -export const disableTemplate = true; - export type OpenTimelineOwnProps = OwnProps & Pick< OpenTimelineProps, diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/__snapshots__/timeline.test.tsx.snap b/x-pack/plugins/security_solution/public/timelines/components/timeline/__snapshots__/timeline.test.tsx.snap index 4ed0b52fc0f14..4e6cce618880b 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/__snapshots__/timeline.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/__snapshots__/timeline.test.tsx.snap @@ -606,19 +606,40 @@ exports[`Timeline rendering renders correctly against snapshot 1`] = ` }, "filters": Array [], "uiSettings": Object { - "get": [Function], - "get$": [MockFunction], - "getAll": [MockFunction], - "getSaved$": [MockFunction], - "getUpdate$": [MockFunction], - "getUpdateErrors$": [MockFunction], - "isCustom": [MockFunction], - "isDeclared": [MockFunction], - "isDefault": [MockFunction], - "isOverridden": [MockFunction], - "overrideLocalDefault": [MockFunction], - "remove": [MockFunction], - "set": [MockFunction], + "get": [MockFunction] { + "calls": Array [ + Array [ + "query:allowLeadingWildcards", + ], + Array [ + "query:queryString:options", + ], + Array [ + "courier:ignoreFilterIfFieldNotInIndex", + ], + Array [ + "dateFormat:tz", + ], + ], + "results": Array [ + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + ], + }, }, "updated$": Subject { "_isScalar": false, @@ -826,7 +847,7 @@ exports[`Timeline rendering renders correctly against snapshot 1`] = ` } inputId="timeline" /> - - + `; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx index 581fa125d21e2..3110129867628 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx @@ -26,7 +26,13 @@ import { mockDataProviders } from './data_providers/mock/mock_data_providers'; import { StatefulTimeline, Props as StatefulTimelineProps } from './index'; import { Timeline } from './timeline'; -jest.mock('../../../common/lib/kibana'); +jest.mock('../../../common/lib/kibana', () => { + const originalModule = jest.requireActual('../../../common/lib/kibana'); + return { + ...originalModule, + useGetUserSavedObjectPermissions: jest.fn(), + }; +}); const mockUseResizeObserver: jest.Mock = useResizeObserver as jest.Mock; jest.mock('use-resize-observer/polyfilled'); @@ -34,7 +40,11 @@ mockUseResizeObserver.mockImplementation(() => ({})); const mockUseSignalIndex: jest.Mock = useSignalIndex as jest.Mock; jest.mock('../../../alerts/containers/detection_engine/alerts/use_signal_index'); - +jest.mock('react-router-dom', () => ({ + ...jest.requireActual('react-router-dom'), + useHistory: jest.fn(), +})); +jest.mock('../flyout/header_with_close_button'); describe('StatefulTimeline', () => { let props = {} as StatefulTimelineProps; const sort: Sort = { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/index.test.tsx index 0a70413b7ea29..2ffbae1f7eb5c 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/index.test.tsx @@ -17,6 +17,14 @@ jest.mock('react-redux', () => { return { ...reactRedux, useDispatch: () => mockDispatch, + useSelector: jest + .fn() + .mockReturnValueOnce({ + timelineId: 'timeline-id', + timelineSavedObjectId: '34578-3497-5893-47589-34759', + timelineTitle: 'Timeline title', + }) + .mockReturnValue(null), }; }); const mockLocation = { @@ -25,17 +33,6 @@ const mockLocation = { search: '', state: '', }; -const mockLocationWithState = { - ...mockLocation, - state: { - insertTimeline: { - timelineId: 'timeline-id', - timelineSavedObjectId: '34578-3497-5893-47589-34759', - timelineTitle: 'Timeline title', - }, - }, -}; - const onTimelineChange = jest.fn(); const defaultProps = { isDisabled: false, @@ -43,18 +40,21 @@ const defaultProps = { }; describe('Insert timeline popover ', () => { - beforeEach(() => { - jest.resetAllMocks(); + afterEach(() => { + jest.clearAllMocks(); }); it('should insert a timeline when passed in the router state', () => { - jest.spyOn(routeData, 'useLocation').mockReturnValue(mockLocationWithState); mount(); - expect(mockDispatch).toBeCalledWith({ + expect(mockDispatch.mock.calls[0][0]).toEqual({ payload: { id: 'timeline-id', show: false }, type: 'x-pack/security_solution/local/timeline/SHOW_TIMELINE', }); expect(onTimelineChange).toBeCalledWith('Timeline title', '34578-3497-5893-47589-34759'); + expect(mockDispatch.mock.calls[1][0]).toEqual({ + payload: null, + type: 'x-pack/security_solution/local/timeline/SET_INSERT_TIMELINE', + }); }); it('should do nothing when router state', () => { jest.spyOn(routeData, 'useLocation').mockReturnValue(mockLocation); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/index.tsx index ed4d742bb8b4d..de199d9a1cc2e 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/index.tsx @@ -6,14 +6,15 @@ import { EuiButtonIcon, EuiPopover, EuiSelectableOption, EuiToolTip } from '@elastic/eui'; import React, { memo, useCallback, useEffect, useMemo, useState } from 'react'; -import { useLocation } from 'react-router-dom'; -import { useDispatch } from 'react-redux'; +import { useDispatch, useSelector } from 'react-redux'; import { OpenTimelineResult } from '../../open_timeline/types'; import { SelectableTimeline } from '../selectable_timeline'; import * as i18n from '../translations'; -import { timelineActions } from '../../../../timelines/store/timeline'; +import { timelineActions, timelineSelectors } from '../../../../timelines/store/timeline'; import { TimelineType } from '../../../../../common/types/timeline'; +import { State } from '../../../../common/store'; +import { setInsertTimeline } from '../../../store/timeline/actions'; interface InsertTimelinePopoverProps { isDisabled: boolean; @@ -21,14 +22,6 @@ interface InsertTimelinePopoverProps { onTimelineChange: (timelineTitle: string, timelineId: string | null) => void; } -interface RouterState { - insertTimeline: { - timelineId: string; - timelineSavedObjectId: string; - timelineTitle: string; - }; -} - type Props = InsertTimelinePopoverProps; export const InsertTimelinePopoverComponent: React.FC = ({ @@ -38,22 +31,18 @@ export const InsertTimelinePopoverComponent: React.FC = ({ }) => { const dispatch = useDispatch(); const [isPopoverOpen, setIsPopoverOpen] = useState(false); - const { state } = useLocation(); - const [routerState, setRouterState] = useState(state ?? null); + const insertTimeline = useSelector((state: State) => { + return timelineSelectors.selectInsertTimeline(state); + }); useEffect(() => { - if (routerState && routerState.insertTimeline) { - dispatch( - timelineActions.showTimeline({ id: routerState.insertTimeline.timelineId, show: false }) - ); - onTimelineChange( - routerState.insertTimeline.timelineTitle, - routerState.insertTimeline.timelineSavedObjectId - ); - setRouterState(null); + if (insertTimeline != null) { + dispatch(timelineActions.showTimeline({ id: insertTimeline.timelineId, show: false })); + onTimelineChange(insertTimeline.timelineTitle, insertTimeline.timelineSavedObjectId); + dispatch(setInsertTimeline(null)); } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [routerState]); + }, [insertTimeline, dispatch]); const handleClosePopover = useCallback(() => { setIsPopoverOpen(false); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/use_insert_timeline.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/use_insert_timeline.tsx index 0f9e64082a603..6269bc1b4a1a3 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/use_insert_timeline.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/insert_timeline_popover/use_insert_timeline.tsx @@ -17,7 +17,7 @@ export const useInsertTimeline = (form: FormHook, fieldNa }); const handleOnTimelineChange = useCallback( (title: string, id: string | null) => { - const builtLink = `${basePath}/app/siem#/timelines?timeline=(id:'${id}',isOpen:!t)`; + const builtLink = `${basePath}/app/security#/timelines?timeline=(id:'${id}',isOpen:!t)`; const currentValue = form.getFormData()[fieldName]; const newValue: string = [ currentValue.slice(0, cursorPosition.start), diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/helpers.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/helpers.test.tsx new file mode 100644 index 0000000000000..fb91bbd5a1124 --- /dev/null +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/helpers.test.tsx @@ -0,0 +1,84 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React from 'react'; +import { mount, shallow } from 'enzyme'; +import { NewTimeline, NewTimelineProps } from './helpers'; +import { useCreateTimelineButton } from './use_create_timeline'; + +jest.mock('./use_create_timeline', () => ({ + useCreateTimelineButton: jest.fn(), +})); + +jest.mock('../../../../common/lib/kibana', () => { + return { + useKibana: jest.fn().mockReturnValue({ + services: { + application: { + capabilities: { + securitySolution: { + crud: true, + }, + }, + }, + }, + }), + }; +}); + +describe('NewTimeline', () => { + const mockGetButton = jest.fn(); + + const props: NewTimelineProps = { + closeGearMenu: jest.fn(), + timelineId: 'mockTimelineId', + title: 'mockTitle', + }; + + describe('render', () => { + describe('default', () => { + beforeAll(() => { + (useCreateTimelineButton as jest.Mock).mockReturnValue({ getButton: mockGetButton }); + shallow(); + }); + + afterAll(() => { + jest.clearAllMocks(); + }); + + test('it should not render outline', () => { + expect(mockGetButton.mock.calls[0][0].outline).toEqual(false); + }); + + test('it should render title', () => { + expect(mockGetButton.mock.calls[0][0].title).toEqual(props.title); + }); + }); + + describe('show outline', () => { + beforeAll(() => { + (useCreateTimelineButton as jest.Mock).mockReturnValue({ getButton: mockGetButton }); + + const enableOutline = { + ...props, + outline: true, + }; + mount(); + }); + + afterAll(() => { + jest.clearAllMocks(); + }); + + test('it should render outline', () => { + expect(mockGetButton.mock.calls[0][0].outline).toEqual(true); + }); + + test('it should render title', () => { + expect(mockGetButton.mock.calls[0][0].title).toEqual(props.title); + }); + }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/helpers.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/helpers.tsx index 38a85a7a92631..00a0e57324841 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/helpers.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/helpers.tsx @@ -21,18 +21,28 @@ import React, { useCallback } from 'react'; import uuid from 'uuid'; import styled from 'styled-components'; import { useHistory } from 'react-router-dom'; -import { useSelector } from 'react-redux'; +import { useDispatch, useSelector } from 'react-redux'; -import { TimelineStatus } from '../../../../../common/types/timeline'; +import { + TimelineTypeLiteral, + TimelineStatus, + TimelineType, +} from '../../../../../common/types/timeline'; + +import { SiemPageName } from '../../../../app/types'; +import { timelineSelectors } from '../../../../timelines/store/timeline'; +import { State } from '../../../../common/store'; +import { useKibana } from '../../../../common/lib/kibana'; import { Note } from '../../../../common/lib/note'; + import { Notes } from '../../notes'; import { AssociateNote, UpdateNote } from '../../notes/helpers'; + import { NOTES_PANEL_WIDTH } from './notes_size'; import { ButtonContainer, DescriptionContainer, LabelText, NameField, StyledStar } from './styles'; import * as i18n from './translations'; -import { SiemPageName } from '../../../../app/types'; -import { timelineSelectors } from '../../../../timelines/store/timeline'; -import { State } from '../../../../common/store'; +import { setInsertTimeline } from '../../../store/timeline/actions'; +import { useCreateTimelineButton } from './use_create_timeline'; export const historyToolTip = 'The chronological history of actions related to this timeline'; export const streamLiveToolTip = 'Update the Timeline as new data arrives'; @@ -44,7 +54,15 @@ const NotesCountBadge = (styled(EuiBadge)` NotesCountBadge.displayName = 'NotesCountBadge'; -type CreateTimeline = ({ id, show }: { id: string; show?: boolean }) => void; +type CreateTimeline = ({ + id, + show, + timelineType, +}: { + id: string; + show?: boolean; + timelineType?: TimelineTypeLiteral; +}) => void; type UpdateIsFavorite = ({ id, isFavorite }: { id: string; isFavorite: boolean }) => void; type UpdateTitle = ({ id, title }: { id: string; title: string }) => void; type UpdateDescription = ({ id, description }: { id: string; description: string }) => void; @@ -127,23 +145,25 @@ interface NewCaseProps { export const NewCase = React.memo( ({ onClosePopover, timelineId, timelineStatus, timelineTitle }) => { const history = useHistory(); + const dispatch = useDispatch(); const { savedObjectId } = useSelector((state: State) => timelineSelectors.selectTimeline(state, timelineId) ); + const handleClick = useCallback(() => { onClosePopover(); history.push({ pathname: `/${SiemPageName.case}/create`, - state: { - insertTimeline: { - timelineId, - timelineSavedObjectId: savedObjectId, - timelineTitle: timelineTitle.length > 0 ? timelineTitle : i18n.UNTITLED_TIMELINE, - }, - }, }); + dispatch( + setInsertTimeline({ + timelineId, + timelineSavedObjectId: savedObjectId, + timelineTitle: timelineTitle.length > 0 ? timelineTitle : i18n.UNTITLED_TIMELINE, + }) + ); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [onClosePopover, history, timelineId, timelineTitle]); + }, [dispatch, onClosePopover, history, timelineId, timelineTitle]); return ( ( ); NewCase.displayName = 'NewCase'; -interface NewTimelineProps { - createTimeline: CreateTimeline; +interface ExistingCaseProps { onClosePopover: () => void; - timelineId: string; + onOpenCaseModal: () => void; + timelineStatus: TimelineStatus; } - -export const NewTimeline = React.memo( - ({ createTimeline, onClosePopover, timelineId }) => { +export const ExistingCase = React.memo( + ({ onClosePopover, onOpenCaseModal, timelineStatus }) => { const handleClick = useCallback(() => { - createTimeline({ id: timelineId, show: true }); onClosePopover(); - }, [createTimeline, timelineId, onClosePopover]); + onOpenCaseModal(); + }, [onOpenCaseModal, onClosePopover]); return ( - - {i18n.NEW_TIMELINE} - + <> + + {i18n.ATTACH_TIMELINE_TO_EXISTING_CASE} + + ); } ); +ExistingCase.displayName = 'ExistingCase'; + +export interface NewTimelineProps { + createTimeline?: CreateTimeline; + closeGearMenu?: () => void; + outline?: boolean; + timelineId: string; + title?: string; +} + +export const NewTimeline = React.memo( + ({ closeGearMenu, outline = false, timelineId, title = i18n.NEW_TIMELINE }) => { + const uiCapabilities = useKibana().services.application.capabilities; + const capabilitiesCanUserCRUD: boolean = !!uiCapabilities.securitySolution.crud; + + const { getButton } = useCreateTimelineButton({ + timelineId, + timelineType: TimelineType.default, + closeGearMenu, + }); + const button = getButton({ outline, title }); + + return capabilitiesCanUserCRUD ? button : null; + } +); NewTimeline.displayName = 'NewTimeline'; interface NotesButtonProps { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.test.tsx index 8bdec78ec8da2..505d0b8cba854 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.test.tsx @@ -6,25 +6,48 @@ import { mount } from 'enzyme'; import React from 'react'; -import { Provider as ReduxStoreProvider } from 'react-redux'; - import { TimelineStatus } from '../../../../../common/types/timeline'; import { mockGlobalState, apolloClientObservable, SUB_PLUGINS_REDUCER, + TestProviders, } from '../../../../common/mock'; import { createStore, State } from '../../../../common/store'; import { useThrottledResizeObserver } from '../../../../common/components/utils'; import { Properties, showDescriptionThreshold, showNotesThreshold } from '.'; +import { SiemPageName } from '../../../../app/types'; +import { setInsertTimeline } from '../../../store/timeline/actions'; +export { nextTick } from '../../../../../../../test_utils'; -jest.mock('../../../../common/lib/kibana'); +import { act } from 'react-dom/test-utils'; -let mockedWidth = 1000; -jest.mock('../../../../common/components/utils'); -(useThrottledResizeObserver as jest.Mock).mockImplementation(() => ({ - width: mockedWidth, -})); +jest.mock('../../../../common/lib/kibana', () => { + const originalModule = jest.requireActual('../../../../common/lib/kibana'); + return { + ...originalModule, + useKibana: jest.fn().mockReturnValue({ + services: { + application: { + capabilities: { + securitySolution: { + crud: true, + }, + }, + }, + }, + }), + useUiSetting$: jest.fn().mockReturnValue([]), + useGetUserSavedObjectPermissions: jest.fn(), + }; +}); + +const mockDispatch = jest.fn(); +jest.mock('../../../../common/components/utils', () => { + return { + useThrottledResizeObserver: jest.fn(), + }; +}); jest.mock('react-redux', () => { const originalModule = jest.requireActual('react-redux'); @@ -35,50 +58,59 @@ jest.mock('react-redux', () => { }; }); -jest.mock('react-router-dom', () => { - const originalModule = jest.requireActual('react-router-dom'); +jest.mock('react-redux', () => ({ + ...jest.requireActual('react-redux'), + useDispatch: () => mockDispatch, + useSelector: jest.fn().mockReturnValue({ savedObjectId: '1', urlState: {} }), +})); +const mockHistoryPush = jest.fn(); - return { - ...originalModule, - useHistory: jest.fn(), - }; -}); +jest.mock('react-router-dom', () => ({ + ...jest.requireActual('react-router-dom'), + useHistory: () => ({ + push: mockHistoryPush, + }), +})); +jest.mock('./use_create_timeline', () => ({ + useCreateTimelineButton: jest.fn().mockReturnValue({ getButton: jest.fn() }), +})); +const usersViewing = ['elastic']; +const defaultProps = { + associateNote: jest.fn(), + createTimeline: jest.fn(), + isDataInTimeline: false, + isDatepickerLocked: false, + isFavorite: false, + title: '', + description: '', + getNotesByIds: jest.fn(), + noteIds: [], + status: TimelineStatus.active, + timelineId: 'abc', + toggleLock: jest.fn(), + updateDescription: jest.fn(), + updateIsFavorite: jest.fn(), + updateTitle: jest.fn(), + updateNote: jest.fn(), + usersViewing, +}; describe('Properties', () => { - const usersViewing = ['elastic']; - const state: State = mockGlobalState; + let mockedWidth = 1000; let store = createStore(state, SUB_PLUGINS_REDUCER, apolloClientObservable); beforeEach(() => { jest.clearAllMocks(); store = createStore(state, SUB_PLUGINS_REDUCER, apolloClientObservable); - mockedWidth = 1000; + (useThrottledResizeObserver as jest.Mock).mockReturnValue({ width: mockedWidth }); }); test('renders correctly', () => { const wrapper = mount( - - - + + + ); wrapper.find('[data-test-subj="settings-gear"]').at(0).simulate('click'); @@ -87,31 +119,16 @@ describe('Properties', () => { expect(wrapper.find('button[data-test-subj="attach-timeline-case"]').prop('disabled')).toEqual( false ); + expect( + wrapper.find('button[data-test-subj="attach-timeline-existing-case"]').prop('disabled') + ).toEqual(false); }); test('renders correctly draft timeline', () => { const wrapper = mount( - - - + + + ); wrapper.find('[data-test-subj="settings-gear"]').at(0).simulate('click'); @@ -119,31 +136,16 @@ describe('Properties', () => { expect(wrapper.find('button[data-test-subj="attach-timeline-case"]').prop('disabled')).toEqual( true ); + expect( + wrapper.find('button[data-test-subj="attach-timeline-existing-case"]').prop('disabled') + ).toEqual(true); }); test('it renders an empty star icon when it is NOT a favorite', () => { const wrapper = mount( - - - + + + ); expect(wrapper.find('[data-test-subj="timeline-favorite-empty-star"]').exists()).toEqual(true); @@ -151,27 +153,9 @@ describe('Properties', () => { test('it renders a filled star icon when it is a favorite', () => { const wrapper = mount( - - - + + + ); expect(wrapper.find('[data-test-subj="timeline-favorite-filled-star"]').exists()).toEqual(true); @@ -181,27 +165,9 @@ describe('Properties', () => { const title = 'foozle'; const wrapper = mount( - - - + + + ); expect(wrapper.find('[data-test-subj="timeline-title"]').first().props().value).toEqual(title); @@ -209,27 +175,9 @@ describe('Properties', () => { test('it renders the date picker with the lock icon', () => { const wrapper = mount( - - - + + + ); expect( @@ -242,27 +190,9 @@ describe('Properties', () => { test('it renders the lock icon when isDatepickerLocked is true', () => { const wrapper = mount( - - - + + + ); expect( wrapper @@ -274,27 +204,9 @@ describe('Properties', () => { test('it renders the unlock icon when isDatepickerLocked is false', () => { const wrapper = mount( - - - + + + ); expect( wrapper @@ -306,30 +218,14 @@ describe('Properties', () => { test('it renders a description on the left when the width is at least as wide as the threshold', () => { const description = 'strange'; - mockedWidth = showDescriptionThreshold; + + (useThrottledResizeObserver as jest.Mock).mockReset(); + (useThrottledResizeObserver as jest.Mock).mockReturnValue({ width: showDescriptionThreshold }); const wrapper = mount( - - - + + + ); expect( @@ -343,30 +239,16 @@ describe('Properties', () => { test('it does NOT render a description on the left when the width is less than the threshold', () => { const description = 'strange'; - mockedWidth = showDescriptionThreshold - 1; + + (useThrottledResizeObserver as jest.Mock).mockReset(); + (useThrottledResizeObserver as jest.Mock).mockReturnValue({ + width: showDescriptionThreshold - 1, + }); const wrapper = mount( - - - + + + ); expect( @@ -381,27 +263,9 @@ describe('Properties', () => { mockedWidth = showNotesThreshold; const wrapper = mount( - - - + + + ); expect( @@ -413,30 +277,15 @@ describe('Properties', () => { }); test('it does NOT render a a notes button on the left when the width is less than the threshold', () => { - mockedWidth = showNotesThreshold - 1; + (useThrottledResizeObserver as jest.Mock).mockReset(); + (useThrottledResizeObserver as jest.Mock).mockReturnValue({ + width: showNotesThreshold - 1, + }); const wrapper = mount( - - - + + + ); expect( @@ -449,27 +298,9 @@ describe('Properties', () => { test('it renders a settings icon', () => { const wrapper = mount( - - - + + + ); expect(wrapper.find('[data-test-subj="settings-gear"]').exists()).toEqual(true); @@ -479,27 +310,9 @@ describe('Properties', () => { const title = 'port scan'; const wrapper = mount( - - - + + + ); expect(wrapper.find('[data-test-subj="avatar"]').exists()).toEqual(true); @@ -507,29 +320,45 @@ describe('Properties', () => { test('it does NOT render an avatar for the current user viewing the timeline when it does NOT have a title', () => { const wrapper = mount( - - - + + + ); expect(wrapper.find('[data-test-subj="avatar"]').exists()).toEqual(false); }); + + test('insert timeline - new case', () => { + const wrapper = mount( + + + + ); + wrapper.find('[data-test-subj="settings-gear"]').at(0).simulate('click'); + wrapper.find('[data-test-subj="attach-timeline-case"]').first().simulate('click'); + + expect(mockHistoryPush).toBeCalledWith({ pathname: `/${SiemPageName.case}/create` }); + expect(mockDispatch).toBeCalledWith( + setInsertTimeline({ + timelineId: defaultProps.timelineId, + timelineSavedObjectId: '1', + timelineTitle: 'coolness', + }) + ); + }); + + test('insert timeline - existing case', async () => { + const wrapper = mount( + + + + ); + wrapper.find('[data-test-subj="settings-gear"]').at(0).simulate('click'); + wrapper.find('[data-test-subj="attach-timeline-existing-case"]').first().simulate('click'); + + await act(async () => { + await Promise.resolve({}); + }); + expect(wrapper.find('[data-test-subj="all-cases-modal"]').exists()).toBeTruthy(); + }); }); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.tsx index 1532a64e4083e..be79c0773bf88 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.tsx @@ -6,17 +6,34 @@ import React, { useState, useCallback, useMemo } from 'react'; -import { TimelineStatus } from '../../../../../common/types/timeline'; +import { useDispatch, useSelector } from 'react-redux'; +import { useHistory } from 'react-router-dom'; +import { TimelineStatus, TimelineTypeLiteral } from '../../../../../common/types/timeline'; import { useThrottledResizeObserver } from '../../../../common/components/utils'; import { Note } from '../../../../common/lib/note'; import { InputsModelId } from '../../../../common/store/inputs/constants'; + import { AssociateNote, UpdateNote } from '../../notes/helpers'; import { TimelineProperties } from './styles'; import { PropertiesRight } from './properties_right'; import { PropertiesLeft } from './properties_left'; +import { AllCasesModal } from '../../../../cases/components/all_cases_modal'; +import { SiemPageName } from '../../../../app/types'; +import * as i18n from './translations'; +import { State } from '../../../../common/store'; +import { timelineSelectors } from '../../../store/timeline'; +import { setInsertTimeline } from '../../../store/timeline/actions'; -type CreateTimeline = ({ id, show }: { id: string; show?: boolean }) => void; +type CreateTimeline = ({ + id, + show, + timelineType, +}: { + id: string; + show?: boolean; + timelineType?: TimelineTypeLiteral; +}) => void; type UpdateIsFavorite = ({ id, isFavorite }: { id: string; isFavorite: boolean }) => void; type UpdateTitle = ({ id, title }: { id: string; title: string }) => void; type UpdateDescription = ({ id, description }: { id: string; description: string }) => void; @@ -78,6 +95,7 @@ export const Properties = React.memo( const [showActions, setShowActions] = useState(false); const [showNotes, setShowNotes] = useState(false); const [showTimelineModal, setShowTimelineModal] = useState(false); + const dispatch = useDispatch(); const onButtonClick = useCallback(() => setShowActions(!showActions), [showActions]); const onToggleShowNotes = useCallback(() => setShowNotes(!showNotes), [showNotes]); @@ -89,6 +107,30 @@ export const Properties = React.memo( setShowTimelineModal(true); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); + const [showCaseModal, setShowCaseModal] = useState(false); + const onCloseCaseModal = useCallback(() => setShowCaseModal(false), []); + const onOpenCaseModal = useCallback(() => setShowCaseModal(true), []); + const history = useHistory(); + const currentTimeline = useSelector((state: State) => + timelineSelectors.selectTimeline(state, timelineId) + ); + + const onRowClick = useCallback( + (id: string) => { + onCloseCaseModal(); + history.push({ + pathname: `/${SiemPageName.case}/${id}`, + }); + dispatch( + setInsertTimeline({ + timelineId, + timelineSavedObjectId: currentTimeline.savedObjectId, + timelineTitle: title.length > 0 ? title : i18n.UNTITLED_TIMELINE, + }) + ); + }, + [onCloseCaseModal, currentTimeline, dispatch, history, timelineId, title] + ); const datePickerWidth = useMemo( () => @@ -128,7 +170,6 @@ export const Properties = React.memo( /> ( onButtonClick={onButtonClick} onClosePopover={onClosePopover} onCloseTimelineModal={onCloseTimelineModal} + onOpenCaseModal={onOpenCaseModal} onOpenTimelineModal={onOpenTimelineModal} onToggleShowNotes={onToggleShowNotes} showActions={showActions} @@ -151,6 +193,11 @@ export const Properties = React.memo( updateNote={updateNote} usersViewing={usersViewing} /> + ); } diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/new_template_timeline.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/new_template_timeline.test.tsx new file mode 100644 index 0000000000000..b9b6dadf6f9d7 --- /dev/null +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/new_template_timeline.test.tsx @@ -0,0 +1,104 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { mount, ReactWrapper } from 'enzyme'; +import React from 'react'; +import { Provider as ReduxStoreProvider } from 'react-redux'; + +import { + mockGlobalState, + apolloClientObservable, + SUB_PLUGINS_REDUCER, +} from '../../../../common/mock'; +import { createStore, State } from '../../../../common/store'; +import { useKibana } from '../../../../common/lib/kibana'; +import { NewTemplateTimeline } from './new_template_timeline'; + +jest.mock('../../../../common/lib/kibana', () => { + return { + useKibana: jest.fn(), + }; +}); + +describe('NewTemplateTimeline', () => { + const state: State = mockGlobalState; + const store = createStore(state, SUB_PLUGINS_REDUCER, apolloClientObservable); + const mockClosePopover = jest.fn(); + const mockTitle = 'NEW_TIMELINE'; + let wrapper: ReactWrapper; + + describe('render if CRUD', () => { + beforeAll(() => { + (useKibana as jest.Mock).mockReturnValue({ + services: { + application: { + capabilities: { + securitySolution: { + crud: true, + }, + }, + }, + }, + }); + + afterAll(() => { + (useKibana as jest.Mock).mockReset(); + }); + + wrapper = mount( + + + + ); + }); + + test('render with iconType', () => { + expect( + wrapper + .find('[data-test-subj="template-timeline-new-with-border"]') + .first() + .prop('iconType') + ).toEqual('plusInCircle'); + }); + + test('render with onClick', () => { + expect( + wrapper.find('[data-test-subj="template-timeline-new-with-border"]').first().prop('onClick') + ).toBeTruthy(); + }); + }); + + describe('If no CRUD', () => { + beforeAll(() => { + (useKibana as jest.Mock).mockReturnValue({ + services: { + application: { + capabilities: { + securitySolution: { + crud: false, + }, + }, + }, + }, + }); + + wrapper = mount( + + + + ); + }); + + afterAll(() => { + (useKibana as jest.Mock).mockReset(); + }); + + test('no render', () => { + expect( + wrapper.find('[data-test-subj="template-timeline-new-with-border"]').exists() + ).toBeFalsy(); + }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/new_template_timeline.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/new_template_timeline.tsx new file mode 100644 index 0000000000000..45b2ce62fb85b --- /dev/null +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/new_template_timeline.tsx @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; + +import { TimelineType } from '../../../../../common/types/timeline'; + +import { useKibana } from '../../../../common/lib/kibana'; +import { useCreateTimelineButton } from './use_create_timeline'; + +interface OwnProps { + closeGearMenu?: () => void; + outline?: boolean; + title?: string; + timelineId?: string; +} + +export const NewTemplateTimelineComponent: React.FC = ({ + closeGearMenu, + outline, + title, + timelineId = 'timeline-1', +}) => { + const uiCapabilities = useKibana().services.application.capabilities; + const capabilitiesCanUserCRUD: boolean = !!uiCapabilities.securitySolution.crud; + + const { getButton } = useCreateTimelineButton({ + timelineId, + timelineType: TimelineType.template, + closeGearMenu, + }); + + const button = getButton({ outline, title }); + + return capabilitiesCanUserCRUD ? button : null; +}; + +export const NewTemplateTimeline = React.memo(NewTemplateTimelineComponent); +NewTemplateTimeline.displayName = 'NewTemplateTimeline'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/properties_right.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/properties_right.test.tsx new file mode 100644 index 0000000000000..e297a3cc595d6 --- /dev/null +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/properties_right.test.tsx @@ -0,0 +1,291 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { mount, ReactWrapper } from 'enzyme'; +import React from 'react'; + +import { PropertiesRight } from './properties_right'; +import { useKibana } from '../../../../common/lib/kibana'; +import { TimelineStatus } from '../../../../../common/types/timeline'; +import { disableTemplate } from '../../../../../common/constants'; + +jest.mock('../../../../common/lib/kibana', () => { + return { + useKibana: jest.fn(), + useUiSetting$: jest.fn().mockReturnValue([]), + }; +}); + +jest.mock('./new_template_timeline', () => { + return { + NewTemplateTimeline: jest.fn(() =>
), + }; +}); + +jest.mock('./helpers', () => { + return { + Description: jest.fn().mockReturnValue(
), + ExistingCase: jest.fn().mockReturnValue(
), + NewCase: jest.fn().mockReturnValue(
), + NewTimeline: jest.fn().mockReturnValue(
), + NotesButton: jest.fn().mockReturnValue(
), + }; +}); + +jest.mock('../../../../common/components/inspect', () => { + return { + InspectButton: jest.fn().mockReturnValue(
), + InspectButtonContainer: jest.fn(({ children }) =>
{children}
), + }; +}); + +describe('Properties Right', () => { + let wrapper: ReactWrapper; + const props = { + onButtonClick: jest.fn(), + onClosePopover: jest.fn(), + showActions: true, + createTimeline: jest.fn(), + timelineId: 'timelineId', + isDataInTimeline: false, + showNotes: false, + showNotesFromWidth: false, + showDescription: false, + showUsersView: false, + usersViewing: [], + description: 'desc', + updateDescription: jest.fn(), + associateNote: jest.fn(), + getNotesByIds: jest.fn(), + noteIds: [], + onToggleShowNotes: jest.fn(), + onCloseTimelineModal: jest.fn(), + onOpenCaseModal: jest.fn(), + onOpenTimelineModal: jest.fn(), + status: TimelineStatus.active, + showTimelineModal: false, + title: 'title', + updateNote: jest.fn(), + }; + + describe('with crud', () => { + describe('render', () => { + beforeAll(() => { + (useKibana as jest.Mock).mockReturnValue({ + services: { + application: { + capabilities: { + securitySolution: { + crud: true, + }, + }, + }, + }, + }); + wrapper = mount(); + }); + + afterAll(() => { + (useKibana as jest.Mock).mockReset(); + }); + + test('it renders settings-gear', () => { + expect(wrapper.find('[data-test-subj="settings-gear"]').exists()).toBeTruthy(); + }); + + test('it renders create timelin btn', () => { + expect(wrapper.find('[data-test-subj="create-default-btn"]').exists()).toBeTruthy(); + }); + + /* + * CreateTemplateTimelineBtn + * Remove the comment here to enable CreateTemplateTimelineBtn + */ + test('it renders no create template timelin btn', () => { + expect(wrapper.find('[data-test-subj="create-template-btn"]').exists()).toEqual( + !disableTemplate + ); + }); + + test('it renders create attach timeline to a case btn', () => { + expect(wrapper.find('[data-test-subj="NewCase"]').exists()).toBeTruthy(); + }); + + test('it renders no NotesButton', () => { + expect(wrapper.find('[data-test-subj="NotesButton"]').exists()).not.toBeTruthy(); + }); + + test('it renders no Description', () => { + expect(wrapper.find('[data-test-subj="Description"]').exists()).not.toBeTruthy(); + }); + }); + + describe('render with notes button', () => { + beforeAll(() => { + (useKibana as jest.Mock).mockReturnValue({ + services: { + application: { + capabilities: { + securitySolution: { + crud: true, + }, + }, + }, + }, + }); + const propsWithshowNotes = { + ...props, + showNotesFromWidth: true, + }; + wrapper = mount(); + }); + + afterAll(() => { + (useKibana as jest.Mock).mockReset(); + }); + + test('it renders NotesButton', () => { + expect(wrapper.find('[data-test-subj="NotesButton"]').exists()).toBeTruthy(); + }); + }); + + describe('render with description', () => { + beforeAll(() => { + (useKibana as jest.Mock).mockReturnValue({ + services: { + application: { + capabilities: { + securitySolution: { + crud: true, + }, + }, + }, + }, + }); + const propsWithshowDescription = { + ...props, + showDescription: true, + }; + wrapper = mount(); + }); + + afterAll(() => { + (useKibana as jest.Mock).mockReset(); + }); + + test('it renders Description', () => { + expect(wrapper.find('[data-test-subj="Description"]').exists()).toBeTruthy(); + }); + }); + }); + + describe('with no crud', () => { + describe('render', () => { + beforeAll(() => { + (useKibana as jest.Mock).mockReturnValue({ + services: { + application: { + capabilities: { + securitySolution: { + crud: false, + }, + }, + }, + }, + }); + wrapper = mount(); + }); + + afterAll(() => { + (useKibana as jest.Mock).mockReset(); + }); + + test('it renders settings-gear', () => { + expect(wrapper.find('[data-test-subj="settings-gear"]').exists()).toBeTruthy(); + }); + + test('it renders no create timelin btn', () => { + expect(wrapper.find('[data-test-subj="create-default-btn"]').exists()).not.toBeTruthy(); + }); + + test('it renders create template timelin btn if it is enabled', () => { + expect(wrapper.find('[data-test-subj="create-template-btn"]').exists()).toEqual( + !disableTemplate + ); + }); + + test('it renders create attach timeline to a case btn', () => { + expect(wrapper.find('[data-test-subj="NewCase"]').exists()).toBeTruthy(); + }); + + test('it renders no NotesButton', () => { + expect(wrapper.find('[data-test-subj="NotesButton"]').exists()).not.toBeTruthy(); + }); + + test('it renders no Description', () => { + expect(wrapper.find('[data-test-subj="Description"]').exists()).not.toBeTruthy(); + }); + }); + + describe('render with notes button', () => { + beforeAll(() => { + (useKibana as jest.Mock).mockReturnValue({ + services: { + application: { + capabilities: { + securitySolution: { + crud: false, + }, + }, + }, + }, + }); + const propsWithshowNotes = { + ...props, + showNotesFromWidth: true, + }; + wrapper = mount(); + }); + + afterAll(() => { + (useKibana as jest.Mock).mockReset(); + }); + + test('it renders NotesButton', () => { + expect(wrapper.find('[data-test-subj="NotesButton"]').exists()).toBeTruthy(); + }); + }); + + describe('render with description', () => { + beforeAll(() => { + (useKibana as jest.Mock).mockReturnValue({ + services: { + application: { + capabilities: { + securitySolution: { + crud: false, + }, + }, + }, + }, + }); + const propsWithshowDescription = { + ...props, + showDescription: true, + }; + wrapper = mount(); + }); + + afterAll(() => { + (useKibana as jest.Mock).mockReset(); + }); + + test('it renders Description', () => { + expect(wrapper.find('[data-test-subj="Description"]').exists()).toBeTruthy(); + }); + }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/properties_right.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/properties_right.tsx index 963b67838e811..a9baf73676ffb 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/properties_right.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/properties_right.tsx @@ -14,15 +14,21 @@ import { EuiToolTip, EuiAvatar, } from '@elastic/eui'; -import { NewTimeline, Description, NotesButton, NewCase } from './helpers'; +import { NewTimeline, Description, NotesButton, NewCase, ExistingCase } from './helpers'; + +import { disableTemplate } from '../../../../../common/constants'; +import { TimelineStatus } from '../../../../../common/types/timeline'; + +import { InspectButton, InspectButtonContainer } from '../../../../common/components/inspect'; +import { useKibana } from '../../../../common/lib/kibana'; +import { Note } from '../../../../common/lib/note'; + +import { AssociateNote } from '../../notes/helpers'; import { OpenTimelineModalButton } from '../../open_timeline/open_timeline_modal/open_timeline_modal_button'; import { OpenTimelineModal } from '../../open_timeline/open_timeline_modal'; -import { InspectButton, InspectButtonContainer } from '../../../../common/components/inspect'; import * as i18n from './translations'; -import { AssociateNote } from '../../notes/helpers'; -import { Note } from '../../../../common/lib/note'; -import { TimelineStatus } from '../../../../../common/types/timeline'; +import { NewTemplateTimeline } from './new_template_timeline'; export const PropertiesRightStyle = styled(EuiFlexGroup)` margin-right: 5px; @@ -55,161 +61,187 @@ const Avatar = styled(EuiAvatar)` Avatar.displayName = 'Avatar'; -type CreateTimeline = ({ id, show }: { id: string; show?: boolean }) => void; type UpdateDescription = ({ id, description }: { id: string; description: string }) => void; export type UpdateNote = (note: Note) => void; -interface Props { - onButtonClick: () => void; - onClosePopover: () => void; - showActions: boolean; - createTimeline: CreateTimeline; - timelineId: string; - isDataInTimeline: boolean; - showNotes: boolean; - showNotesFromWidth: boolean; - showDescription: boolean; - showUsersView: boolean; - usersViewing: string[]; - description: string; - updateDescription: UpdateDescription; +interface PropertiesRightComponentProps { associateNote: AssociateNote; + description: string; getNotesByIds: (noteIds: string[]) => Note[]; + isDataInTimeline: boolean; noteIds: string[]; - onToggleShowNotes: () => void; + onButtonClick: () => void; + onClosePopover: () => void; onCloseTimelineModal: () => void; + onOpenCaseModal: () => void; onOpenTimelineModal: () => void; + onToggleShowNotes: () => void; + showActions: boolean; + showDescription: boolean; + showNotes: boolean; + showNotesFromWidth: boolean; showTimelineModal: boolean; + showUsersView: boolean; status: TimelineStatus; + timelineId: string; title: string; + updateDescription: UpdateDescription; updateNote: UpdateNote; + usersViewing: string[]; } -const PropertiesRightComponent: React.FC = ({ - onButtonClick, - showActions, - onClosePopover, - createTimeline, - timelineId, - isDataInTimeline, - showNotesFromWidth, - showNotes, - showDescription, - showUsersView, - usersViewing, - description, - updateDescription, +const PropertiesRightComponent: React.FC = ({ associateNote, + description, getNotesByIds, + isDataInTimeline, noteIds, - onToggleShowNotes, - updateNote, - showTimelineModal, + onButtonClick, + onClosePopover, onCloseTimelineModal, + onOpenCaseModal, onOpenTimelineModal, - title, + onToggleShowNotes, + showActions, + showDescription, + showNotes, + showNotesFromWidth, + showTimelineModal, + showUsersView, status, -}) => ( - - - - - } - id="timelineSettingsPopover" - isOpen={showActions} - closePopover={onClosePopover} - > - - - - - - - - - - - - - - - { + const uiCapabilities = useKibana().services.application.capabilities; + const capabilitiesCanUserCRUD: boolean = !!uiCapabilities.securitySolution.crud; + return ( + + + + - + } + id="timelineSettingsPopover" + isOpen={showActions} + closePopover={onClosePopover} + > + + {capabilitiesCanUserCRUD && ( + + + + )} + + {/* + * CreateTemplateTimelineBtn + * Remove the comment here to enable CreateTemplateTimelineBtn + */} + {!disableTemplate && ( + + + + )} - {showNotesFromWidth ? ( - + + + + + + + - ) : null} - {showDescription ? ( - - - + - ) : null} - - - - - - {showUsersView - ? usersViewing.map((user) => ( - // Hide the hard-coded elastic user avatar as the 7.2 release does not implement - // support for multi-user-collaboration as proposed in elastic/ingest-dev#395 - - - - - - )) - : null} - - {showTimelineModal ? : null} - -); + + {showNotesFromWidth ? ( + + + + ) : null} + + {showDescription ? ( + + + + + + ) : null} + + + + + + {showUsersView + ? usersViewing.map((user) => ( + // Hide the hard-coded elastic user avatar as the 7.2 release does not implement + // support for multi-user-collaboration as proposed in elastic/ingest-dev#395 + + + + + + )) + : null} + + {showTimelineModal ? : null} + + ); +}; export const PropertiesRight = React.memo(PropertiesRightComponent); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/translations.ts b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/translations.ts index 88cbd3b1503f6..1621afc91cdbf 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/translations.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/translations.ts @@ -109,6 +109,13 @@ export const NEW_TIMELINE = i18n.translate( } ); +export const NEW_TEMPLATE_TIMELINE = i18n.translate( + 'xpack.securitySolution.timeline.properties.newTemplateTimelineButtonLabel', + { + defaultMessage: 'Create template timeline', + } +); + export const ATTACH_TIMELINE_TO_NEW_CASE = i18n.translate( 'xpack.securitySolution.timeline.properties.newCaseButtonLabel', { @@ -116,6 +123,13 @@ export const ATTACH_TIMELINE_TO_NEW_CASE = i18n.translate( } ); +export const ATTACH_TIMELINE_TO_EXISTING_CASE = i18n.translate( + 'xpack.securitySolution.timeline.properties.existingCaseButtonLabel', + { + defaultMessage: 'Attach timeline to existing case', + } +); + export const STREAM_LIVE = i18n.translate( 'xpack.securitySolution.timeline.properties.streamLiveButtonLabel', { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/use_create_timeline.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/use_create_timeline.test.tsx new file mode 100644 index 0000000000000..68a3362b721d8 --- /dev/null +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/use_create_timeline.test.tsx @@ -0,0 +1,60 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { renderHook, act } from '@testing-library/react-hooks'; +import { shallow } from 'enzyme'; + +import { TimelineType } from '../../../../../common/types/timeline'; +import { useCreateTimelineButton } from './use_create_timeline'; + +jest.mock('react-redux', () => { + const actual = jest.requireActual('react-redux'); + return { + ...actual, + useDispatch: jest.fn(), + }; +}); + +describe('useCreateTimelineButton', () => { + const mockId = 'mockId'; + const timelineType = TimelineType.default; + + test('return getButton', async () => { + await act(async () => { + const { result, waitForNextUpdate } = renderHook(() => + useCreateTimelineButton({ timelineId: mockId, timelineType }) + ); + await waitForNextUpdate(); + + expect(result.current.getButton).toBeTruthy(); + }); + }); + + test('getButton renders correct outline - EuiButton', async () => { + await act(async () => { + const { result, waitForNextUpdate } = renderHook(() => + useCreateTimelineButton({ timelineId: mockId, timelineType }) + ); + await waitForNextUpdate(); + + const button = result.current.getButton({ outline: true, title: 'mock title' }); + const wrapper = shallow(button); + expect(wrapper.find('[data-test-subj="timeline-new-with-border"]').exists()).toBeTruthy(); + }); + }); + + test('getButton renders correct outline - EuiButtonEmpty', async () => { + await act(async () => { + const { result, waitForNextUpdate } = renderHook(() => + useCreateTimelineButton({ timelineId: mockId, timelineType }) + ); + await waitForNextUpdate(); + + const button = result.current.getButton({ outline: false, title: 'mock title' }); + const wrapper = shallow(button); + expect(wrapper.find('[data-test-subj="timeline-new"]').exists()).toBeTruthy(); + }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/use_create_timeline.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/use_create_timeline.tsx new file mode 100644 index 0000000000000..fb05b056cdf82 --- /dev/null +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/use_create_timeline.tsx @@ -0,0 +1,66 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React, { useCallback } from 'react'; +import { useDispatch } from 'react-redux'; +import { EuiButton, EuiButtonEmpty } from '@elastic/eui'; +import { defaultHeaders } from '../body/column_headers/default_headers'; +import { timelineActions } from '../../../store/timeline'; +import { TimelineTypeLiteral, TimelineType } from '../../../../../common/types/timeline'; + +export const useCreateTimelineButton = ({ + timelineId, + timelineType, + closeGearMenu, +}: { + timelineId?: string; + timelineType: TimelineTypeLiteral; + closeGearMenu?: () => void; +}) => { + const dispatch = useDispatch(); + + const createTimeline = useCallback( + ({ id, show }) => + dispatch( + timelineActions.createTimeline({ + id, + columns: defaultHeaders, + show, + timelineType, + }) + ), + [dispatch, timelineType] + ); + + const handleButtonClick = useCallback(() => { + createTimeline({ id: timelineId, show: true, timelineType }); + if (typeof closeGearMenu === 'function') { + closeGearMenu(); + } + }, [createTimeline, timelineId, timelineType, closeGearMenu]); + + const getButton = useCallback( + ({ outline, title }: { outline?: boolean; title?: string }) => { + const buttonProps = { + iconType: 'plusInCircle', + onClick: handleButtonClick, + }; + const dataTestSubjPrefix = + timelineType === TimelineType.template ? `template-timeline-new` : `timeline-new`; + return outline ? ( + + {title} + + ) : ( + + {title} + + ); + }, + [handleButtonClick, timelineType] + ); + + return { getButton }; +}; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.test.tsx index b07be4a471a70..2447ebf47463f 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.test.tsx @@ -26,11 +26,36 @@ import { mockDataProviders } from './data_providers/mock/mock_data_providers'; import { useMountAppended } from '../../../common/utils/use_mount_appended'; jest.mock('../../../common/lib/kibana'); - +jest.mock('./properties/properties_right'); const mockUseResizeObserver: jest.Mock = useResizeObserver as jest.Mock; jest.mock('use-resize-observer/polyfilled'); + mockUseResizeObserver.mockImplementation(() => ({})); +jest.mock('react-router-dom', () => { + const originalModule = jest.requireActual('react-router-dom'); + return { + ...originalModule, + useHistory: jest.fn(), + }; +}); +jest.mock('../../../common/lib/kibana', () => { + const originalModule = jest.requireActual('../../../common/lib/kibana'); + return { + ...originalModule, + useKibana: jest.fn().mockReturnValue({ + services: { + uiSettings: { + get: jest.fn(), + }, + savedObjects: { + client: {}, + }, + }, + }), + useGetUserSavedObjectPermissions: jest.fn(), + }; +}); describe('Timeline', () => { let props = {} as TimelineComponentProps; const sort: Sort = { diff --git a/x-pack/plugins/security_solution/public/timelines/containers/all/index.gql_query.ts b/x-pack/plugins/security_solution/public/timelines/containers/all/index.gql_query.ts index cdbf3e768581b..60d000fe78184 100644 --- a/x-pack/plugins/security_solution/public/timelines/containers/all/index.gql_query.ts +++ b/x-pack/plugins/security_solution/public/timelines/containers/all/index.gql_query.ts @@ -56,6 +56,7 @@ export const allTimelinesQuery = gql` } noteIds pinnedEventIds + status title timelineType templateTimelineId diff --git a/x-pack/plugins/security_solution/public/timelines/containers/api.test.ts b/x-pack/plugins/security_solution/public/timelines/containers/api.test.ts new file mode 100644 index 0000000000000..26373fa1a825d --- /dev/null +++ b/x-pack/plugins/security_solution/public/timelines/containers/api.test.ts @@ -0,0 +1,503 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import * as api from './api'; +import { KibanaServices } from '../../common/lib/kibana'; +import { TimelineType, TimelineStatus } from '../../../common/types/timeline'; +import { TIMELINE_DRAFT_URL, TIMELINE_URL } from '../../../common/constants'; + +jest.mock('../../common/lib/kibana', () => { + return { + KibanaServices: { get: jest.fn() }, + }; +}); + +describe('persistTimeline', () => { + describe('create draft timeline', () => { + const timelineId = null; + const initialDraftTimeline = { + columns: [ + { + columnHeaderType: 'not-filtered', + id: '@timestamp', + }, + { + columnHeaderType: 'not-filtered', + id: 'message', + }, + { + columnHeaderType: 'not-filtered', + id: 'event.category', + }, + { + columnHeaderType: 'not-filtered', + id: 'event.action', + }, + { + columnHeaderType: 'not-filtered', + id: 'host.name', + }, + { + columnHeaderType: 'not-filtered', + id: 'source.ip', + }, + { + columnHeaderType: 'not-filtered', + id: 'destination.ip', + }, + { + columnHeaderType: 'not-filtered', + id: 'user.name', + }, + ], + dataProviders: [], + description: 'x', + eventType: 'all', + filters: [], + kqlMode: 'filter', + kqlQuery: { + filterQuery: null, + }, + title: '', + timelineType: TimelineType.default, + templateTimelineVersion: null, + templateTimelineId: null, + dateRange: { + start: 1590998565409, + end: 1591084965409, + }, + savedQueryId: null, + sort: { + columnId: '@timestamp', + sortDirection: 'desc', + }, + status: TimelineStatus.draft, + }; + const mockDraftResponse = { + data: { + persistTimeline: { + timeline: { + savedObjectId: '9d5693e0-a42a-11ea-b8f4-c5434162742a', + version: 'WzMzMiwxXQ==', + columns: [ + { columnHeaderType: 'not-filtered', id: '@timestamp' }, + { columnHeaderType: 'not-filtered', id: 'message' }, + { columnHeaderType: 'not-filtered', id: 'event.category' }, + { columnHeaderType: 'not-filtered', id: 'event.action' }, + { columnHeaderType: 'not-filtered', id: 'host.name' }, + { columnHeaderType: 'not-filtered', id: 'source.ip' }, + { columnHeaderType: 'not-filtered', id: 'destination.ip' }, + { columnHeaderType: 'not-filtered', id: 'user.name' }, + ], + dataProviders: [], + description: '', + eventType: 'all', + filters: [], + kqlMode: 'filter', + timelineType: 'default', + kqlQuery: { filterQuery: null }, + title: '', + sort: { columnId: '@timestamp', sortDirection: 'desc' }, + status: 'draft', + created: 1591091394733, + createdBy: 'angela', + updated: 1591091394733, + updatedBy: 'angela', + templateTimelineId: null, + templateTimelineVersion: null, + dateRange: { start: 1590998565409, end: 1591084965409 }, + savedQueryId: null, + favorite: [], + eventIdToNoteIds: [], + noteIds: [], + notes: [], + pinnedEventIds: [], + pinnedEventsSaveObject: [], + }, + }, + }, + }; + const mockPatchTimelineResponse = { + data: { + persistTimeline: { + code: 200, + message: 'success', + timeline: { + savedObjectId: '9d5693e0-a42a-11ea-b8f4-c5434162742a', + version: 'WzM0NSwxXQ==', + columns: [ + { columnHeaderType: 'not-filtered', id: '@timestamp' }, + { columnHeaderType: 'not-filtered', id: 'message' }, + { columnHeaderType: 'not-filtered', id: 'event.category' }, + { columnHeaderType: 'not-filtered', id: 'event.action' }, + { columnHeaderType: 'not-filtered', id: 'host.name' }, + { columnHeaderType: 'not-filtered', id: 'source.ip' }, + { columnHeaderType: 'not-filtered', id: 'destination.ip' }, + { columnHeaderType: 'not-filtered', id: 'user.name' }, + ], + dataProviders: [], + description: 'x', + eventType: 'all', + filters: [], + kqlMode: 'filter', + timelineType: 'default', + kqlQuery: { filterQuery: null }, + title: '', + sort: { columnId: '@timestamp', sortDirection: 'desc' }, + status: 'draft', + created: 1591092702804, + createdBy: 'angela', + updated: 1591092705206, + updatedBy: 'angela', + templateTimelineId: null, + templateTimelineVersion: null, + dateRange: { start: 1590998565409, end: 1591084965409 }, + savedQueryId: null, + favorite: [], + eventIdToNoteIds: [], + noteIds: [], + notes: [], + pinnedEventIds: [], + pinnedEventsSaveObject: [], + }, + }, + }, + }; + const version = null; + const fetchMock = jest.fn(); + const postMock = jest.fn(); + const patchMock = jest.fn(); + + beforeAll(() => { + jest.resetAllMocks(); + + (KibanaServices.get as jest.Mock).mockReturnValue({ + http: { + fetch: fetchMock, + post: postMock.mockReturnValue(mockDraftResponse), + patch: patchMock.mockReturnValue(mockPatchTimelineResponse), + }, + }); + api.persistTimeline({ timelineId, timeline: initialDraftTimeline, version }); + }); + + afterAll(() => { + jest.resetAllMocks(); + }); + + test('it should create a draft timeline if given status is draft and timelineId is null', () => { + expect(postMock).toHaveBeenCalledWith(TIMELINE_DRAFT_URL, { + body: JSON.stringify({ + timelineType: initialDraftTimeline.timelineType, + }), + }); + }); + + test('it should update timeline', () => { + expect(patchMock.mock.calls[0][0]).toEqual(TIMELINE_URL); + }); + + test('it should update timeline with patch', () => { + expect(patchMock.mock.calls[0][1].method).toEqual('PATCH'); + }); + + test("it should update timeline from clean draft timeline's response", () => { + expect(JSON.parse(patchMock.mock.calls[0][1].body)).toEqual({ + timelineId: mockDraftResponse.data.persistTimeline.timeline.savedObjectId, + timeline: { + ...initialDraftTimeline, + templateTimelineId: mockDraftResponse.data.persistTimeline.timeline.templateTimelineId, + templateTimelineVersion: + mockDraftResponse.data.persistTimeline.timeline.templateTimelineVersion, + }, + version: mockDraftResponse.data.persistTimeline.timeline.version ?? '', + }); + }); + }); + + describe('create active timeline (import)', () => { + const timelineId = null; + const importTimeline = { + columns: [ + { + columnHeaderType: 'not-filtered', + id: '@timestamp', + }, + { + columnHeaderType: 'not-filtered', + id: 'message', + }, + { + columnHeaderType: 'not-filtered', + id: 'event.category', + }, + { + columnHeaderType: 'not-filtered', + id: 'event.action', + }, + { + columnHeaderType: 'not-filtered', + id: 'host.name', + }, + { + columnHeaderType: 'not-filtered', + id: 'source.ip', + }, + { + columnHeaderType: 'not-filtered', + id: 'destination.ip', + }, + { + columnHeaderType: 'not-filtered', + id: 'user.name', + }, + ], + dataProviders: [], + description: 'x', + eventType: 'all', + filters: [], + kqlMode: 'filter', + kqlQuery: { + filterQuery: null, + }, + title: '', + timelineType: TimelineType.default, + templateTimelineVersion: null, + templateTimelineId: null, + dateRange: { + start: 1590998565409, + end: 1591084965409, + }, + savedQueryId: null, + sort: { + columnId: '@timestamp', + sortDirection: 'desc', + }, + status: TimelineStatus.active, + }; + const mockPostTimelineResponse = { + data: { + persistTimeline: { + timeline: { + savedObjectId: '9d5693e0-a42a-11ea-b8f4-c5434162742a', + version: 'WzMzMiwxXQ==', + columns: [ + { columnHeaderType: 'not-filtered', id: '@timestamp' }, + { columnHeaderType: 'not-filtered', id: 'message' }, + { columnHeaderType: 'not-filtered', id: 'event.category' }, + { columnHeaderType: 'not-filtered', id: 'event.action' }, + { columnHeaderType: 'not-filtered', id: 'host.name' }, + { columnHeaderType: 'not-filtered', id: 'source.ip' }, + { columnHeaderType: 'not-filtered', id: 'destination.ip' }, + { columnHeaderType: 'not-filtered', id: 'user.name' }, + ], + dataProviders: [], + description: '', + eventType: 'all', + filters: [], + kqlMode: 'filter', + timelineType: 'default', + kqlQuery: { filterQuery: null }, + title: '', + sort: { columnId: '@timestamp', sortDirection: 'desc' }, + status: 'draft', + created: 1591091394733, + createdBy: 'angela', + updated: 1591091394733, + updatedBy: 'angela', + templateTimelineId: null, + templateTimelineVersion: null, + dateRange: { start: 1590998565409, end: 1591084965409 }, + savedQueryId: null, + favorite: [], + eventIdToNoteIds: [], + noteIds: [], + notes: [], + pinnedEventIds: [], + pinnedEventsSaveObject: [], + }, + }, + }, + }; + + const version = null; + const fetchMock = jest.fn(); + const postMock = jest.fn(); + const patchMock = jest.fn(); + + beforeAll(() => { + jest.resetAllMocks(); + + (KibanaServices.get as jest.Mock).mockReturnValue({ + http: { + fetch: fetchMock, + post: postMock.mockReturnValue(mockPostTimelineResponse), + patch: patchMock, + }, + }); + api.persistTimeline({ timelineId, timeline: importTimeline, version }); + }); + + afterAll(() => { + jest.resetAllMocks(); + }); + + test('it should update timeline', () => { + expect(postMock.mock.calls[0][0]).toEqual(TIMELINE_URL); + }); + + test('it should update timeline with patch', () => { + expect(postMock.mock.calls[0][1].method).toEqual('POST'); + }); + + test('should call create timeline', () => { + expect(JSON.parse(postMock.mock.calls[0][1].body)).toEqual({ timeline: importTimeline }); + }); + }); + + describe('update active timeline', () => { + const timelineId = '9d5693e0-a42a-11ea-b8f4-c5434162742a'; + const inputTimeline = { + columns: [ + { + columnHeaderType: 'not-filtered', + id: '@timestamp', + }, + { + columnHeaderType: 'not-filtered', + id: 'message', + }, + { + columnHeaderType: 'not-filtered', + id: 'event.category', + }, + { + columnHeaderType: 'not-filtered', + id: 'event.action', + }, + { + columnHeaderType: 'not-filtered', + id: 'host.name', + }, + { + columnHeaderType: 'not-filtered', + id: 'source.ip', + }, + { + columnHeaderType: 'not-filtered', + id: 'destination.ip', + }, + { + columnHeaderType: 'not-filtered', + id: 'user.name', + }, + ], + dataProviders: [], + description: 'x', + eventType: 'all', + filters: [], + kqlMode: 'filter', + kqlQuery: { + filterQuery: null, + }, + title: '', + timelineType: TimelineType.default, + templateTimelineVersion: null, + templateTimelineId: null, + dateRange: { + start: 1590998565409, + end: 1591084965409, + }, + savedQueryId: null, + sort: { + columnId: '@timestamp', + sortDirection: 'desc', + }, + status: TimelineStatus.active, + }; + const mockPatchTimelineResponse = { + data: { + persistTimeline: { + timeline: { + savedObjectId: '9d5693e0-a42a-11ea-b8f4-c5434162742a', + version: 'WzMzMiwxXQ==', + columns: [ + { columnHeaderType: 'not-filtered', id: '@timestamp' }, + { columnHeaderType: 'not-filtered', id: 'message' }, + { columnHeaderType: 'not-filtered', id: 'event.category' }, + { columnHeaderType: 'not-filtered', id: 'event.action' }, + { columnHeaderType: 'not-filtered', id: 'host.name' }, + { columnHeaderType: 'not-filtered', id: 'source.ip' }, + { columnHeaderType: 'not-filtered', id: 'destination.ip' }, + { columnHeaderType: 'not-filtered', id: 'user.name' }, + ], + dataProviders: [], + description: '', + eventType: 'all', + filters: [], + kqlMode: 'filter', + timelineType: 'default', + kqlQuery: { filterQuery: null }, + title: '', + sort: { columnId: '@timestamp', sortDirection: 'desc' }, + status: 'draft', + created: 1591091394733, + createdBy: 'angela', + updated: 1591091394733, + updatedBy: 'angela', + templateTimelineId: null, + templateTimelineVersion: null, + dateRange: { start: 1590998565409, end: 1591084965409 }, + savedQueryId: null, + favorite: [], + eventIdToNoteIds: [], + noteIds: [], + notes: [], + pinnedEventIds: [], + pinnedEventsSaveObject: [], + }, + }, + }, + }; + + const version = 'initial version'; + const fetchMock = jest.fn(); + const postMock = jest.fn(); + const patchMock = jest.fn(); + + beforeAll(() => { + jest.resetAllMocks(); + + (KibanaServices.get as jest.Mock).mockReturnValue({ + http: { + fetch: fetchMock, + post: postMock, + patch: patchMock.mockReturnValue(mockPatchTimelineResponse), + }, + }); + api.persistTimeline({ timelineId, timeline: inputTimeline, version }); + }); + + afterAll(() => { + jest.resetAllMocks(); + }); + + test('it should update timeline', () => { + expect(patchMock.mock.calls[0][0]).toEqual(TIMELINE_URL); + }); + + test('it should update timeline with patch', () => { + expect(patchMock.mock.calls[0][1].method).toEqual('PATCH'); + }); + + test('should call patch timeline', () => { + expect(JSON.parse(patchMock.mock.calls[0][1].body)).toEqual({ + timeline: inputTimeline, + timelineId, + version, + }); + }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/timelines/containers/api.ts b/x-pack/plugins/security_solution/public/timelines/containers/api.ts index 9f5e65e0fc5af..10893feccfed4 100644 --- a/x-pack/plugins/security_solution/public/timelines/containers/api.ts +++ b/x-pack/plugins/security_solution/public/timelines/containers/api.ts @@ -77,9 +77,15 @@ export const persistTimeline = async ({ }: RequestPersistTimeline): Promise => { if (timelineId == null && timeline.status === TimelineStatus.draft) { const draftTimeline = await cleanDraftTimeline({ timelineType: timeline.timelineType! }); + return patchTimeline({ timelineId: draftTimeline.data.persistTimeline.timeline.savedObjectId, - timeline, + timeline: { + ...timeline, + templateTimelineId: draftTimeline.data.persistTimeline.timeline.templateTimelineId, + templateTimelineVersion: + draftTimeline.data.persistTimeline.timeline.templateTimelineVersion, + }, version: draftTimeline.data.persistTimeline.timeline.version ?? '', }); } diff --git a/x-pack/plugins/security_solution/public/timelines/pages/timelines_page.test.tsx b/x-pack/plugins/security_solution/public/timelines/pages/timelines_page.test.tsx index 1fc3a33fbca08..e7b66c4e8addb 100644 --- a/x-pack/plugins/security_solution/public/timelines/pages/timelines_page.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/pages/timelines_page.test.tsx @@ -10,6 +10,7 @@ import React from 'react'; import { useKibana } from '../../common/lib/kibana'; import { TimelinesPageComponent } from './timelines_page'; +import { disableTemplate } from '../../../common/constants'; jest.mock('../../overview/components/events_by_dataset'); @@ -18,6 +19,7 @@ jest.mock('../../common/lib/kibana', () => { useKibana: jest.fn(), }; }); + describe('TimelinesPageComponent', () => { const mockAppollloClient = {} as ApolloClient; let wrapper: ShallowWrapper; @@ -58,6 +60,20 @@ describe('TimelinesPageComponent', () => { wrapper.find('[data-test-subj="stateful-open-timeline"]').prop('importDataModalToggle') ).toEqual(true); }); + + test('it renders create timelin btn', () => { + expect(wrapper.find('[data-test-subj="create-default-btn"]').exists()).toBeTruthy(); + }); + + /* + * CreateTemplateTimelineBtn + * Remove the comment here to enable CreateTemplateTimelineBtn + */ + test('it renders no create template timelin btn', () => { + expect(wrapper.find('[data-test-subj="create-template-btn"]').exists()).toEqual( + !disableTemplate + ); + }); }); describe('If the user is not authorised', () => { diff --git a/x-pack/plugins/security_solution/public/timelines/pages/timelines_page.tsx b/x-pack/plugins/security_solution/public/timelines/pages/timelines_page.tsx index fd734d10ecba0..2c692d850cd16 100644 --- a/x-pack/plugins/security_solution/public/timelines/pages/timelines_page.tsx +++ b/x-pack/plugins/security_solution/public/timelines/pages/timelines_page.tsx @@ -4,15 +4,23 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiButton } from '@elastic/eui'; +import { EuiButton, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import ApolloClient from 'apollo-client'; import React, { useCallback, useState } from 'react'; import styled from 'styled-components'; + +import { disableTemplate } from '../../../common/constants'; + import { HeaderPage } from '../../common/components/header_page'; import { WrapperPage } from '../../common/components/wrapper_page'; import { useKibana } from '../../common/lib/kibana'; import { SpyRoute } from '../../common/utils/route/spy_routes'; + import { StatefulOpenTimeline } from '../components/open_timeline'; +import { NEW_TEMPLATE_TIMELINE } from '../components/timeline/properties/translations'; +import { NewTemplateTimeline } from '../components/timeline/properties/new_template_timeline'; +import { NewTimeline } from '../components/timeline/properties/helpers'; + import * as i18n from './translations'; const TimelinesContainer = styled.div` @@ -34,24 +42,47 @@ export const TimelinesPageComponent: React.FC = ({ apolloClient }) => }, [setImportDataModalToggle]); const uiCapabilities = useKibana().services.application.capabilities; - const capabilitiesCanUserCRUD: boolean = - typeof uiCapabilities.securitySolution.crud === 'boolean' - ? uiCapabilities.securitySolution.crud - : false; + const capabilitiesCanUserCRUD: boolean = !!uiCapabilities.securitySolution.crud; return ( <> - {capabilitiesCanUserCRUD && ( - - {i18n.ALL_TIMELINES_IMPORT_TIMELINE_TITLE} - - )} + + + {capabilitiesCanUserCRUD && ( + + {i18n.ALL_TIMELINES_IMPORT_TIMELINE_TITLE} + + )} + + + {capabilitiesCanUserCRUD && ( + + )} + + {/** + * CreateTemplateTimelineBtn + * Remove the comment here to enable CreateTemplateTimelineBtn + */} + {!disableTemplate && ( + + + + )} + diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/actions.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/actions.ts index e11d1bcc72e09..c5df017604b0c 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/actions.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/actions.ts @@ -16,6 +16,8 @@ import { KueryFilterQuery, SerializedFilterQuery } from '../../../common/store/t import { EventType, KqlMode, TimelineModel, ColumnHeaderOptions } from './model'; import { TimelineNonEcsData } from '../../../graphql/types'; +import { TimelineTypeLiteral } from '../../../../common/types/timeline'; +import { InsertTimeline } from './types'; const actionCreator = actionCreatorFactory('x-pack/security_solution/local/timeline'); @@ -67,6 +69,7 @@ export const createTimeline = actionCreator<{ sort?: Sort; showCheckboxes?: boolean; showRowRenderers?: boolean; + timelineType?: TimelineTypeLiteral; }>('CREATE_TIMELINE'); export const pinEvent = actionCreator<{ id: string; eventId: string }>('PIN_EVENT'); @@ -96,6 +99,8 @@ export const addTimeline = actionCreator<{ timeline: TimelineModel; }>('ADD_TIMELINE'); +export const setInsertTimeline = actionCreator('SET_INSERT_TIMELINE'); + export const startTimelineSaving = actionCreator<{ id: string; }>('START_TIMELINE_SAVING'); diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/helpers.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/helpers.ts index b2472cbe89a50..03e9ca176ee82 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/helpers.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/helpers.ts @@ -7,6 +7,9 @@ import { getOr, omit, uniq, isEmpty, isEqualWith, union } from 'lodash/fp'; import { Filter } from '../../../../../../../src/plugins/data/public'; + +import { disableTemplate } from '../../../../common/constants'; + import { getColumnWidthFromType } from '../../../timelines/components/timeline/body/column_headers/helpers'; import { Sort } from '../../../timelines/components/timeline/body/sort'; import { @@ -15,11 +18,12 @@ import { QueryMatch, } from '../../../timelines/components/timeline/data_providers/data_provider'; import { KueryFilterQuery, SerializedFilterQuery } from '../../../common/store/model'; +import { TimelineNonEcsData } from '../../../graphql/types'; +import { TimelineTypeLiteral } from '../../../../common/types/timeline'; import { timelineDefaults } from './defaults'; import { ColumnHeaderOptions, KqlMode, TimelineModel, EventType } from './model'; import { TimelineById, TimelineState } from './types'; -import { TimelineNonEcsData } from '../../../graphql/types'; const EMPTY_TIMELINE_BY_ID: TimelineById = {}; // stable reference @@ -32,6 +36,7 @@ export const initialTimelineState: TimelineState = { newTimelineModel: null, }, showCallOutUnauthorizedMsg: false, + insertTimeline: null, }; interface AddTimelineHistoryParams { @@ -147,6 +152,7 @@ interface AddNewTimelineParams { showCheckboxes?: boolean; showRowRenderers?: boolean; timelineById: TimelineById; + timelineType: TimelineTypeLiteral; } /** Adds a new `Timeline` to the provided collection of `TimelineById` */ @@ -163,6 +169,7 @@ export const addNewTimeline = ({ showCheckboxes = false, showRowRenderers = true, timelineById, + timelineType, }: AddNewTimelineParams): TimelineById => ({ ...timelineById, [id]: { @@ -182,6 +189,7 @@ export const addNewTimeline = ({ isLoading: false, showCheckboxes, showRowRenderers, + timelineType: !disableTemplate ? timelineType : timelineDefaults.timelineType, }, }); diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.test.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.test.ts index d17bc1f20e1e8..3bdb16be79939 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.test.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.test.ts @@ -139,6 +139,7 @@ describe('Timeline', () => { id: 'bar', columns: defaultHeaders, timelineById: timelineByIdMock, + timelineType: TimelineType.default, }); expect(update).not.toBe(timelineByIdMock); }); @@ -148,6 +149,7 @@ describe('Timeline', () => { id: 'bar', columns: timelineDefaults.columns, timelineById: timelineByIdMock, + timelineType: TimelineType.default, }); expect(update).toEqual({ foo: timelineByIdMock.foo, @@ -163,6 +165,7 @@ describe('Timeline', () => { id: 'bar', columns: defaultHeaders, timelineById: timelineByIdMock, + timelineType: TimelineType.default, }); expect(update).toEqual({ foo: timelineByIdMock.foo, diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.ts index a8ae39527cdbf..5e314f1597451 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.ts @@ -6,14 +6,17 @@ import { reducerWithInitialState } from 'typescript-fsa-reducers'; import { - addTimeline, addHistory, addNote, addNoteToEvent, addProvider, + addTimeline, applyDeltaToColumnWidth, applyDeltaToWidth, applyKqlFilterQuery, + clearEventsDeleted, + clearEventsLoading, + clearSelected, createTimeline, dataProviderEdited, endTimelineSaving, @@ -21,12 +24,12 @@ import { removeColumn, removeProvider, setEventsDeleted, - clearEventsDeleted, setEventsLoading, - clearEventsLoading, + setFilters, + setInsertTimeline, setKqlFilterQueryDraft, + setSavedQueryId, setSelected, - clearSelected, showCallOutUnauthorizedMsg, showTimeline, startTimelineSaving, @@ -37,9 +40,11 @@ import { updateDataProviderExcluded, updateDataProviderKqlQuery, updateDescription, + updateEventType, updateHighlightedDropAndProviderId, updateIsFavorite, updateIsLive, + updateIsLoading, updateItemsPerPage, updateItemsPerPageOptions, updateKqlMode, @@ -50,10 +55,6 @@ import { updateTimeline, updateTitle, upsertColumn, - updateIsLoading, - setSavedQueryId, - setFilters, - updateEventType, } from './actions'; import { addNewTimeline, @@ -98,6 +99,7 @@ import { } from './helpers'; import { TimelineState, EMPTY_TIMELINE_BY_ID } from './types'; +import { TimelineType } from '../../../../common/types/timeline'; export const initialTimelineState: TimelineState = { timelineById: EMPTY_TIMELINE_BY_ID, @@ -106,6 +108,7 @@ export const initialTimelineState: TimelineState = { newTimelineModel: null, }, showCallOutUnauthorizedMsg: false, + insertTimeline: null, }; /** The reducer for all timeline actions */ @@ -129,6 +132,7 @@ export const timelineReducer = reducerWithInitialState(initialTimelineState) sort, showCheckboxes, showRowRenderers, + timelineType = TimelineType.default, filters, } ) => ({ @@ -146,6 +150,7 @@ export const timelineReducer = reducerWithInitialState(initialTimelineState) showCheckboxes, showRowRenderers, timelineById: state.timelineById, + timelineType, }), }) ) @@ -483,4 +488,8 @@ export const timelineReducer = reducerWithInitialState(initialTimelineState) timelineById: state.timelineById, }), })) + .case(setInsertTimeline, (state, insertTimeline) => ({ + ...state, + insertTimeline, + })) .build(); diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/selectors.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/selectors.ts index af7ac075468c3..a80a28660e28b 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/selectors.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/selectors.ts @@ -10,7 +10,7 @@ import { isFromKueryExpressionValid } from '../../../common/lib/keury'; import { State } from '../../../common/store/types'; import { TimelineModel } from './model'; -import { AutoSavedWarningMsg, TimelineById } from './types'; +import { AutoSavedWarningMsg, InsertTimeline, TimelineById } from './types'; const selectTimelineById = (state: State): TimelineById => state.timeline.timelineById; @@ -22,6 +22,9 @@ const selectCallOutUnauthorizedMsg = (state: State): boolean => export const selectTimeline = (state: State, timelineId: string): TimelineModel => state.timeline.timelineById[timelineId]; +export const selectInsertTimeline = (state: State): InsertTimeline | null => + state.timeline.insertTimeline; + export const autoSaveMsgSelector = createSelector(selectAutoSaveMsg, (autoSaveMsg) => autoSaveMsg); export const timelineByIdSelector = createSelector( diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/types.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/types.ts index 1cc4517d2c964..aa6c308614287 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/types.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/types.ts @@ -16,6 +16,12 @@ export interface TimelineById { [id: string]: TimelineModel; } +export interface InsertTimeline { + timelineId: string; + timelineSavedObjectId: string | null; + timelineTitle: string; +} + export const EMPTY_TIMELINE_BY_ID: TimelineById = {}; // stable reference /** The state of all timelines is stored here */ @@ -23,6 +29,7 @@ export interface TimelineState { timelineById: TimelineById; autoSavedWarningMsg: AutoSavedWarningMsg; showCallOutUnauthorizedMsg: boolean; + insertTimeline: InsertTimeline | null; } export interface ActionTimeline extends Action { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_responses.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_responses.ts index 9246d8cb3519b..23d5d7eb8d385 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_responses.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_responses.ts @@ -6,11 +6,7 @@ import { SavedObjectsFindResponse } from 'kibana/server'; import { ActionResult } from '../../../../../../actions/server'; -import { - SignalsStatusRestParams, - SignalsQueryRestParams, - SignalSearchResponse, -} from '../../signals/types'; +import { SignalSearchResponse } from '../../signals/types'; import { DETECTION_ENGINE_RULES_URL, DETECTION_ENGINE_SIGNALS_STATUS_URL, @@ -26,45 +22,11 @@ import { IRuleSavedAttributesSavedObjectAttributes, HapiReadableStream, } from '../../rules/types'; -import { RuleAlertParamsRest, PrepackagedRules } from '../../types'; +import { RuleAlertParamsRest } from '../../types'; import { requestMock } from './request'; import { RuleNotificationAlertType } from '../../notifications/types'; - -export const mockPrepackagedRule = (): PrepackagedRules => ({ - rule_id: 'rule-1', - description: 'Detecting root and admin users', - index: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], - interval: '5m', - name: 'Detect Root/Admin Users', - output_index: '.siem-signals', - risk_score: 50, - type: 'query', - from: 'now-6m', - to: 'now', - severity: 'high', - query: 'user.name: root or user.name: admin', - language: 'kuery', - threat: [ - { - framework: 'fake', - tactic: { id: 'fakeId', name: 'fakeName', reference: 'fakeRef' }, - technique: [{ id: 'techniqueId', name: 'techniqueName', reference: 'techniqueRef' }], - }, - ], - throttle: null, - enabled: true, - filters: [], - immutable: false, - references: [], - meta: {}, - tags: [], - version: 1, - false_positives: [], - max_signals: 100, - note: '', - timeline_id: 'timeline-id', - timeline_title: 'timeline-title', -}); +import { QuerySignalsSchemaDecoded } from '../../../../../common/detection_engine/schemas/request/query_signals_index_schema'; +import { SetSignalsStatusSchemaDecoded } from '../../../../../common/detection_engine/schemas/request/set_signal_status_schema'; export const typicalPayload = (): Partial => ({ rule_id: 'rule-1', @@ -89,25 +51,25 @@ export const typicalPayload = (): Partial => ({ ], }); -export const typicalSetStatusSignalByIdsPayload = (): Partial => ({ +export const typicalSetStatusSignalByIdsPayload = (): SetSignalsStatusSchemaDecoded => ({ signal_ids: ['somefakeid1', 'somefakeid2'], status: 'closed', }); -export const typicalSetStatusSignalByQueryPayload = (): Partial => ({ +export const typicalSetStatusSignalByQueryPayload = (): SetSignalsStatusSchemaDecoded => ({ query: { bool: { filter: { range: { '@timestamp': { gte: 'now-2M', lte: 'now/M' } } } } }, status: 'closed', }); -export const typicalSignalsQuery = (): Partial => ({ +export const typicalSignalsQuery = (): QuerySignalsSchemaDecoded => ({ query: { match_all: {} }, }); -export const typicalSignalsQueryAggs = (): Partial => ({ +export const typicalSignalsQueryAggs = (): QuerySignalsSchemaDecoded => ({ aggs: { statuses: { terms: { field: 'signal.status', size: 10 } } }, }); -export const setStatusSignalMissingIdsAndQueryPayload = (): Partial => ({ +export const setStatusSignalMissingIdsAndQueryPayload = (): SetSignalsStatusSchemaDecoded => ({ status: 'closed', }); @@ -170,14 +132,14 @@ export const getDeleteBulkRequestById = () => requestMock.create({ method: 'delete', path: `${DETECTION_ENGINE_RULES_URL}/_bulk_delete`, - body: [{ id: 'rule-04128c15-0d1b-4716-a4c5-46997ac7f3bd' }], + body: [{ id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd' }], }); export const getDeleteAsPostBulkRequestById = () => requestMock.create({ method: 'post', path: `${DETECTION_ENGINE_RULES_URL}/_bulk_delete`, - body: [{ id: 'rule-04128c15-0d1b-4716-a4c5-46997ac7f3bd' }], + body: [{ id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd' }], }); export const getDeleteAsPostBulkRequest = () => @@ -448,7 +410,7 @@ export const getResult = (): RuleAlertType => ({ references: ['http://www.example.com', 'https://ww.example.com'], note: '# Investigative notes', version: 1, - exceptions_list: [ + exceptionsList: [ { field: 'source.ip', values_operator: 'included', diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts index 241d362753d53..4b65ee5efdff0 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts @@ -13,18 +13,16 @@ import { } from '../__mocks__/request_responses'; import { requestContextMock, serverMock } from '../__mocks__'; import { addPrepackedRulesRoute } from './add_prepackaged_rules_route'; -import { PrepackagedRules } from '../../types'; import { setFeatureFlagsForTestsOnly, unSetFeatureFlagsForTestsOnly } from '../../feature_flags'; +import { AddPrepackagedRulesSchemaDecoded } from '../../../../../common/detection_engine/schemas/request/add_prepackaged_rules_schema'; jest.mock('../../rules/get_prepackaged_rules', () => { return { - getPrepackagedRules: (): PrepackagedRules[] => { + getPrepackagedRules: (): AddPrepackagedRulesSchemaDecoded[] => { return [ { tags: [], - immutable: true, rule_id: 'rule-1', - output_index: '.siem-signals', risk_score: 50, description: 'some description', from: 'now-5m', @@ -34,6 +32,16 @@ jest.mock('../../rules/get_prepackaged_rules', () => { severity: 'low', interval: '5m', type: 'query', + query: 'user.name: root or user.name: admin', + language: 'kuery', + references: [], + actions: [], + enabled: false, + false_positives: [], + max_signals: 100, + threat: [], + throttle: null, + exceptions_list: [], version: 2, // set one higher than the mocks which is set to 1 to trigger updates }, ]; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts index d5628877ee16e..39eea16c6290a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts @@ -29,7 +29,7 @@ export const addPrepackedRulesRoute = (router: IRouter) => { tags: ['access:securitySolution'], }, }, - async (context, request, response) => { + async (context, _, response) => { const siemResponse = buildSiemResponse(response); try { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.test.ts index 6875b0fc76ecc..1df6070bc33a6 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.test.ts @@ -180,7 +180,7 @@ describe('create_rules_bulk', () => { const result = server.validate(request); expect(result.badRequest).toHaveBeenCalledWith( - '"value" at position 0 fails because [child "type" fails because ["type" must be one of [query, saved_query, machine_learning]]]' + 'Invalid value "unexpected_type" supplied to "type"' ); }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts index dc0b65cef61d0..7af58adca7529 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts @@ -4,8 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ -import uuid from 'uuid'; - +import { createRuleValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/create_rules_type_dependents'; +import { RuleAlertAction } from '../../../../../common/detection_engine/types'; +import { + CreateRulesBulkSchemaDecoded, + createRulesBulkSchema, +} from '../../../../../common/detection_engine/schemas/request/create_rules_bulk_schema'; import { rulesBulkSchema } from '../../../../../common/detection_engine/schemas/response/rules_bulk_schema'; import { IRouter } from '../../../../../../../../src/core/server'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; @@ -13,26 +17,24 @@ import { SetupPlugins } from '../../../../plugin'; import { buildMlAuthz } from '../../../machine_learning/authz'; import { throwHttpError } from '../../../machine_learning/validation'; import { createRules } from '../../rules/create_rules'; -import { RuleAlertParamsRest } from '../../types'; import { readRules } from '../../rules/read_rules'; import { getDuplicates } from './utils'; import { transformValidateBulkError, validate } from './validate'; import { getIndexExists } from '../../index/get_index_exists'; -import { - transformBulkError, - createBulkErrorObject, - buildRouteValidation, - buildSiemResponse, -} from '../utils'; -import { createRulesBulkSchema } from '../schemas/create_rules_bulk_schema'; +import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; + +import { transformBulkError, createBulkErrorObject, buildSiemResponse } from '../utils'; import { updateRulesNotifications } from '../../rules/update_rules_notifications'; +import { PartialFilter } from '../../types'; export const createRulesBulkRoute = (router: IRouter, ml: SetupPlugins['ml']) => { router.post( { path: `${DETECTION_ENGINE_RULES_URL}/_bulk_create`, validate: { - body: buildRouteValidation(createRulesBulkSchema), + body: buildRouteValidation( + createRulesBulkSchema + ), }, options: { tags: ['access:securitySolution'], @@ -59,19 +61,19 @@ export const createRulesBulkRoute = (router: IRouter, ml: SetupPlugins['ml']) => .filter((rule) => rule.rule_id == null || !dupes.includes(rule.rule_id)) .map(async (payloadRule) => { const { - actions, + actions: actionsRest, anomaly_threshold: anomalyThreshold, description, enabled, false_positives: falsePositives, from, - query, - language, + query: queryOrUndefined, + language: languageOrUndefined, machine_learning_job_id: machineLearningJobId, output_index: outputIndex, saved_id: savedId, meta, - filters, + filters: filtersRest, rule_id: ruleId, index, interval, @@ -89,23 +91,42 @@ export const createRulesBulkRoute = (router: IRouter, ml: SetupPlugins['ml']) => timeline_id: timelineId, timeline_title: timelineTitle, version, - exceptions_list, + exceptions_list: exceptionsList, } = payloadRule; - const ruleIdOrUuid = ruleId ?? uuid.v4(); try { + const validationErrors = createRuleValidateTypeDependents(payloadRule); + if (validationErrors.length) { + return createBulkErrorObject({ + ruleId, + statusCode: 400, + message: validationErrors.join(), + }); + } + + const query = + type !== 'machine_learning' && queryOrUndefined == null ? '' : queryOrUndefined; + + const language = + type !== 'machine_learning' && languageOrUndefined == null + ? 'kuery' + : languageOrUndefined; + + // TODO: Fix these either with an is conversion or by better typing them within io-ts + const actions: RuleAlertAction[] = actionsRest as RuleAlertAction[]; + const filters: PartialFilter[] | undefined = filtersRest as PartialFilter[]; throwHttpError(await mlAuthz.validateRuleType(type)); const finalIndex = outputIndex ?? siemClient.getSignalsIndex(); const indexExists = await getIndexExists(clusterClient.callAsCurrentUser, finalIndex); if (!indexExists) { return createBulkErrorObject({ - ruleId: ruleIdOrUuid, + ruleId, statusCode: 400, message: `To create a rule, the index must exist first. Index ${finalIndex} does not exist`, }); } if (ruleId != null) { - const rule = await readRules({ alertsClient, ruleId }); + const rule = await readRules({ alertsClient, ruleId, id: undefined }); if (rule != null) { return createBulkErrorObject({ ruleId, @@ -131,7 +152,7 @@ export const createRulesBulkRoute = (router: IRouter, ml: SetupPlugins['ml']) => timelineTitle, meta, filters, - ruleId: ruleIdOrUuid, + ruleId, index, interval, maxSignals, @@ -145,7 +166,7 @@ export const createRulesBulkRoute = (router: IRouter, ml: SetupPlugins['ml']) => references, note, version, - exceptions_list, + exceptionsList, actions: throttle === 'rule' ? actions : [], // Only enable actions if throttle is set to rule, otherwise we are a notification and should not enable it, }); @@ -159,9 +180,9 @@ export const createRulesBulkRoute = (router: IRouter, ml: SetupPlugins['ml']) => name, }); - return transformValidateBulkError(ruleIdOrUuid, createdRule, ruleActions); + return transformValidateBulkError(ruleId, createdRule, ruleActions); } catch (err) { - return transformBulkError(ruleIdOrUuid, err); + return transformBulkError(ruleId, err); } }) ); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.test.ts index 7984b84729821..5abd7b1e76a76 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.test.ts @@ -170,7 +170,7 @@ describe('create_rules', () => { const result = server.validate(request); expect(result.badRequest).toHaveBeenCalledWith( - 'child "type" fails because ["type" must be one of [query, saved_query, machine_learning]]' + 'Invalid value "unexpected_type" supplied to "type"' ); }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts index 6138db4dcb0ff..78d67e0e9366c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts @@ -4,8 +4,13 @@ * you may not use this file except in compliance with the Elastic License. */ -import uuid from 'uuid'; - +import { createRuleValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/create_rules_type_dependents'; +import { RuleAlertAction } from '../../../../../common/detection_engine/types'; +import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; +import { + createRulesSchema, + CreateRulesSchemaDecoded, +} from '../../../../../common/detection_engine/schemas/request/create_rules_schema'; import { IRouter } from '../../../../../../../../src/core/server'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { SetupPlugins } from '../../../../plugin'; @@ -13,42 +18,48 @@ import { buildMlAuthz } from '../../../machine_learning/authz'; import { throwHttpError } from '../../../machine_learning/validation'; import { createRules } from '../../rules/create_rules'; import { readRules } from '../../rules/read_rules'; -import { RuleAlertParamsRest } from '../../types'; import { transformValidate } from './validate'; import { getIndexExists } from '../../index/get_index_exists'; -import { createRulesSchema } from '../schemas/create_rules_schema'; -import { buildRouteValidation, transformError, buildSiemResponse } from '../utils'; +import { transformError, buildSiemResponse } from '../utils'; import { updateRulesNotifications } from '../../rules/update_rules_notifications'; import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; +import { PartialFilter } from '../../types'; export const createRulesRoute = (router: IRouter, ml: SetupPlugins['ml']): void => { router.post( { path: DETECTION_ENGINE_RULES_URL, validate: { - body: buildRouteValidation(createRulesSchema), + body: buildRouteValidation( + createRulesSchema + ), }, options: { tags: ['access:securitySolution'], }, }, async (context, request, response) => { + const siemResponse = buildSiemResponse(response); + const validationErrors = createRuleValidateTypeDependents(request.body); + if (validationErrors.length) { + return siemResponse.error({ statusCode: 400, body: validationErrors }); + } const { - actions, + actions: actionsRest, anomaly_threshold: anomalyThreshold, description, enabled, false_positives: falsePositives, from, - query, - language, + query: queryOrUndefined, + language: languageOrUndefined, output_index: outputIndex, saved_id: savedId, timeline_id: timelineId, timeline_title: timelineTitle, meta, machine_learning_job_id: machineLearningJobId, - filters, + filters: filtersRest, rule_id: ruleId, index, interval, @@ -63,11 +74,21 @@ export const createRulesRoute = (router: IRouter, ml: SetupPlugins['ml']): void type, references, note, - exceptions_list, + exceptions_list: exceptionsList, } = request.body; - const siemResponse = buildSiemResponse(response); - try { + const query = + type !== 'machine_learning' && queryOrUndefined == null ? '' : queryOrUndefined; + + const language = + type !== 'machine_learning' && languageOrUndefined == null + ? 'kuery' + : languageOrUndefined; + + // TODO: Fix these either with an is conversion or by better typing them within io-ts + const actions: RuleAlertAction[] = actionsRest as RuleAlertAction[]; + const filters: PartialFilter[] | undefined = filtersRest as PartialFilter[]; + const alertsClient = context.alerting?.getAlertsClient(); const clusterClient = context.core.elasticsearch.legacy.client; const savedObjectsClient = context.core.savedObjects.client; @@ -89,7 +110,7 @@ export const createRulesRoute = (router: IRouter, ml: SetupPlugins['ml']): void }); } if (ruleId != null) { - const rule = await readRules({ alertsClient, ruleId }); + const rule = await readRules({ alertsClient, ruleId, id: undefined }); if (rule != null) { return siemResponse.error({ statusCode: 409, @@ -114,7 +135,7 @@ export const createRulesRoute = (router: IRouter, ml: SetupPlugins['ml']): void meta, machineLearningJobId, filters, - ruleId: ruleId ?? uuid.v4(), + ruleId, index, interval, maxSignals, @@ -128,7 +149,7 @@ export const createRulesRoute = (router: IRouter, ml: SetupPlugins['ml']): void references, note, version: 1, - exceptions_list, + exceptionsList, actions: throttle === 'rule' ? actions : [], // Only enable actions if throttle is rule, otherwise we are a notification and should not enable it, }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.test.ts index f2da3ab4be8f6..4c1c1046a9fcd 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.test.ts @@ -105,11 +105,33 @@ describe('delete_rules', () => { path: `${DETECTION_ENGINE_RULES_URL}/_bulk_delete`, body: [{}], }); - const result = server.validate(request); + const response = await server.inject(request, context); + expect(response.status).toEqual(200); + expect(response.body).toEqual([ + { + error: { message: 'either "id" or "rule_id" must be set', status_code: 400 }, + rule_id: '(unknown id)', + }, + ]); + }); - expect(result.badRequest).toHaveBeenCalledWith( - '"value" at position 0 fails because ["value" must contain at least one of [id, rule_id]]' - ); + test('rejects requests with both id and rule_id', async () => { + const request = requestMock.create({ + method: 'post', + path: `${DETECTION_ENGINE_RULES_URL}/_bulk_delete`, + body: [{ id: 'c1e1b359-7ac1-4e96-bc81-c683c092436f', rule_id: 'rule_1' }], + }); + const response = await server.inject(request, context); + expect(response.status).toEqual(200); + expect(response.body).toEqual([ + { + error: { + message: 'both "id" and "rule_id" cannot exist, choose one or the other', + status_code: 400, + }, + rule_id: 'c1e1b359-7ac1-4e96-bc81-c683c092436f', + }, + ]); }); }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts index c1e359b36caa1..12f908ce7e8b5 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts @@ -4,26 +4,32 @@ * you may not use this file except in compliance with the Elastic License. */ +import { queryRuleValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/query_rules_type_dependents'; +import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; +import { + queryRulesBulkSchema, + QueryRulesBulkSchemaDecoded, +} from '../../../../../common/detection_engine/schemas/request/query_rules_bulk_schema'; import { rulesBulkSchema } from '../../../../../common/detection_engine/schemas/response/rules_bulk_schema'; import { IRouter, RouteConfig, RequestHandler } from '../../../../../../../../src/core/server'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; -import { queryRulesBulkSchema } from '../schemas/query_rules_bulk_schema'; import { getIdBulkError } from './utils'; import { transformValidateBulkError, validate } from './validate'; -import { transformBulkError, buildRouteValidation, buildSiemResponse } from '../utils'; -import { DeleteRulesRequestParams } from '../../rules/types'; +import { transformBulkError, buildSiemResponse, createBulkErrorObject } from '../utils'; import { deleteRules } from '../../rules/delete_rules'; import { deleteNotifications } from '../../notifications/delete_notifications'; import { deleteRuleActionsSavedObject } from '../../rule_actions/delete_rule_actions_saved_object'; import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; -type Config = RouteConfig; -type Handler = RequestHandler; +type Config = RouteConfig; +type Handler = RequestHandler; export const deleteRulesBulkRoute = (router: IRouter) => { const config: Config = { validate: { - body: buildRouteValidation(queryRulesBulkSchema), + body: buildRouteValidation( + queryRulesBulkSchema + ), }, path: `${DETECTION_ENGINE_RULES_URL}/_bulk_delete`, options: { @@ -46,6 +52,15 @@ export const deleteRulesBulkRoute = (router: IRouter) => { request.body.map(async (payloadRule) => { const { id, rule_id: ruleId } = payloadRule; const idOrRuleIdOrUnknown = id ?? ruleId ?? '(unknown id)'; + const validationErrors = queryRuleValidateTypeDependents(payloadRule); + if (validationErrors.length) { + return createBulkErrorObject({ + ruleId: idOrRuleIdOrUnknown, + statusCode: 400, + message: validationErrors.join(), + }); + } + try { const rule = await deleteRules({ alertsClient, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.test.ts index e30f332ecd1ca..8530b845e9bb9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.test.ts @@ -92,11 +92,12 @@ describe('delete_rules', () => { path: DETECTION_ENGINE_RULES_URL, query: {}, }); - const result = server.validate(request); - - expect(result.badRequest).toHaveBeenCalledWith( - '"value" must contain at least one of [id, rule_id]' - ); + const response = await server.inject(request, context); + expect(response.status).toEqual(400); + expect(response.body).toEqual({ + message: ['either "id" or "rule_id" must be set'], + status_code: 400, + }); }); }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.ts index a2256b8338d2f..f4aa51c6dcfc3 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/delete_rules_route.ts @@ -4,14 +4,18 @@ * you may not use this file except in compliance with the Elastic License. */ +import { queryRuleValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/query_rules_type_dependents'; +import { + queryRulesSchema, + QueryRulesSchemaDecoded, +} from '../../../../../common/detection_engine/schemas/request/query_rules_schema'; +import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; import { IRouter } from '../../../../../../../../src/core/server'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { deleteRules } from '../../rules/delete_rules'; -import { queryRulesSchema } from '../schemas/query_rules_schema'; import { getIdError } from './utils'; import { transformValidate } from './validate'; -import { buildRouteValidation, transformError, buildSiemResponse } from '../utils'; -import { DeleteRuleRequestParams } from '../../rules/types'; +import { transformError, buildSiemResponse } from '../utils'; import { deleteNotifications } from '../../notifications/delete_notifications'; import { deleteRuleActionsSavedObject } from '../../rule_actions/delete_rule_actions_saved_object'; import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; @@ -21,7 +25,9 @@ export const deleteRulesRoute = (router: IRouter) => { { path: DETECTION_ENGINE_RULES_URL, validate: { - query: buildRouteValidation(queryRulesSchema), + query: buildRouteValidation( + queryRulesSchema + ), }, options: { tags: ['access:securitySolution'], @@ -29,6 +35,10 @@ export const deleteRulesRoute = (router: IRouter) => { }, async (context, request, response) => { const siemResponse = buildSiemResponse(response); + const validationErrors = queryRuleValidateTypeDependents(request.query); + if (validationErrors.length) { + return siemResponse.error({ statusCode: 400, body: validationErrors }); + } try { const { id, rule_id: ruleId } = request.query; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/export_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/export_rules_route.ts index ad0b3c87ff145..8df9f114559a8 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/export_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/export_rules_route.ts @@ -4,23 +4,32 @@ * you may not use this file except in compliance with the Elastic License. */ +import { + exportRulesQuerySchema, + ExportRulesQuerySchemaDecoded, + exportRulesSchema, + ExportRulesSchemaDecoded, +} from '../../../../../common/detection_engine/schemas/request/export_rules_schema'; +import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; import { IRouter } from '../../../../../../../../src/core/server'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { ConfigType } from '../../../../config'; -import { ExportRulesRequestParams } from '../../rules/types'; import { getNonPackagedRulesCount } from '../../rules/get_existing_prepackaged_rules'; -import { exportRulesSchema, exportRulesQuerySchema } from '../schemas/export_rules_schema'; import { getExportByObjectIds } from '../../rules/get_export_by_object_ids'; import { getExportAll } from '../../rules/get_export_all'; -import { transformError, buildRouteValidation, buildSiemResponse } from '../utils'; +import { transformError, buildSiemResponse } from '../utils'; export const exportRulesRoute = (router: IRouter, config: ConfigType) => { router.post( { path: `${DETECTION_ENGINE_RULES_URL}/_export`, validate: { - query: buildRouteValidation(exportRulesQuerySchema), - body: buildRouteValidation(exportRulesSchema), + query: buildRouteValidation( + exportRulesQuerySchema + ), + body: buildRouteValidation( + exportRulesSchema + ), }, options: { tags: ['access:securitySolution'], diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.test.ts index b4591a8141f7b..892b7a2dd7315 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.test.ts @@ -91,7 +91,7 @@ describe('find_rules', () => { }); const result = server.validate(request); - expect(result.badRequest).toHaveBeenCalledWith('"invalid_value" is not allowed'); + expect(result.badRequest).toHaveBeenCalledWith('invalid keys "invalid_value"'); }); }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts index 7d99be908d064..eceb953762090 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_route.ts @@ -4,22 +4,28 @@ * you may not use this file except in compliance with the Elastic License. */ +import { findRuleValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/find_rules_type_dependents'; +import { + findRulesSchema, + FindRulesSchemaDecoded, +} from '../../../../../common/detection_engine/schemas/request/find_rules_schema'; import { IRouter } from '../../../../../../../../src/core/server'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { findRules } from '../../rules/find_rules'; -import { FindRulesRequestParams } from '../../rules/types'; -import { findRulesSchema } from '../schemas/find_rules_schema'; import { transformValidateFindAlerts } from './validate'; -import { buildRouteValidation, transformError, buildSiemResponse } from '../utils'; +import { transformError, buildSiemResponse } from '../utils'; import { getRuleActionsSavedObject } from '../../rule_actions/get_rule_actions_saved_object'; import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; +import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; export const findRulesRoute = (router: IRouter) => { router.get( { path: `${DETECTION_ENGINE_RULES_URL}/_find`, validate: { - query: buildRouteValidation(findRulesSchema), + query: buildRouteValidation( + findRulesSchema + ), }, options: { tags: ['access'], @@ -27,6 +33,10 @@ export const findRulesRoute = (router: IRouter) => { }, async (context, request, response) => { const siemResponse = buildSiemResponse(response); + const validationErrors = findRuleValidateTypeDependents(request.query); + if (validationErrors.length) { + return siemResponse.error({ statusCode: 400, body: validationErrors }); + } try { const { query } = request; @@ -45,6 +55,7 @@ export const findRulesRoute = (router: IRouter) => { sortField: query.sort_field, sortOrder: query.sort_order, filter: query.filter, + fields: query.fields, }); const ruleStatuses = await Promise.all( rules.data.map(async (rule) => { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.test.ts index d7c6d317227fa..c2f396c874a7c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.test.ts @@ -66,7 +66,7 @@ describe('find_statuses', () => { }); const result = server.validate(request); - expect(result.badRequest).toHaveBeenCalledWith('"id" is not allowed'); + expect(result.badRequest).toHaveBeenCalledWith('Invalid value "undefined" supplied to "ids"'); }); }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.ts index a923c1bb49200..c02e28456111a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/find_rules_status_route.ts @@ -4,28 +4,25 @@ * you may not use this file except in compliance with the Elastic License. */ +import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; import { IRouter } from '../../../../../../../../src/core/server'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; -import { findRulesStatusesSchema } from '../schemas/find_rules_statuses_schema'; -import { - FindRulesStatusesRequestParams, - RuleStatusResponse, - IRuleStatusAttributes, -} from '../../rules/types'; -import { - buildRouteValidation, - transformError, - convertToSnakeCase, - buildSiemResponse, -} from '../utils'; +import { RuleStatusResponse, IRuleStatusAttributes } from '../../rules/types'; +import { transformError, convertToSnakeCase, buildSiemResponse } from '../utils'; import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; +import { + findRulesStatusesSchema, + FindRulesStatusesSchemaDecoded, +} from '../../../../../common/detection_engine/schemas/request/find_rule_statuses_schema'; export const findRulesStatusesRoute = (router: IRouter) => { router.post( { path: `${DETECTION_ENGINE_RULES_URL}/_find_statuses`, validate: { - body: buildRouteValidation(findRulesStatusesSchema), + body: buildRouteValidation( + findRulesStatusesSchema + ), }, options: { tags: ['access:securitySolution'], diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts index 31aad769d5a3d..c3f4695a20461 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts @@ -44,6 +44,7 @@ export const getPrepackagedRulesStatusRoute = (router: IRouter) => { sortField: 'enabled', sortOrder: 'desc', filter: 'alert.attributes.tags:"__internal_immutable:false"', + fields: undefined, }); const prepackagedRules = await getExistingPrepackagedRules({ alertsClient }); const rulesToInstall = getRulesToInstall(rulesFromFileSystem, prepackagedRules); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.test.ts index a7d5e579b074d..0762fbc7dd6e3 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.test.ts @@ -250,14 +250,16 @@ describe('import_rules_route', () => { errors: [ { error: { - message: 'child "rule_id" fails because ["rule_id" is required]', + // TODO: Change the formatter to do better than output [object Object] + message: '[object Object],[object Object]', status_code: 400, }, rule_id: '(unknown id)', }, { error: { - message: 'child "rule_id" fails because ["rule_id" is required]', + // TODO: Change the formatter to do better than output [object Object] + message: '[object Object],[object Object]', status_code: 400, }, rule_id: '(unknown id)', diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.ts index cbe583a11d1c1..c8b61414608a9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/import_rules_route.ts @@ -8,8 +8,15 @@ import { chunk } from 'lodash/fp'; import { extname } from 'path'; import { - ImportRulesSchema, - importRulesSchema, + importRulesQuerySchema, + ImportRulesQuerySchemaDecoded, + importRulesPayloadSchema, + ImportRulesPayloadSchemaDecoded, + ImportRulesSchemaDecoded, +} from '../../../../../common/detection_engine/schemas/request/import_rules_schema'; +import { + ImportRulesSchema as ImportRulesResponseSchema, + importRulesSchema as importRulesResponseSchema, } from '../../../../../common/detection_engine/schemas/response/import_rules_schema'; import { IRouter } from '../../../../../../../../src/core/server'; import { createPromiseFromStreams } from '../../../../../../../../src/legacy/utils/streams'; @@ -19,11 +26,9 @@ import { SetupPlugins } from '../../../../plugin'; import { buildMlAuthz } from '../../../machine_learning/authz'; import { throwHttpError } from '../../../machine_learning/validation'; import { createRules } from '../../rules/create_rules'; -import { ImportRulesRequestParams } from '../../rules/types'; import { readRules } from '../../rules/read_rules'; import { getIndexExists } from '../../index/get_index_exists'; import { - buildRouteValidation, createBulkErrorObject, ImportRuleResponse, BulkError, @@ -32,14 +37,15 @@ import { transformError, buildSiemResponse, } from '../utils'; -import { ImportRuleAlertRest } from '../../types'; import { patchRules } from '../../rules/patch_rules'; -import { importRulesQuerySchema, importRulesPayloadSchema } from '../schemas/import_rules_schema'; import { getTupleDuplicateErrorsAndUniqueRules } from './utils'; import { validate } from './validate'; import { createRulesStreamFromNdJson } from '../../rules/create_rules_stream_from_ndjson'; +import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; +import { HapiReadableStream } from '../../rules/types'; +import { PartialFilter } from '../../types'; -type PromiseFromStreams = ImportRuleAlertRest | Error; +type PromiseFromStreams = ImportRulesSchemaDecoded | Error; const CHUNK_PARSED_OBJECT_SIZE = 10; @@ -48,8 +54,13 @@ export const importRulesRoute = (router: IRouter, config: ConfigType, ml: SetupP { path: `${DETECTION_ENGINE_RULES_URL}/_import`, validate: { - query: buildRouteValidation(importRulesQuerySchema), - body: buildRouteValidation(importRulesPayloadSchema), + query: buildRouteValidation( + importRulesQuerySchema + ), + body: buildRouteValidation< + typeof importRulesPayloadSchema, + ImportRulesPayloadSchemaDecoded + >(importRulesPayloadSchema), }, options: { tags: ['access:securitySolution'], @@ -74,7 +85,7 @@ export const importRulesRoute = (router: IRouter, config: ConfigType, ml: SetupP const mlAuthz = buildMlAuthz({ license: context.licensing.license, ml, request }); - const { filename } = request.body.file.hapi; + const { filename } = (request.body.file as HapiReadableStream).hapi; const fileExtension = extname(filename).toLowerCase(); if (fileExtension !== '.ndjson') { return siemResponse.error({ @@ -94,7 +105,7 @@ export const importRulesRoute = (router: IRouter, config: ConfigType, ml: SetupP const objectLimit = config.maxRuleImportExportSize; const readStream = createRulesStreamFromNdJson(objectLimit); const parsedObjects = await createPromiseFromStreams([ - request.body.file, + request.body.file as HapiReadableStream, ...readStream, ]); const [duplicateIdErrors, uniqueParsedObjects] = getTupleDuplicateErrorsAndUniqueRules( @@ -128,13 +139,13 @@ export const importRulesRoute = (router: IRouter, config: ConfigType, ml: SetupP false_positives: falsePositives, from, immutable, - query, - language, + query: queryOrUndefined, + language: languageOrUndefined, machine_learning_job_id: machineLearningJobId, output_index: outputIndex, saved_id: savedId, meta, - filters, + filters: filtersRest, rule_id: ruleId, index, interval, @@ -151,13 +162,24 @@ export const importRulesRoute = (router: IRouter, config: ConfigType, ml: SetupP timeline_id: timelineId, timeline_title: timelineTitle, version, - exceptions_list, + exceptions_list: exceptionsList, } = parsedRule; try { + const query = + type !== 'machine_learning' && queryOrUndefined == null ? '' : queryOrUndefined; + + const language = + type !== 'machine_learning' && languageOrUndefined == null + ? 'kuery' + : languageOrUndefined; + + // TODO: Fix these either with an is conversion or by better typing them within io-ts + const filters: PartialFilter[] | undefined = filtersRest as PartialFilter[]; + throwHttpError(await mlAuthz.validateRuleType(type)); - const rule = await readRules({ alertsClient, ruleId }); + const rule = await readRules({ alertsClient, ruleId, id: undefined }); if (rule == null) { await createRules({ alertsClient, @@ -190,7 +212,7 @@ export const importRulesRoute = (router: IRouter, config: ConfigType, ml: SetupP references, note, version, - exceptions_list, + exceptionsList, actions: [], // Actions are not imported nor exported at this time }); resolve({ rule_id: ruleId, status_code: 200 }); @@ -202,7 +224,6 @@ export const importRulesRoute = (router: IRouter, config: ConfigType, ml: SetupP enabled, falsePositives, from, - immutable, query, language, outputIndex, @@ -225,9 +246,10 @@ export const importRulesRoute = (router: IRouter, config: ConfigType, ml: SetupP references, note, version, - exceptions_list, + exceptionsList, anomalyThreshold, machineLearningJobId, + actions: undefined, }); resolve({ rule_id: ruleId, status_code: 200 }); } else if (rule != null) { @@ -267,12 +289,12 @@ export const importRulesRoute = (router: IRouter, config: ConfigType, ml: SetupP return false; } }); - const importRules: ImportRulesSchema = { + const importRules: ImportRulesResponseSchema = { success: errorsResp.length === 0, success_count: successes.length, errors: errorsResp, }; - const [validated, errors] = validate(importRules, importRulesSchema); + const [validated, errors] = validate(importRules, importRulesResponseSchema); if (errors != null) { return siemResponse.error({ statusCode: 500, body: errors }); } else { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.test.ts index 24b2d5631b3a7..d5145e1dceae0 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.test.ts @@ -155,11 +155,18 @@ describe('patch_rules_bulk', () => { path: `${DETECTION_ENGINE_RULES_URL}/_bulk_update`, body: [{ ...typicalPayload(), rule_id: undefined }], }); - const result = server.validate(request); + const response = await server.inject(request, context); - expect(result.badRequest).toHaveBeenCalledWith( - '"value" at position 0 fails because ["value" must contain at least one of [id, rule_id]]' - ); + expect(response.status).toEqual(200); + expect(response.body).toEqual([ + { + error: { + message: 'id or rule_id should have been defined', + status_code: 404, + }, + rule_id: '(unknown id)', + }, + ]); }); test('allows query rule type', async () => { @@ -182,7 +189,7 @@ describe('patch_rules_bulk', () => { const result = server.validate(request); expect(result.badRequest).toHaveBeenCalledWith( - '"value" at position 0 fails because [child "type" fails because ["type" must be one of [query, saved_query, machine_learning]]]' + 'Invalid value "unknown_type" supplied to "type"' ); }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.ts index d1347786ddc1b..16f491547a9e6 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_bulk_route.ts @@ -4,28 +4,35 @@ * you may not use this file except in compliance with the Elastic License. */ +import { RuleAlertAction } from '../../../../../common/detection_engine/types'; +import { + patchRulesBulkSchema, + PatchRulesBulkSchemaDecoded, +} from '../../../../../common/detection_engine/schemas/request/patch_rules_bulk_schema'; +import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; import { rulesBulkSchema } from '../../../../../common/detection_engine/schemas/response/rules_bulk_schema'; import { IRouter } from '../../../../../../../../src/core/server'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { SetupPlugins } from '../../../../plugin'; import { buildMlAuthz } from '../../../machine_learning/authz'; import { throwHttpError } from '../../../machine_learning/validation'; -import { PatchRuleAlertParamsRest } from '../../rules/types'; -import { transformBulkError, buildRouteValidation, buildSiemResponse } from '../utils'; +import { transformBulkError, buildSiemResponse } from '../utils'; import { getIdBulkError } from './utils'; import { transformValidateBulkError, validate } from './validate'; -import { patchRulesBulkSchema } from '../schemas/patch_rules_bulk_schema'; import { patchRules } from '../../rules/patch_rules'; import { updateRulesNotifications } from '../../rules/update_rules_notifications'; import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; import { readRules } from '../../rules/read_rules'; +import { PartialFilter } from '../../types'; export const patchRulesBulkRoute = (router: IRouter, ml: SetupPlugins['ml']) => { router.patch( { path: `${DETECTION_ENGINE_RULES_URL}/_bulk_update`, validate: { - body: buildRouteValidation(patchRulesBulkSchema), + body: buildRouteValidation( + patchRulesBulkSchema + ), }, options: { tags: ['access:securitySolution'], @@ -46,7 +53,7 @@ export const patchRulesBulkRoute = (router: IRouter, ml: SetupPlugins['ml']) => const rules = await Promise.all( request.body.map(async (payloadRule) => { const { - actions, + actions: actionsRest, description, enabled, false_positives: falsePositives, @@ -58,7 +65,7 @@ export const patchRulesBulkRoute = (router: IRouter, ml: SetupPlugins['ml']) => timeline_id: timelineId, timeline_title: timelineTitle, meta, - filters, + filters: filtersRest, rule_id: ruleId, id, index, @@ -77,8 +84,13 @@ export const patchRulesBulkRoute = (router: IRouter, ml: SetupPlugins['ml']) => version, anomaly_threshold: anomalyThreshold, machine_learning_job_id: machineLearningJobId, + exceptions_list: exceptionsList, } = payloadRule; const idOrRuleIdOrUnknown = id ?? ruleId ?? '(unknown id)'; + // TODO: Fix these either with an is conversion or by better typing them within io-ts + const actions: RuleAlertAction[] = actionsRest as RuleAlertAction[]; + const filters: PartialFilter[] | undefined = filtersRest as PartialFilter[]; + try { if (type) { // reject an unauthorized "promotion" to ML @@ -123,6 +135,7 @@ export const patchRulesBulkRoute = (router: IRouter, ml: SetupPlugins['ml']) => anomalyThreshold, machineLearningJobId, actions, + exceptionsList, }); if (rule != null && rule.enabled != null && rule.name != null) { const ruleActions = await updateRulesNotifications({ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.test.ts index 9ae7e83ef7989..09230d45ee785 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.test.ts @@ -167,11 +167,11 @@ describe('patch_rules', () => { path: DETECTION_ENGINE_RULES_URL, body: { ...typicalPayload(), rule_id: undefined }, }); - const result = server.validate(request); - - expect(result.badRequest).toHaveBeenCalledWith( - '"value" must contain at least one of [id, rule_id]' - ); + const response = await server.inject(request, context); + expect(response.body).toEqual({ + message: ['either "id" or "rule_id" must be set'], + status_code: 400, + }); }); test('allows query rule type', async () => { @@ -194,7 +194,7 @@ describe('patch_rules', () => { const result = server.validate(request); expect(result.badRequest).toHaveBeenCalledWith( - 'child "type" fails because ["type" must be one of [query, saved_query, machine_learning]]' + 'Invalid value "unknown_type" supplied to "type"' ); }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.ts index 8f0d222ebaa64..385eec0fe1180 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/patch_rules_route.ts @@ -4,35 +4,48 @@ * you may not use this file except in compliance with the Elastic License. */ +import { RuleAlertAction } from '../../../../../common/detection_engine/types'; +import { patchRuleValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/patch_rules_type_dependents'; +import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; +import { + PatchRulesSchemaDecoded, + patchRulesSchema, +} from '../../../../../common/detection_engine/schemas/request/patch_rules_schema'; import { IRouter } from '../../../../../../../../src/core/server'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { SetupPlugins } from '../../../../plugin'; import { buildMlAuthz } from '../../../machine_learning/authz'; import { throwHttpError } from '../../../machine_learning/validation'; import { patchRules } from '../../rules/patch_rules'; -import { PatchRuleAlertParamsRest } from '../../rules/types'; -import { patchRulesSchema } from '../schemas/patch_rules_schema'; -import { buildRouteValidation, transformError, buildSiemResponse } from '../utils'; +import { transformError, buildSiemResponse } from '../utils'; import { getIdError } from './utils'; import { transformValidate } from './validate'; import { updateRulesNotifications } from '../../rules/update_rules_notifications'; import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; import { readRules } from '../../rules/read_rules'; +import { PartialFilter } from '../../types'; export const patchRulesRoute = (router: IRouter, ml: SetupPlugins['ml']) => { router.patch( { path: DETECTION_ENGINE_RULES_URL, validate: { - body: buildRouteValidation(patchRulesSchema), + body: buildRouteValidation( + patchRulesSchema + ), }, options: { tags: ['access:securitySolution'], }, }, async (context, request, response) => { + const siemResponse = buildSiemResponse(response); + const validationErrors = patchRuleValidateTypeDependents(request.body); + if (validationErrors.length) { + return siemResponse.error({ statusCode: 400, body: validationErrors }); + } const { - actions, + actions: actionsRest, description, enabled, false_positives: falsePositives, @@ -44,7 +57,7 @@ export const patchRulesRoute = (router: IRouter, ml: SetupPlugins['ml']) => { timeline_id: timelineId, timeline_title: timelineTitle, meta, - filters, + filters: filtersRest, rule_id: ruleId, id, index, @@ -63,10 +76,13 @@ export const patchRulesRoute = (router: IRouter, ml: SetupPlugins['ml']) => { version, anomaly_threshold: anomalyThreshold, machine_learning_job_id: machineLearningJobId, + exceptions_list: exceptionsList, } = request.body; - const siemResponse = buildSiemResponse(response); - try { + // TODO: Fix these either with an is conversion or by better typing them within io-ts + const actions: RuleAlertAction[] = actionsRest as RuleAlertAction[]; + const filters: PartialFilter[] | undefined = filtersRest as PartialFilter[]; + const alertsClient = context.alerting?.getAlertsClient(); const savedObjectsClient = context.core.savedObjects.client; @@ -119,6 +135,7 @@ export const patchRulesRoute = (router: IRouter, ml: SetupPlugins['ml']) => { anomalyThreshold, machineLearningJobId, actions, + exceptionsList, }); if (rule != null && rule.enabled != null && rule.name != null) { const ruleActions = await updateRulesNotifications({ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.ts index c9b218a3f0898..4a568643ccc2e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/read_rules_route.ts @@ -4,14 +4,18 @@ * you may not use this file except in compliance with the Elastic License. */ +import { queryRuleValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/query_rules_type_dependents'; +import { + queryRulesSchema, + QueryRulesSchemaDecoded, +} from '../../../../../common/detection_engine/schemas/request/query_rules_schema'; +import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; import { IRouter } from '../../../../../../../../src/core/server'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { getIdError } from './utils'; import { transformValidate } from './validate'; -import { buildRouteValidation, transformError, buildSiemResponse } from '../utils'; +import { transformError, buildSiemResponse } from '../utils'; import { readRules } from '../../rules/read_rules'; -import { queryRulesSchema } from '../schemas/query_rules_schema'; -import { ReadRuleRequestParams } from '../../rules/types'; import { getRuleActionsSavedObject } from '../../rule_actions/get_rule_actions_saved_object'; import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; @@ -20,15 +24,22 @@ export const readRulesRoute = (router: IRouter) => { { path: DETECTION_ENGINE_RULES_URL, validate: { - query: buildRouteValidation(queryRulesSchema), + query: buildRouteValidation( + queryRulesSchema + ), }, options: { tags: ['access:securitySolution'], }, }, async (context, request, response) => { - const { id, rule_id: ruleId } = request.query; const siemResponse = buildSiemResponse(response); + const validationErrors = queryRuleValidateTypeDependents(request.query); + if (validationErrors.length) { + return siemResponse.error({ statusCode: 400, body: validationErrors }); + } + + const { id, rule_id: ruleId } = request.query; const alertsClient = context.alerting?.getAlertsClient(); const savedObjectsClient = context.core.savedObjects.client; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.test.ts index 74b135bcb4d8c..2f331938e3ca8 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.test.ts @@ -126,16 +126,18 @@ describe('update_rules_bulk', () => { describe('request validation', () => { test('rejects payloads with no ID', async () => { - const request = requestMock.create({ + const noIdRequest = requestMock.create({ method: 'put', path: `${DETECTION_ENGINE_RULES_URL}/_bulk_update`, body: [{ ...typicalPayload(), rule_id: undefined }], }); - const result = server.validate(request); - - expect(result.badRequest).toHaveBeenCalledWith( - '"value" at position 0 fails because ["value" must contain at least one of [id, rule_id]]' - ); + const response = await server.inject(noIdRequest, context); + expect(response.body).toEqual([ + { + error: { message: 'either "id" or "rule_id" must be set', status_code: 400 }, + rule_id: '(unknown id)', + }, + ]); }); test('allows query rule type', async () => { @@ -158,7 +160,7 @@ describe('update_rules_bulk', () => { const result = server.validate(request); expect(result.badRequest).toHaveBeenCalledWith( - '"value" at position 0 fails because [child "type" fails because ["type" must be one of [query, saved_query, machine_learning]]]' + 'Invalid value "unknown_type" supplied to "type"' ); }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts index ec2b0168c18bf..3ca4a28dd93ee 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts @@ -4,27 +4,35 @@ * you may not use this file except in compliance with the Elastic License. */ +import { updateRuleValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/update_rules_type_dependents'; +import { RuleAlertAction } from '../../../../../common/detection_engine/types'; +import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; +import { + updateRulesBulkSchema, + UpdateRulesBulkSchemaDecoded, +} from '../../../../../common/detection_engine/schemas/request/update_rules_bulk_schema'; import { rulesBulkSchema } from '../../../../../common/detection_engine/schemas/response/rules_bulk_schema'; import { IRouter } from '../../../../../../../../src/core/server'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { SetupPlugins } from '../../../../plugin'; import { buildMlAuthz } from '../../../machine_learning/authz'; import { throwHttpError } from '../../../machine_learning/validation'; -import { UpdateRuleAlertParamsRest } from '../../rules/types'; import { getIdBulkError } from './utils'; import { transformValidateBulkError, validate } from './validate'; -import { buildRouteValidation, transformBulkError, buildSiemResponse } from '../utils'; -import { updateRulesBulkSchema } from '../schemas/update_rules_bulk_schema'; +import { transformBulkError, buildSiemResponse, createBulkErrorObject } from '../utils'; import { updateRules } from '../../rules/update_rules'; import { updateRulesNotifications } from '../../rules/update_rules_notifications'; import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; +import { PartialFilter } from '../../types'; export const updateRulesBulkRoute = (router: IRouter, ml: SetupPlugins['ml']) => { router.put( { path: `${DETECTION_ENGINE_RULES_URL}/_bulk_update`, validate: { - body: buildRouteValidation(updateRulesBulkSchema), + body: buildRouteValidation( + updateRulesBulkSchema + ), }, options: { tags: ['access:securitySolution'], @@ -46,21 +54,21 @@ export const updateRulesBulkRoute = (router: IRouter, ml: SetupPlugins['ml']) => const rules = await Promise.all( request.body.map(async (payloadRule) => { const { - actions, + actions: actionsRest, anomaly_threshold: anomalyThreshold, description, enabled, false_positives: falsePositives, from, - query, - language, + query: queryOrUndefined, + language: languageOrUndefined, machine_learning_job_id: machineLearningJobId, output_index: outputIndex, saved_id: savedId, timeline_id: timelineId, timeline_title: timelineTitle, meta, - filters, + filters: filtersRest, rule_id: ruleId, id, index, @@ -77,11 +85,32 @@ export const updateRulesBulkRoute = (router: IRouter, ml: SetupPlugins['ml']) => references, note, version, - exceptions_list, + exceptions_list: exceptionsList, } = payloadRule; const finalIndex = outputIndex ?? siemClient.getSignalsIndex(); const idOrRuleIdOrUnknown = id ?? ruleId ?? '(unknown id)'; try { + const validationErrors = updateRuleValidateTypeDependents(payloadRule); + if (validationErrors.length) { + return createBulkErrorObject({ + ruleId, + statusCode: 400, + message: validationErrors.join(), + }); + } + + const query = + type !== 'machine_learning' && queryOrUndefined == null ? '' : queryOrUndefined; + + const language = + type !== 'machine_learning' && languageOrUndefined == null + ? 'kuery' + : languageOrUndefined; + + // TODO: Fix these either with an is conversion or by better typing them within io-ts + const actions: RuleAlertAction[] = actionsRest as RuleAlertAction[]; + const filters: PartialFilter[] | undefined = filtersRest as PartialFilter[]; + throwHttpError(await mlAuthz.validateRuleType(type)); const rule = await updateRules({ @@ -116,7 +145,7 @@ export const updateRulesBulkRoute = (router: IRouter, ml: SetupPlugins['ml']) => references, note, version, - exceptions_list, + exceptionsList, actions, }); if (rule != null) { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.test.ts index 25556d8d10fd4..f8b7636080b1b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.test.ts @@ -138,13 +138,16 @@ describe('update_rules', () => { const noIdRequest = requestMock.create({ method: 'put', path: DETECTION_ENGINE_RULES_URL, - body: { ...typicalPayload(), rule_id: undefined }, + body: { + ...typicalPayload(), + rule_id: undefined, + }, + }); + const response = await server.inject(noIdRequest, context); + expect(response.body).toEqual({ + message: ['either "id" or "rule_id" must be set'], + status_code: 400, }); - const result = await server.validate(noIdRequest); - - expect(result.badRequest).toHaveBeenCalledWith( - '"value" must contain at least one of [id, rule_id]' - ); }); test('allows query rule type', async () => { @@ -167,7 +170,7 @@ describe('update_rules', () => { const result = await server.validate(request); expect(result.badRequest).toHaveBeenCalledWith( - 'child "type" fails because ["type" must be one of [query, saved_query, machine_learning]]' + 'Invalid value "unknown type" supplied to "type"' ); }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.ts index 2680db8abdd4d..f2b47f195ca5c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/update_rules_route.ts @@ -4,48 +4,62 @@ * you may not use this file except in compliance with the Elastic License. */ +import { updateRuleValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/update_rules_type_dependents'; +import { RuleAlertAction } from '../../../../../common/detection_engine/types'; +import { + updateRulesSchema, + UpdateRulesSchemaDecoded, +} from '../../../../../common/detection_engine/schemas/request/update_rules_schema'; import { IRouter } from '../../../../../../../../src/core/server'; import { DETECTION_ENGINE_RULES_URL } from '../../../../../common/constants'; import { SetupPlugins } from '../../../../plugin'; import { buildMlAuthz } from '../../../machine_learning/authz'; import { throwHttpError } from '../../../machine_learning/validation'; -import { UpdateRuleAlertParamsRest } from '../../rules/types'; -import { updateRulesSchema } from '../schemas/update_rules_schema'; -import { buildRouteValidation, transformError, buildSiemResponse } from '../utils'; +import { transformError, buildSiemResponse } from '../utils'; import { getIdError } from './utils'; import { transformValidate } from './validate'; import { updateRules } from '../../rules/update_rules'; import { updateRulesNotifications } from '../../rules/update_rules_notifications'; import { ruleStatusSavedObjectsClientFactory } from '../../signals/rule_status_saved_objects_client'; +import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; +import { PartialFilter } from '../../types'; export const updateRulesRoute = (router: IRouter, ml: SetupPlugins['ml']) => { router.put( { path: DETECTION_ENGINE_RULES_URL, validate: { - body: buildRouteValidation(updateRulesSchema), + body: buildRouteValidation( + updateRulesSchema + ), }, options: { tags: ['access:securitySolution'], }, }, async (context, request, response) => { + const siemResponse = buildSiemResponse(response); + const validationErrors = updateRuleValidateTypeDependents(request.body); + if (validationErrors.length) { + return siemResponse.error({ statusCode: 400, body: validationErrors }); + } + const { - actions, + actions: actionsRest, anomaly_threshold: anomalyThreshold, description, enabled, false_positives: falsePositives, from, - query, - language, + query: queryOrUndefined, + language: languageOrUndefined, machine_learning_job_id: machineLearningJobId, output_index: outputIndex, saved_id: savedId, timeline_id: timelineId, timeline_title: timelineTitle, meta, - filters, + filters: filtersRest, rule_id: ruleId, id, index, @@ -62,11 +76,21 @@ export const updateRulesRoute = (router: IRouter, ml: SetupPlugins['ml']) => { references, note, version, - exceptions_list, + exceptions_list: exceptionsList, } = request.body; - const siemResponse = buildSiemResponse(response); - try { + const query = + type !== 'machine_learning' && queryOrUndefined == null ? '' : queryOrUndefined; + + const language = + type !== 'machine_learning' && languageOrUndefined == null + ? 'kuery' + : languageOrUndefined; + + // TODO: Fix these either with an is conversion or by better typing them within io-ts + const actions: RuleAlertAction[] = actionsRest as RuleAlertAction[]; + const filters: PartialFilter[] | undefined = filtersRest as PartialFilter[]; + const alertsClient = context.alerting?.getAlertsClient(); const savedObjectsClient = context.core.savedObjects.client; const siemClient = context.securitySolution?.getAppClient(); @@ -112,7 +136,7 @@ export const updateRulesRoute = (router: IRouter, ml: SetupPlugins['ml']) => { references, note, version, - exceptions_list, + exceptionsList, actions: throttle === 'rule' ? actions : [], // Only enable actions if throttle is rule, otherwise we are a notification and should not enable it }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/utils.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/utils.test.ts index df158d23c0e24..3b2750bbbf664 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/utils.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/utils.test.ts @@ -19,7 +19,7 @@ import { } from './utils'; import { getResult } from '../__mocks__/request_responses'; import { INTERNAL_IDENTIFIER } from '../../../../../common/constants'; -import { ImportRuleAlertRest, RuleAlertParamsRest, RuleTypeParams } from '../../types'; +import { RuleTypeParams } from '../../types'; import { BulkError, ImportSuccessError } from '../utils'; import { getSimpleRule, getOutputRuleAlertForRest } from '../__mocks__/utils'; import { createPromiseFromStreams } from '../../../../../../../../src/legacy/utils/streams'; @@ -28,8 +28,10 @@ import { SanitizedAlert } from '../../../../../../alerts/server/types'; import { createRulesStreamFromNdJson } from '../../rules/create_rules_stream_from_ndjson'; import { RuleAlertType } from '../../rules/types'; import { setFeatureFlagsForTestsOnly, unSetFeatureFlagsForTestsOnly } from '../../feature_flags'; +import { CreateRulesBulkSchemaDecoded } from '../../../../../common/detection_engine/schemas/request/create_rules_bulk_schema'; +import { ImportRulesSchemaDecoded } from '../../../../../common/detection_engine/schemas/request/import_rules_schema'; -type PromiseFromStreams = ImportRuleAlertRest | Error; +type PromiseFromStreams = ImportRulesSchemaDecoded | Error; describe('utils', () => { beforeAll(() => { @@ -485,7 +487,7 @@ describe('utils', () => { { rule_id: 'value3' }, {}, {}, - ] as RuleAlertParamsRest[], + ] as CreateRulesBulkSchemaDecoded, 'rule_id' ); const expected = ['value2', 'value3']; @@ -499,7 +501,7 @@ describe('utils', () => { { rule_id: 'value3' }, {}, {}, - ] as RuleAlertParamsRest[], + ] as CreateRulesBulkSchemaDecoded, 'rule_id' ); const expected: string[] = []; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/utils.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/utils.ts index 5329ff04435ca..3ed45bd8367fc 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/utils.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/utils.ts @@ -8,6 +8,8 @@ import { pickBy, countBy } from 'lodash/fp'; import { SavedObject, SavedObjectsFindResponse } from 'kibana/server'; import uuid from 'uuid'; +import { ImportRulesSchemaDecoded } from '../../../../../common/detection_engine/schemas/request/import_rules_schema'; +import { CreateRulesBulkSchemaDecoded } from '../../../../../common/detection_engine/schemas/request/create_rules_bulk_schema'; import { PartialAlert, FindResult } from '../../../../../../alerts/server'; import { INTERNAL_IDENTIFIER } from '../../../../../common/constants'; import { @@ -19,7 +21,7 @@ import { isRuleStatusFindTypes, isRuleStatusSavedObjectType, } from '../../rules/types'; -import { OutputRuleAlertRest, ImportRuleAlertRest, RuleAlertParamsRest } from '../../types'; +import { OutputRuleAlertRest } from '../../types'; import { createBulkErrorObject, BulkError, @@ -29,10 +31,9 @@ import { OutputError, } from '../utils'; import { hasListsFeature } from '../../feature_flags'; -// import { transformAlertToRuleAction } from '../../../../../common/detection_engine/transform_actions'; import { RuleActions } from '../../rule_actions/types'; -type PromiseFromStreams = ImportRuleAlertRest | Error; +type PromiseFromStreams = ImportRulesSchemaDecoded | Error; export const getIdError = ({ id, @@ -148,7 +149,7 @@ export const transformAlertToRule = ( last_failure_message: ruleStatus?.attributes.lastFailureMessage, last_success_message: ruleStatus?.attributes.lastSuccessMessage, // TODO: (LIST-FEATURE) Remove hasListsFeature() check once we have lists available for a release - exceptions_list: hasListsFeature() ? alert.params.exceptions_list : null, + exceptions_list: hasListsFeature() ? alert.params.exceptionsList : null, }); }; @@ -243,7 +244,10 @@ export const transformOrImportError = ( } }; -export const getDuplicates = (ruleDefinitions: RuleAlertParamsRest[], by: 'rule_id'): string[] => { +export const getDuplicates = ( + ruleDefinitions: CreateRulesBulkSchemaDecoded, + by: 'rule_id' +): string[] => { const mappedDuplicates = countBy( by, ruleDefinitions.filter((r) => r[by] != null) @@ -265,21 +269,17 @@ export const getTupleDuplicateErrorsAndUniqueRules = ( acc.rulesAcc.set(uuid.v4(), parsedRule); } else { const { rule_id: ruleId } = parsedRule; - if (ruleId != null) { - if (acc.rulesAcc.has(ruleId) && !isOverwrite) { - acc.errors.set( - uuid.v4(), - createBulkErrorObject({ - ruleId, - statusCode: 400, - message: `More than one rule with rule-id: "${ruleId}" found`, - }) - ); - } - acc.rulesAcc.set(ruleId, parsedRule); - } else { - acc.rulesAcc.set(uuid.v4(), parsedRule); + if (acc.rulesAcc.has(ruleId) && !isOverwrite) { + acc.errors.set( + uuid.v4(), + createBulkErrorObject({ + ruleId, + statusCode: 400, + message: `More than one rule with rule-id: "${ruleId}" found`, + }) + ); } + acc.rulesAcc.set(ruleId, parsedRule); } return acc; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/add_prepackaged_rules_schema.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/add_prepackaged_rules_schema.test.ts deleted file mode 100644 index 66356a1d65352..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/add_prepackaged_rules_schema.test.ts +++ /dev/null @@ -1,1658 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { AlertAction } from '../../../../../../alerts/common'; -import { RuleAlertAction } from '../../../../../common/detection_engine/types'; -import { ThreatParams, PrepackagedRules } from '../../types'; -import { addPrepackagedRulesSchema } from './add_prepackaged_rules_schema'; -import { setFeatureFlagsForTestsOnly, unSetFeatureFlagsForTestsOnly } from '../../feature_flags'; - -describe('add prepackaged rules schema', () => { - beforeAll(() => { - setFeatureFlagsForTestsOnly(); - }); - - afterAll(() => { - unSetFeatureFlagsForTestsOnly(); - }); - - test('empty objects do not validate', () => { - expect(addPrepackagedRulesSchema.validate>({}).error).toBeTruthy(); - }); - - test('made up values do not validate', () => { - expect( - addPrepackagedRulesSchema.validate>({ - madeUp: 'hi', - }).error - ).toBeTruthy(); - }); - - test('[rule_id] does not validate', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description] does not validate', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from] does not validate', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to] does not validate', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name] does not validate', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity] does not validate', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity, type] does not validate', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity, type, interval] does not validate', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity, type, interval, index] does not validate', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - interval: '5m', - index: ['index-1'], - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity, type, query, index, interval, version] does validate', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - query: 'some query', - index: ['index-1'], - interval: '5m', - version: 1, - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, query, language] does not validate', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some query', - language: 'kuery', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, query, language, risk_score, version] does validate', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some query', - language: 'kuery', - version: 1, - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, query, language, risk_score, output_index] does not validate because output_index is not allowed', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some query', - language: 'kuery', - version: 1, - }).error.message - ).toEqual('"output_index" is not allowed'); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, version] does validate', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - version: 1, - }).error - ).toBeFalsy(); - }); - - test('You can send in an empty array to threat', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [], - version: 1, - }).error - ).toBeFalsy(); - }); - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, version, s] does validate', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - threat: [ - { - framework: 'someFramework', - tactic: { - id: 'fakeId', - name: 'fakeName', - reference: 'fakeRef', - }, - technique: [ - { - id: 'techniqueId', - name: 'techniqueName', - reference: 'techniqueRef', - }, - ], - }, - ], - version: 1, - }).error - ).toBeFalsy(); - }); - - test('allows references to be sent as valid', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - version: 1, - }).error - ).toBeFalsy(); - }); - - test('defaults references to an array', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some-query', - language: 'kuery', - version: 1, - }).value.references - ).toEqual([]); - }); - - test('defaults immutable to true', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some-query', - language: 'kuery', - version: 1, - }).value.immutable - ).toEqual(true); - }); - - test('immutable cannot be set in a pre-packaged rule', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - immutable: true, - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some-query', - language: 'kuery', - version: 1, - }).error.message - ).toEqual('child "immutable" fails because ["immutable" is not allowed]'); - }); - - test('defaults enabled to false', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some-query', - language: 'kuery', - version: 1, - }).value.enabled - ).toEqual(false); - }); - - test('rule_id is required', () => { - expect( - addPrepackagedRulesSchema.validate>({ - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some-query', - language: 'kuery', - version: 1, - }).error.message - ).toEqual('child "rule_id" fails because ["rule_id" is required]'); - }); - - test('references cannot be numbers', () => { - expect( - addPrepackagedRulesSchema.validate< - Partial> & { references: number[] } - >({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some-query', - language: 'kuery', - references: [5], - version: 1, - }).error.message - ).toEqual( - 'child "references" fails because ["references" at position 0 fails because ["0" must be a string]]' - ); - }); - - test('indexes cannot be numbers', () => { - expect( - addPrepackagedRulesSchema.validate< - Partial> & { index: number[] } - >({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: [5], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some-query', - language: 'kuery', - version: 1, - }).error.message - ).toEqual( - 'child "index" fails because ["index" at position 0 fails because ["0" must be a string]]' - ); - }); - - test('defaults interval to 5 min', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - type: 'query', - version: 1, - }).value.interval - ).toEqual('5m'); - }); - - test('defaults max signals to 100', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - version: 1, - }).value.max_signals - ).toEqual(100); - }); - - test('saved_id is required when type is saved_query and will not validate without out', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - version: 1, - }).error.message - ).toEqual('child "saved_id" fails because ["saved_id" is required]'); - }); - - test('saved_id is required when type is saved_query and validates with it', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - version: 1, - }).error - ).toBeFalsy(); - }); - - test('saved_query type can have filters with it', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - filters: [], - version: 1, - }).error - ).toBeFalsy(); - }); - - test('filters cannot be a string', () => { - expect( - addPrepackagedRulesSchema.validate< - Partial & { filters: string }> - >({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - filters: 'some string', - version: 1, - }).error.message - ).toEqual('child "filters" fails because ["filters" must be an array]'); - }); - - test('language validates with kuery', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - version: 1, - }).error - ).toBeFalsy(); - }); - - test('language validates with lucene', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'lucene', - version: 1, - }).error - ).toBeFalsy(); - }); - - test('language does not validate with something made up', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'something-made-up', - version: 1, - }).error.message - ).toEqual('child "language" fails because ["language" must be one of [kuery, lucene]]'); - }); - - test('max_signals cannot be negative', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: -1, - version: 1, - }).error.message - ).toEqual('child "max_signals" fails because ["max_signals" must be greater than 0]'); - }); - - test('max_signals cannot be zero', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 0, - version: 1, - }).error.message - ).toEqual('child "max_signals" fails because ["max_signals" must be greater than 0]'); - }); - - test('max_signals can be 1', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error - ).toBeFalsy(); - }); - - test('You can optionally send in an array of tags', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - tags: ['tag_1', 'tag_2'], - version: 1, - }).error - ).toBeFalsy(); - }); - - test('You cannot send in an array of tags that are numbers', () => { - expect( - addPrepackagedRulesSchema.validate< - Partial> & { tags: number[] } - >({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - tags: [0, 1, 2], - version: 1, - }).error.message - ).toEqual( - 'child "tags" fails because ["tags" at position 0 fails because ["0" must be a string]]' - ); - }); - - test('You cannot send in an array of threat that are missing "framework"', () => { - expect( - addPrepackagedRulesSchema.validate< - Partial> & { - threat: Array>>; - } - >({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [ - { - tactic: { - id: 'fakeId', - name: 'fakeName', - reference: 'fakeRef', - }, - technique: [ - { - id: 'techniqueId', - name: 'techniqueName', - reference: 'techniqueRef', - }, - ], - }, - ], - version: 1, - }).error.message - ).toEqual( - 'child "threat" fails because ["threat" at position 0 fails because [child "framework" fails because ["framework" is required]]]' - ); - }); - - test('You cannot send in an array of threat that are missing "tactic"', () => { - expect( - addPrepackagedRulesSchema.validate< - Partial> & { - threat: Array>>; - } - >({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [ - { - framework: 'fake', - technique: [ - { - id: 'techniqueId', - name: 'techniqueName', - reference: 'techniqueRef', - }, - ], - }, - ], - version: 1, - }).error.message - ).toEqual( - 'child "threat" fails because ["threat" at position 0 fails because [child "tactic" fails because ["tactic" is required]]]' - ); - }); - - test('You cannot send in an array of threat that are missing "technique"', () => { - expect( - addPrepackagedRulesSchema.validate< - Partial> & { - threat: Array>>; - } - >({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [ - { - framework: 'fake', - tactic: { - id: 'fakeId', - name: 'fakeName', - reference: 'fakeRef', - }, - }, - ], - version: 1, - }).error.message - ).toEqual( - 'child "threat" fails because ["threat" at position 0 fails because [child "technique" fails because ["technique" is required]]]' - ); - }); - - test('You can optionally send in an array of false positives', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - false_positives: ['false_1', 'false_2'], - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error - ).toBeFalsy(); - }); - - test('You cannot send in an array of false positives that are numbers', () => { - expect( - addPrepackagedRulesSchema.validate< - Partial> & { false_positives: number[] } - >({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - false_positives: [5, 4], - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "false_positives" fails because ["false_positives" at position 0 fails because ["0" must be a string]]' - ); - }); - - test('You cannot set the risk_score to 101', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 101, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual('child "risk_score" fails because ["risk_score" must be less than 101]'); - }); - - test('You cannot set the risk_score to -1', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: -1, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual('child "risk_score" fails because ["risk_score" must be greater than -1]'); - }); - - test('You can set the risk_score to 0', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 0, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error - ).toBeFalsy(); - }); - - test('You can set the risk_score to 100', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 100, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error - ).toBeFalsy(); - }); - - test('You can set meta to any object you want', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - meta: { - somethingMadeUp: { somethingElse: true }, - }, - version: 1, - }).error - ).toBeFalsy(); - }); - - test('You cannot create meta as a string', () => { - expect( - addPrepackagedRulesSchema.validate< - Partial & { meta: string }> - >({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - meta: 'should not work', - version: 1, - }).error.message - ).toEqual('child "meta" fails because ["meta" must be an object]'); - }); - - test('You can omit the query string when filters are present', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - language: 'kuery', - filters: [], - max_signals: 1, - version: 1, - }).error - ).toBeFalsy(); - }); - - test('validates with timeline_id and timeline_title', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - version: 1, - timeline_id: 'timeline-id', - timeline_title: 'timeline-title', - }).error - ).toBeFalsy(); - }); - - test('You cannot omit timeline_title when timeline_id is present', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - language: 'kuery', - filters: [], - max_signals: 1, - version: 1, - timeline_id: 'timeline-id', - }).error.message - ).toEqual('child "timeline_title" fails because ["timeline_title" is required]'); - }); - - test('You cannot have a null value for timeline_title when timeline_id is present', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - language: 'kuery', - filters: [], - max_signals: 1, - version: 1, - timeline_id: 'timeline-id', - timeline_title: null, - }).error.message - ).toEqual('child "timeline_title" fails because ["timeline_title" must be a string]'); - }); - - test('You cannot have empty string for timeline_title when timeline_id is present', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - language: 'kuery', - filters: [], - max_signals: 1, - version: 1, - timeline_id: 'timeline-id', - timeline_title: '', - }).error.message - ).toEqual('child "timeline_title" fails because ["timeline_title" is not allowed to be empty]'); - }); - - test('You cannot have timeline_title with an empty timeline_id', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - language: 'kuery', - filters: [], - max_signals: 1, - version: 1, - timeline_id: '', - timeline_title: 'some-title', - }).error.message - ).toEqual('child "timeline_id" fails because ["timeline_id" is not allowed to be empty]'); - }); - - test('You cannot have timeline_title without timeline_id', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - language: 'kuery', - filters: [], - max_signals: 1, - version: 1, - timeline_title: 'some-title', - }).error.message - ).toEqual('child "timeline_title" fails because ["timeline_title" is not allowed]'); - }); - - test('The default for "from" will be "now-6m"', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).value.from - ).toEqual('now-6m'); - }); - - test('The default for "to" will be "now"', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - index: ['auditbeat-*'], - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).value.to - ).toEqual('now'); - }); - - test('You cannot set the severity to a value other than low, medium, high, or critical', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - index: ['auditbeat-*'], - name: 'some-name', - severity: 'junk', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "severity" fails because ["severity" must be one of [low, medium, high, critical]]' - ); - }); - - test('The default for "actions" will be an empty array', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - index: ['auditbeat-*'], - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).value.actions - ).toEqual([]); - }); - - test('You cannot send in an array of actions that are missing "group"', () => { - expect( - addPrepackagedRulesSchema.validate< - Partial> & { - actions: Array>; - } - >({ - actions: [ - { - id: 'id', - action_type_id: 'actionTypeId', - params: {}, - }, - ], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "group" fails because ["group" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are missing "id"', () => { - expect( - addPrepackagedRulesSchema.validate< - Partial> & { - actions: Array>; - } - >({ - actions: [ - { - group: 'group', - action_type_id: 'action_type_id', - params: {}, - }, - ], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "id" fails because ["id" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are missing "action_type_id"', () => { - expect( - addPrepackagedRulesSchema.validate< - Partial> & { - actions: Array>; - } - >({ - actions: [ - { - group: 'group', - id: 'id', - params: {}, - }, - ], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "action_type_id" fails because ["action_type_id" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are missing "params"', () => { - expect( - addPrepackagedRulesSchema.validate< - Partial> & { - actions: Array>; - } - >({ - actions: [ - { - group: 'group', - id: 'id', - action_type_id: 'action_type_id', - }, - ], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "params" fails because ["params" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are including "actionTypeId', () => { - expect( - addPrepackagedRulesSchema.validate< - Partial> & { - actions: AlertAction[]; - } - >({ - actions: [ - { - group: 'group', - id: 'id', - actionTypeId: 'actionTypeId', - params: {}, - }, - ], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "action_type_id" fails because ["action_type_id" is required]]]' - ); - }); - - test('The default for "throttle" will be null', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - index: ['auditbeat-*'], - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).value.throttle - ).toEqual(null); - }); - - describe('note', () => { - test('You can set note to any string you want', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - meta: { - somethingMadeUp: { somethingElse: true }, - }, - note: '# test header', - version: 1, - }).error - ).toBeFalsy(); - }); - - test('You cannot create note as anything other than a string', () => { - expect( - addPrepackagedRulesSchema.validate< - Partial & { note: object }> - >({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - meta: { - somethingMadeUp: { somethingElse: true }, - }, - note: { - somethingMadeUp: { somethingElse: true }, - }, - version: 1, - }).error.message - ).toEqual('child "note" fails because ["note" must be a string]'); - }); - }); - - // TODO: (LIST-FEATURE) We can enable this once we change the schema's to not be global per module but rather functions that can create the schema - // on demand. Since they are per module, we have a an issue where the ENV variables do not take effect. It is better we change all the - // schema's to be function calls to avoid global side effects or just wait until the feature is available. If you want to test this early, - // you can remove the .skip and set your env variable of export ELASTIC_XPACK_SIEM_LISTS_FEATURE=true locally - describe.skip('exceptions_list', () => { - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and exceptions_list] does validate', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - version: 1, - exceptions_list: [ - { - field: 'source.ip', - values_operator: 'included', - values_type: 'exists', - }, - { - field: 'host.name', - values_operator: 'excluded', - values_type: 'match', - values: [ - { - name: 'rock01', - }, - ], - and: [ - { - field: 'host.id', - values_operator: 'included', - values_type: 'match_all', - values: [ - { - name: '123', - }, - { - name: '678', - }, - ], - }, - ], - }, - ], - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and empty exceptions_list] does validate', () => { - expect( - addPrepackagedRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - exceptions_list: [], - version: 1, - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and invalid exceptions_list] does NOT validate', () => { - expect( - addPrepackagedRulesSchema.validate>>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - exceptions_list: [{ invalid_value: 'invalid value' }], - version: 1, - }).error.message - ).toEqual( - 'child "exceptions_list" fails because ["exceptions_list" at position 0 fails because [child "field" fails because ["field" is required]]]' - ); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and non-existent exceptions_list] does validate with empty exceptions_list', () => { - expect( - addPrepackagedRulesSchema.validate>>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - version: 1, - }).value.exceptions_list - ).toEqual([]); - }); - }); -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/add_prepackaged_rules_schema.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/add_prepackaged_rules_schema.ts deleted file mode 100644 index f1bffdaf83522..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/add_prepackaged_rules_schema.ts +++ /dev/null @@ -1,115 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import Joi from 'joi'; - -/* eslint-disable @typescript-eslint/camelcase */ -import { - actions, - enabled, - description, - false_positives, - filters, - from, - immutable, - index, - rule_id, - interval, - query, - language, - saved_id, - timeline_id, - timeline_title, - meta, - risk_score, - max_signals, - name, - severity, - tags, - to, - type, - threat, - throttle, - references, - note, - version, - lists, - anomaly_threshold, - machine_learning_job_id, -} from './schemas'; -/* eslint-enable @typescript-eslint/camelcase */ - -import { DEFAULT_MAX_SIGNALS } from '../../../../../common/constants'; -import { hasListsFeature } from '../../feature_flags'; - -/** - * Big differences between this schema and the createRulesSchema - * - rule_id is required here - * - output_index is not allowed (and instead the space index must be used) - * - immutable is forbidden but defaults to true instead of to false and it can only ever be true - * - enabled defaults to false instead of true - * - version is a required field that must exist - * - index is a required field that must exist if type !== machine_learning - */ -export const addPrepackagedRulesSchema = Joi.object({ - actions: actions.default([]), - anomaly_threshold: anomaly_threshold.when('type', { - is: 'machine_learning', - then: Joi.required(), - otherwise: Joi.forbidden(), - }), - description: description.required(), - enabled: enabled.default(false), - false_positives: false_positives.default([]), - filters, - from: from.default('now-6m'), - rule_id: rule_id.required(), - immutable: immutable.forbidden().default(true).valid(true), - index: index.when('type', { - is: 'machine_learning', - then: Joi.forbidden(), - otherwise: Joi.required(), - }), - interval: interval.default('5m'), - query: query.when('type', { - is: 'machine_learning', - then: Joi.forbidden(), - otherwise: query.allow('').default(''), - }), - language: language.when('type', { - is: 'machine_learning', - then: Joi.forbidden(), - otherwise: language.default('kuery'), - }), - machine_learning_job_id: machine_learning_job_id.when('type', { - is: 'machine_learning', - then: Joi.required(), - otherwise: Joi.forbidden(), - }), - saved_id: saved_id.when('type', { - is: 'saved_query', - then: Joi.required(), - otherwise: Joi.forbidden(), - }), - timeline_id, - timeline_title, - meta, - risk_score: risk_score.required(), - max_signals: max_signals.default(DEFAULT_MAX_SIGNALS), - name: name.required(), - severity: severity.required(), - tags: tags.default([]), - to: to.default('now'), - type: type.required(), - threat: threat.default([]), - throttle: throttle.default(null), - references: references.default([]), - note: note.allow(''), - version: version.required(), - - // TODO: (LIST-FEATURE) Remove the hasListsFeatures once this is ready for release - exceptions_list: hasListsFeature() ? lists.default([]) : lists.forbidden().default([]), -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/create_rules_bulk_schema.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/create_rules_bulk_schema.test.ts deleted file mode 100644 index 0bf59759a6db6..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/create_rules_bulk_schema.test.ts +++ /dev/null @@ -1,260 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { createRulesBulkSchema } from './create_rules_bulk_schema'; -import { PatchRuleAlertParamsRest } from '../../rules/types'; -import { setFeatureFlagsForTestsOnly, unSetFeatureFlagsForTestsOnly } from '../../feature_flags'; - -// only the basics of testing are here. -// see: create_rules_schema.test.ts for the bulk of the validation tests -// this just wraps createRulesSchema in an array -describe('create_rules_bulk_schema', () => { - beforeAll(() => { - setFeatureFlagsForTestsOnly(); - }); - - afterAll(() => { - unSetFeatureFlagsForTestsOnly(); - }); - - test('can take an empty array and validate it', () => { - expect( - createRulesBulkSchema.validate>>([]).error - ).toBeFalsy(); - }); - - test('made up values do not validate', () => { - expect( - createRulesBulkSchema.validate<[{ madeUp: string }]>([ - { - madeUp: 'hi', - }, - ]).error - ).toBeTruthy(); - }); - - test('single array of [id] does validate', () => { - expect( - createRulesBulkSchema.validate>>([ - { - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - query: 'some query', - index: ['index-1'], - interval: '5m', - }, - ]).error - ).toBeFalsy(); - }); - - test('two values of [id] does validate', () => { - expect( - createRulesBulkSchema.validate>>([ - { - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - query: 'some query', - index: ['index-1'], - interval: '5m', - }, - { - rule_id: 'rule-2', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - query: 'some query', - index: ['index-1'], - interval: '5m', - }, - ]).error - ).toBeFalsy(); - }); - - test('The default for "from" will be "now-6m"', () => { - expect( - createRulesBulkSchema.validate>([ - { - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }, - ]).value[0].from - ).toEqual('now-6m'); - }); - - test('The default for "to" will be "now"', () => { - expect( - createRulesBulkSchema.validate>([ - { - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }, - ]).value[0].to - ).toEqual('now'); - }); - - test('You cannot set the severity to a value other than low, medium, high, or critical', () => { - expect( - createRulesBulkSchema.validate>([ - { - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'junk', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }, - ]).error.message - ).toEqual( - '"value" at position 0 fails because [child "severity" fails because ["severity" must be one of [low, medium, high, critical]]]' - ); - }); - - test('You can set "note" to a string', () => { - expect( - createRulesBulkSchema.validate>([ - { - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - note: '# test markdown', - version: 1, - }, - ]).error - ).toBeFalsy(); - }); - - test('You can set "note" to an empty string', () => { - expect( - createRulesBulkSchema.validate>([ - { - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - note: '', - version: 1, - }, - ]).error - ).toBeFalsy(); - }); - - test('You cannot set "note" to anything other than string', () => { - expect( - createRulesBulkSchema.validate>([ - { - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - note: { - something: 'some object', - }, - version: 1, - }, - ]).error.message - ).toEqual( - '"value" at position 0 fails because [child "note" fails because ["note" must be a string]]' - ); - }); - - test('The default for "actions" will be an empty array', () => { - expect( - createRulesBulkSchema.validate>([ - { - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }, - ]).value[0].actions - ).toEqual([]); - }); - - test('The default for "throttle" will be null', () => { - expect( - createRulesBulkSchema.validate>([ - { - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }, - ]).value[0].throttle - ).toEqual(null); - }); -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/create_rules_schema.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/create_rules_schema.test.ts deleted file mode 100644 index 013db2020a146..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/create_rules_schema.test.ts +++ /dev/null @@ -1,1623 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { AlertAction } from '../../../../../../alerts/common'; -import { createRulesSchema } from './create_rules_schema'; -import { PatchRuleAlertParamsRest } from '../../rules/types'; -import { RuleAlertAction } from '../../../../../common/detection_engine/types'; -import { ThreatParams, RuleAlertParamsRest } from '../../types'; -import { setFeatureFlagsForTestsOnly, unSetFeatureFlagsForTestsOnly } from '../../feature_flags'; - -describe('create rules schema', () => { - beforeAll(() => { - setFeatureFlagsForTestsOnly(); - }); - - afterAll(() => { - unSetFeatureFlagsForTestsOnly(); - }); - - test('empty objects do not validate', () => { - expect(createRulesSchema.validate>({}).error).toBeTruthy(); - }); - - test('made up values do not validate', () => { - expect( - createRulesSchema.validate>({ - madeUp: 'hi', - }).error - ).toBeTruthy(); - }); - - test('[rule_id] does not validate', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description] does not validate', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from] does not validate', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to] does not validate', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name] does not validate', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity] does not validate', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity, type] does not validate', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity, type, interval] does not validate', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity, type, interval, index] does not validate', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - interval: '5m', - index: ['index-1'], - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity, type, query, index, interval] does validate', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - query: 'some query', - index: ['index-1'], - interval: '5m', - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, query, language] does not validate', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some query', - language: 'kuery', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, query, language, risk_score] does validate', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some query', - language: 'kuery', - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, query, language, risk_score, output_index] does validate', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some query', - language: 'kuery', - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score] does validate', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, output_index] does validate', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - }).error - ).toBeFalsy(); - }); - - test('You can send in an empty array to threat', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [], - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, output_index, threat] does validate', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - threat: [ - { - framework: 'someFramework', - tactic: { - id: 'fakeId', - name: 'fakeName', - reference: 'fakeRef', - }, - technique: [ - { - id: 'techniqueId', - name: 'techniqueName', - reference: 'techniqueRef', - }, - ], - }, - ], - }).error - ).toBeFalsy(); - }); - - test('allows references to be sent as valid', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - }).error - ).toBeFalsy(); - }); - - test('defaults references to an array', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some-query', - language: 'kuery', - }).value.references - ).toEqual([]); - }); - - test('references cannot be numbers', () => { - expect( - createRulesSchema.validate< - Partial> & { references: number[] } - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some-query', - language: 'kuery', - references: [5], - }).error.message - ).toEqual( - 'child "references" fails because ["references" at position 0 fails because ["0" must be a string]]' - ); - }); - - test('indexes cannot be numbers', () => { - expect( - createRulesSchema.validate> & { index: number[] }>( - { - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: [5], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some-query', - language: 'kuery', - } - ).error.message - ).toEqual( - 'child "index" fails because ["index" at position 0 fails because ["0" must be a string]]' - ); - }); - - test('defaults interval to 5 min', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - type: 'query', - }).value.interval - ).toEqual('5m'); - }); - - test('defaults max signals to 100', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - }).value.max_signals - ).toEqual(100); - }); - - test('saved_id is required when type is saved_query and will not validate without out', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - }).error.message - ).toEqual('child "saved_id" fails because ["saved_id" is required]'); - }); - - test('saved_id is required when type is saved_query and validates with it', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - output_index: '.siem-signals', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - }).error - ).toBeFalsy(); - }); - - test('saved_query type can have filters with it', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - filters: [], - }).error - ).toBeFalsy(); - }); - - test('filters cannot be a string', () => { - expect( - createRulesSchema.validate< - Partial & { filters: string }> - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - filters: 'some string', - }).error.message - ).toEqual('child "filters" fails because ["filters" must be an array]'); - }); - - test('language validates with kuery', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - }).error - ).toBeFalsy(); - }); - - test('language validates with lucene', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - output_index: '.siem-signals', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'lucene', - }).error - ).toBeFalsy(); - }); - - test('language does not validate with something made up', () => { - expect( - createRulesSchema.validate< - Partial & { language: string }> - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'something-made-up', - }).error.message - ).toEqual('child "language" fails because ["language" must be one of [kuery, lucene]]'); - }); - - test('max_signals cannot be negative', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: -1, - }).error.message - ).toEqual('child "max_signals" fails because ["max_signals" must be greater than 0]'); - }); - - test('max_signals cannot be zero', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 0, - }).error.message - ).toEqual('child "max_signals" fails because ["max_signals" must be greater than 0]'); - }); - - test('max_signals can be 1', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error - ).toBeFalsy(); - }); - - test('You can optionally send in an array of tags', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - tags: ['tag_1', 'tag_2'], - }).error - ).toBeFalsy(); - }); - - test('You cannot send in an array of tags that are numbers', () => { - expect( - createRulesSchema.validate> & { tags: number[] }>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - tags: [0, 1, 2], - }).error.message - ).toEqual( - 'child "tags" fails because ["tags" at position 0 fails because ["0" must be a string]]' - ); - }); - - test('You cannot send in an array of threat that are missing "framework"', () => { - expect( - createRulesSchema.validate< - Partial> & { - threat: Array>>; - } - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [ - { - tactic: { - id: 'fakeId', - name: 'fakeName', - reference: 'fakeRef', - }, - technique: [ - { - id: 'techniqueId', - name: 'techniqueName', - reference: 'techniqueRef', - }, - ], - }, - ], - }).error.message - ).toEqual( - 'child "threat" fails because ["threat" at position 0 fails because [child "framework" fails because ["framework" is required]]]' - ); - }); - - test('You cannot send in an array of threat that are missing "tactic"', () => { - expect( - createRulesSchema.validate< - Partial> & { - threat: Array>>; - } - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [ - { - framework: 'fake', - technique: [ - { - id: 'techniqueId', - name: 'techniqueName', - reference: 'techniqueRef', - }, - ], - }, - ], - }).error.message - ).toEqual( - 'child "threat" fails because ["threat" at position 0 fails because [child "tactic" fails because ["tactic" is required]]]' - ); - }); - - test('You cannot send in an array of threat that are missing "technique"', () => { - expect( - createRulesSchema.validate< - Partial> & { - threat: Array>>; - } - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [ - { - framework: 'fake', - tactic: { - id: 'fakeId', - name: 'fakeName', - reference: 'fakeRef', - }, - }, - ], - }).error.message - ).toEqual( - 'child "threat" fails because ["threat" at position 0 fails because [child "technique" fails because ["technique" is required]]]' - ); - }); - - test('You can optionally send in an array of false positives', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - false_positives: ['false_1', 'false_2'], - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error - ).toBeFalsy(); - }); - - test('You cannot send in an array of false positives that are numbers', () => { - expect( - createRulesSchema.validate< - Partial> & { false_positives: number[] } - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - false_positives: [5, 4], - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error.message - ).toEqual( - 'child "false_positives" fails because ["false_positives" at position 0 fails because ["0" must be a string]]' - ); - }); - - test('You cannot set the immutable when trying to create a rule', () => { - expect( - createRulesSchema.validate< - Partial> & { immutable: number } - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - immutable: 5, - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error.message - ).toEqual('"immutable" is not allowed'); - }); - - test('You cannot set the risk_score to 101', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 101, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error.message - ).toEqual('child "risk_score" fails because ["risk_score" must be less than 101]'); - }); - - test('You cannot set the risk_score to -1', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: -1, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error.message - ).toEqual('child "risk_score" fails because ["risk_score" must be greater than -1]'); - }); - - test('You can set the risk_score to 0', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 0, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error - ).toBeFalsy(); - }); - - test('You can set the risk_score to 100', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 100, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error - ).toBeFalsy(); - }); - - test('You can set meta to any object you want', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - meta: { - somethingMadeUp: { somethingElse: true }, - }, - }).error - ).toBeFalsy(); - }); - - test('You cannot create meta as a string', () => { - expect( - createRulesSchema.validate & { meta: string }>>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - meta: 'should not work', - }).error.message - ).toEqual('child "meta" fails because ["meta" must be an object]'); - }); - - test('You can omit the query string when filters are present', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - language: 'kuery', - filters: [], - max_signals: 1, - }).error - ).toBeFalsy(); - }); - - test('validates with timeline_id and timeline_title', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - timeline_id: 'timeline-id', - timeline_title: 'timeline-title', - }).error - ).toBeFalsy(); - }); - - test('You cannot omit timeline_title when timeline_id is present', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - timeline_id: 'some_id', - }).error.message - ).toEqual('child "timeline_title" fails because ["timeline_title" is required]'); - }); - - test('You cannot have a null value for timeline_title when timeline_id is present', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - timeline_id: 'some_id', - timeline_title: null, - }).error.message - ).toEqual('child "timeline_title" fails because ["timeline_title" must be a string]'); - }); - - test('You cannot have empty string for timeline_title when timeline_id is present', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - timeline_id: 'some_id', - timeline_title: '', - }).error.message - ).toEqual('child "timeline_title" fails because ["timeline_title" is not allowed to be empty]'); - }); - - test('You cannot have timeline_title with an empty timeline_id', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - timeline_id: '', - timeline_title: 'some-title', - }).error.message - ).toEqual('child "timeline_id" fails because ["timeline_id" is not allowed to be empty]'); - }); - - test('You cannot have timeline_title without timeline_id', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - timeline_title: 'some-title', - }).error.message - ).toEqual('child "timeline_title" fails because ["timeline_title" is not allowed]'); - }); - - test('The default for "from" will be "now-6m"', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).value.from - ).toEqual('now-6m'); - }); - - test('The default for "to" will be "now"', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).value.to - ).toEqual('now'); - }); - - test('You cannot set the severity to a value other than low, medium, high, or critical', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'junk', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "severity" fails because ["severity" must be one of [low, medium, high, critical]]' - ); - }); - - test('The default for "actions" will be an empty array', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).value.actions - ).toEqual([]); - }); - - test('You cannot send in an array of actions that are missing "group"', () => { - expect( - createRulesSchema.validate< - Partial< - Omit & { - actions: Array>; - } - > - >({ - actions: [{ id: 'id', action_type_id: 'action_type_id', params: {} }], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "group" fails because ["group" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are missing "id"', () => { - expect( - createRulesSchema.validate< - Partial< - Omit & { - actions: Array>; - } - > - >({ - actions: [{ group: 'group', action_type_id: 'action_type_id', params: {} }], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "id" fails because ["id" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are missing "action_type_id"', () => { - expect( - createRulesSchema.validate< - Partial< - Omit & { - actions: Array>; - } - > - >({ - actions: [{ group: 'group', id: 'id', params: {} }], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "action_type_id" fails because ["action_type_id" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are missing "params"', () => { - expect( - createRulesSchema.validate< - Partial< - Omit & { - actions: Array>; - } - > - >({ - actions: [{ group: 'group', id: 'id', action_type_id: 'action_type_id' }], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "params" fails because ["params" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are including "actionTypeId"', () => { - expect( - createRulesSchema.validate< - Partial< - Omit & { - actions: AlertAction[]; - } - > - >({ - actions: [ - { - group: 'group', - id: 'id', - actionTypeId: 'actionTypeId', - params: {}, - }, - ], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "action_type_id" fails because ["action_type_id" is required]]]' - ); - }); - - test('The default for "throttle" will be null', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).value.throttle - ).toEqual(null); - }); - - describe('note', () => { - test('You can set note to a string', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - note: '# documentation markdown here', - }).error - ).toBeFalsy(); - }); - - test('You can set note to an emtpy string', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - note: '', - }).error - ).toBeFalsy(); - }); - - test('You cannot create note as an object', () => { - expect( - createRulesSchema.validate & { note: object }>>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - note: { - somethingHere: 'something else', - }, - }).error.message - ).toEqual('child "note" fails because ["note" must be a string]'); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note] does validate', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - }).error - ).toBeFalsy(); - }); - - // TODO: (LIST-FEATURE) We can enable this once we change the schema's to not be global per module but rather functions that can create the schema - // on demand. Since they are per module, we have a an issue where the ENV variables do not take effect. It is better we change all the - // schema's to be function calls to avoid global side effects or just wait until the feature is available. If you want to test this early, - // you can remove the .skip and set your env variable of export ELASTIC_XPACK_SIEM_LISTS_FEATURE=true locally - describe.skip('exceptions_list', () => { - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and exceptions_list] does validate', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - exceptions_list: [ - { - field: 'source.ip', - values_operator: 'included', - values_type: 'exists', - }, - { - field: 'host.name', - values_operator: 'excluded', - values_type: 'match', - values: [ - { - name: 'rock01', - }, - ], - and: [ - { - field: 'host.id', - values_operator: 'included', - values_type: 'match_all', - values: [ - { - name: '123', - }, - { - name: '678', - }, - ], - }, - ], - }, - ], - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and empty exceptions_list] does validate', () => { - expect( - createRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - exceptions_list: [], - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and invalid exceptions_list] does NOT validate', () => { - expect( - createRulesSchema.validate>>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - exceptions_list: [{ invalid_value: 'invalid value' }], - }).error.message - ).toEqual( - 'child "exceptions_list" fails because ["exceptions_list" at position 0 fails because [child "field" fails because ["field" is required]]]' - ); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and non-existent exceptions_list] does validate with empty exceptions_list', () => { - expect( - createRulesSchema.validate>>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - }).value.exceptions_list - ).toEqual([]); - }); - }); - }); -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/create_rules_schema.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/create_rules_schema.ts deleted file mode 100644 index dec8b5ccbc790..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/create_rules_schema.ts +++ /dev/null @@ -1,102 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import Joi from 'joi'; - -/* eslint-disable @typescript-eslint/camelcase */ -import { - actions, - anomaly_threshold, - enabled, - description, - false_positives, - filters, - from, - index, - rule_id, - interval, - query, - language, - output_index, - saved_id, - timeline_id, - timeline_title, - meta, - risk_score, - max_signals, - name, - severity, - tags, - to, - type, - threat, - throttle, - references, - note, - version, - lists, - machine_learning_job_id, -} from './schemas'; -/* eslint-enable @typescript-eslint/camelcase */ - -import { DEFAULT_MAX_SIGNALS } from '../../../../../common/constants'; -import { hasListsFeature } from '../../feature_flags'; - -export const createRulesSchema = Joi.object({ - actions: actions.default([]), - anomaly_threshold: anomaly_threshold.when('type', { - is: 'machine_learning', - then: Joi.required(), - otherwise: Joi.forbidden(), - }), - description: description.required(), - enabled: enabled.default(true), - false_positives: false_positives.default([]), - filters, - from: from.default('now-6m'), - rule_id, - index, - interval: interval.default('5m'), - query: query.when('type', { - is: 'machine_learning', - then: Joi.forbidden(), - otherwise: query.allow('').default(''), - }), - language: language.when('type', { - is: 'machine_learning', - then: Joi.forbidden(), - otherwise: language.default('kuery'), - }), - output_index, - saved_id: saved_id.when('type', { - is: 'saved_query', - then: Joi.required(), - otherwise: Joi.forbidden(), - }), - timeline_id, - timeline_title, - meta, - machine_learning_job_id: machine_learning_job_id.when('type', { - is: 'machine_learning', - then: Joi.required(), - otherwise: Joi.forbidden(), - }), - risk_score: risk_score.required(), - max_signals: max_signals.default(DEFAULT_MAX_SIGNALS), - name: name.required(), - severity: severity.required(), - tags: tags.default([]), - to: to.default('now'), - type: type.required(), - threat: threat.default([]), - throttle: throttle.default(null), - references: references.default([]), - note: note.allow(''), - version: version.default(1), - - // TODO: (LIST-FEATURE) Remove the hasListsFeatures once this is ready for release - exceptions_list: hasListsFeature() ? lists.default([]) : lists.forbidden().default([]), -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/export_rules_schema.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/export_rules_schema.test.ts deleted file mode 100644 index 0e71237f75232..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/export_rules_schema.test.ts +++ /dev/null @@ -1,113 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { exportRulesSchema, exportRulesQuerySchema } from './export_rules_schema'; -import { ExportRulesRequestParams } from '../../rules/types'; -import { setFeatureFlagsForTestsOnly, unSetFeatureFlagsForTestsOnly } from '../../feature_flags'; - -describe('create rules schema', () => { - beforeAll(() => { - setFeatureFlagsForTestsOnly(); - }); - - afterAll(() => { - unSetFeatureFlagsForTestsOnly(); - }); - - describe('exportRulesSchema', () => { - test('null value or absent values validate', () => { - expect(exportRulesSchema.validate(null).error).toBeFalsy(); - }); - - test('empty object does not validate', () => { - expect( - exportRulesSchema.validate>({}).error - ).toBeTruthy(); - }); - - test('empty object array does validate', () => { - expect( - exportRulesSchema.validate>({ objects: [] }).error - ).toBeTruthy(); - }); - - test('array with rule_id validates', () => { - expect( - exportRulesSchema.validate>({ - objects: [{ rule_id: 'test-1' }], - }).error - ).toBeFalsy(); - }); - - test('array with id does not validate as we do not allow that on purpose since we export rule_id', () => { - expect( - exportRulesSchema.validate>({ - objects: [{ id: 'test-1' }], - }).error.message - ).toEqual( - 'child "objects" fails because ["objects" at position 0 fails because ["id" is not allowed]]' - ); - }); - }); - - describe('exportRulesQuerySchema', () => { - test('default value for file_name is export.ndjson', () => { - expect( - exportRulesQuerySchema.validate>({}).value - .file_name - ).toEqual('export.ndjson'); - }); - - test('default value for exclude_export_details is false', () => { - expect( - exportRulesQuerySchema.validate>({}).value - .exclude_export_details - ).toEqual(false); - }); - - test('file_name validates', () => { - expect( - exportRulesQuerySchema.validate>({ - file_name: 'test.ndjson', - }).error - ).toBeFalsy(); - }); - - test('file_name does not validate with a number', () => { - expect( - exportRulesQuerySchema.validate< - Partial & { file_name: number }> - >({ - file_name: 5, - }).error.message - ).toEqual('child "file_name" fails because ["file_name" must be a string]'); - }); - - test('exclude_export_details validates with a boolean true', () => { - expect( - exportRulesQuerySchema.validate>({ - exclude_export_details: true, - }).error - ).toBeFalsy(); - }); - - test('exclude_export_details does not validate with a weird string', () => { - expect( - exportRulesQuerySchema.validate< - Partial< - Omit & { - exclude_export_details: string; - } - > - >({ - exclude_export_details: 'blah', - }).error.message - ).toEqual( - 'child "exclude_export_details" fails because ["exclude_export_details" must be a boolean]' - ); - }); - }); -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/export_rules_schema.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/export_rules_schema.ts deleted file mode 100644 index a14d81604d9f8..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/export_rules_schema.ts +++ /dev/null @@ -1,22 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import Joi from 'joi'; - -/* eslint-disable @typescript-eslint/camelcase */ -import { objects, exclude_export_details, file_name } from './schemas'; -/* eslint-disable @typescript-eslint/camelcase */ - -export const exportRulesSchema = Joi.object({ - objects, -}) - .min(1) - .allow(null); - -export const exportRulesQuerySchema = Joi.object({ - file_name: file_name.default('export.ndjson'), - exclude_export_details: exclude_export_details.default(false), -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/find_rules_schema.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/find_rules_schema.test.ts deleted file mode 100644 index ffbfd193873a8..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/find_rules_schema.test.ts +++ /dev/null @@ -1,147 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { findRulesSchema } from './find_rules_schema'; -import { FindParamsRest } from '../../rules/types'; -import { setFeatureFlagsForTestsOnly, unSetFeatureFlagsForTestsOnly } from '../../feature_flags'; - -describe('find rules schema', () => { - beforeAll(() => { - setFeatureFlagsForTestsOnly(); - }); - - afterAll(() => { - unSetFeatureFlagsForTestsOnly(); - }); - - test('empty objects do validate', () => { - expect(findRulesSchema.validate>({}).error).toBeFalsy(); - }); - - test('all values validate', () => { - expect( - findRulesSchema.validate>({ - per_page: 5, - page: 1, - sort_field: 'some field', - fields: ['field 1', 'field 2'], - filter: 'some filter', - sort_order: 'asc', - }).error - ).toBeFalsy(); - }); - - test('made up parameters do not validate', () => { - expect( - findRulesSchema.validate>({ - madeUp: 'hi', - }).error - ).toBeTruthy(); - }); - - test('per_page validates', () => { - expect( - findRulesSchema.validate>({ per_page: 5 }).error - ).toBeFalsy(); - }); - - test('page validates', () => { - expect( - findRulesSchema.validate>({ page: 5 }).error - ).toBeFalsy(); - }); - - test('sort_field validates', () => { - expect( - findRulesSchema.validate>({ sort_field: 'some value' }).error - ).toBeFalsy(); - }); - - test('fields validates with a string', () => { - expect( - findRulesSchema.validate>({ fields: ['some value'] }).error - ).toBeFalsy(); - }); - - test('fields validates with multiple strings', () => { - expect( - findRulesSchema.validate>({ - fields: ['some value 1', 'some value 2'], - }).error - ).toBeFalsy(); - }); - - test('fields does not validate with a number', () => { - expect( - findRulesSchema.validate> & { fields: number[] }>({ - fields: [5], - }).error.message - ).toEqual( - 'child "fields" fails because ["fields" at position 0 fails because ["0" must be a string]]' - ); - }); - - test('per page has a default of 20', () => { - expect(findRulesSchema.validate>({}).value.per_page).toEqual(20); - }); - - test('page has a default of 1', () => { - expect(findRulesSchema.validate>({}).value.page).toEqual(1); - }); - - test('filter works with a string', () => { - expect( - findRulesSchema.validate>({ - filter: 'some value 1', - }).error - ).toBeFalsy(); - }); - - test('filter does not work with a number', () => { - expect( - findRulesSchema.validate> & { filter: number }>({ - filter: 5, - }).error.message - ).toEqual('child "filter" fails because ["filter" must be a string]'); - }); - - test('sort_order requires sort_field to work', () => { - expect( - findRulesSchema.validate>({ - sort_order: 'asc', - }).error.message - ).toEqual('child "sort_field" fails because ["sort_field" is required]'); - }); - - test('sort_order and sort_field validate together', () => { - expect( - findRulesSchema.validate>({ - sort_order: 'asc', - sort_field: 'some field', - }).error - ).toBeFalsy(); - }); - - test('sort_order validates with desc and sort_field', () => { - expect( - findRulesSchema.validate>({ - sort_order: 'desc', - sort_field: 'some field', - }).error - ).toBeFalsy(); - }); - - test('sort_order does not validate with a string other than asc and desc', () => { - expect( - findRulesSchema.validate< - Partial> & { sort_order: string } - >({ - sort_order: 'some other string', - sort_field: 'some field', - }).error.message - ).toEqual('child "sort_order" fails because ["sort_order" must be one of [asc, desc]]'); - }); -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/find_rules_schema.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/find_rules_schema.ts deleted file mode 100644 index 3cc5b9ca44530..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/find_rules_schema.ts +++ /dev/null @@ -1,24 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import Joi from 'joi'; - -/* eslint-disable @typescript-eslint/camelcase */ -import { queryFilter, fields, per_page, page, sort_field, sort_order } from './schemas'; -/* eslint-enable @typescript-eslint/camelcase */ - -export const findRulesSchema = Joi.object({ - fields, - filter: queryFilter, - per_page, - page, - sort_field: Joi.when(Joi.ref('sort_order'), { - is: Joi.exist(), - then: sort_field.required(), - otherwise: sort_field.optional(), - }), - sort_order, -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/import_rules_schema.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/import_rules_schema.test.ts deleted file mode 100644 index cb03c4781cb6c..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/import_rules_schema.test.ts +++ /dev/null @@ -1,1841 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { AlertAction } from '../../../../../../alerts/common'; -import { - importRulesSchema, - importRulesQuerySchema, - importRulesPayloadSchema, -} from './import_rules_schema'; -import { RuleAlertAction } from '../../../../../common/detection_engine/types'; -import { ThreatParams, ImportRuleAlertRest } from '../../types'; -import { ImportRulesRequestParams } from '../../rules/types'; -import { setFeatureFlagsForTestsOnly, unSetFeatureFlagsForTestsOnly } from '../../feature_flags'; - -describe('import rules schema', () => { - beforeAll(() => { - setFeatureFlagsForTestsOnly(); - }); - - afterAll(() => { - unSetFeatureFlagsForTestsOnly(); - }); - - describe('importRulesSchema', () => { - test('empty objects do not validate', () => { - expect(importRulesSchema.validate>({}).error).toBeTruthy(); - }); - - test('made up values do not validate', () => { - expect( - importRulesSchema.validate>({ - madeUp: 'hi', - }).error - ).toBeTruthy(); - }); - - test('[rule_id] does not validate', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description] does not validate', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from] does not validate', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to] does not validate', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name] does not validate', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity] does not validate', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity, type] does not validate', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity, type, interval] does not validate', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity, type, interval, index] does not validate', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - interval: '5m', - index: ['index-1'], - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity, type, query, index, interval] does validate', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - query: 'some query', - index: ['index-1'], - interval: '5m', - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, query, language] does not validate', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some query', - language: 'kuery', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, query, language, risk_score] does validate', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some query', - language: 'kuery', - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, query, language, risk_score, output_index] does validate', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some query', - language: 'kuery', - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score] does validate', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, output_index] does validate', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - }).error - ).toBeFalsy(); - }); - - test('You can send in an empty array to threat', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [], - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, output_index, threat] does validate', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - threat: [ - { - framework: 'someFramework', - tactic: { - id: 'fakeId', - name: 'fakeName', - reference: 'fakeRef', - }, - technique: [ - { - id: 'techniqueId', - name: 'techniqueName', - reference: 'techniqueRef', - }, - ], - }, - ], - }).error - ).toBeFalsy(); - }); - - test('allows references to be sent as valid', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - }).error - ).toBeFalsy(); - }); - - test('defaults references to an array', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some-query', - language: 'kuery', - }).value.references - ).toEqual([]); - }); - - test('references cannot be numbers', () => { - expect( - importRulesSchema.validate< - Partial> & { references: number[] } - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some-query', - language: 'kuery', - references: [5], - }).error.message - ).toEqual( - 'child "references" fails because ["references" at position 0 fails because ["0" must be a string]]' - ); - }); - - test('indexes cannot be numbers', () => { - expect( - importRulesSchema.validate< - Partial> & { index: number[] } - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: [5], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some-query', - language: 'kuery', - }).error.message - ).toEqual( - 'child "index" fails because ["index" at position 0 fails because ["0" must be a string]]' - ); - }); - - test('defaults interval to 5 min', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - type: 'query', - }).value.interval - ).toEqual('5m'); - }); - - test('defaults max signals to 100', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - }).value.max_signals - ).toEqual(100); - }); - - test('saved_id is required when type is saved_query and will not validate without out', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - }).error.message - ).toEqual('child "saved_id" fails because ["saved_id" is required]'); - }); - - test('saved_id is required when type is saved_query and validates with it', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - output_index: '.siem-signals', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - }).error - ).toBeFalsy(); - }); - - test('saved_query type can have filters with it', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - filters: [], - }).error - ).toBeFalsy(); - }); - - test('filters cannot be a string', () => { - expect( - importRulesSchema.validate< - Partial & { filters: string }> - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - filters: 'some string', - }).error.message - ).toEqual('child "filters" fails because ["filters" must be an array]'); - }); - - test('language validates with kuery', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - }).error - ).toBeFalsy(); - }); - - test('language validates with lucene', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - output_index: '.siem-signals', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'lucene', - }).error - ).toBeFalsy(); - }); - - test('language does not validate with something made up', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'something-made-up', - }).error.message - ).toEqual('child "language" fails because ["language" must be one of [kuery, lucene]]'); - }); - - test('max_signals cannot be negative', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: -1, - }).error.message - ).toEqual('child "max_signals" fails because ["max_signals" must be greater than 0]'); - }); - - test('max_signals cannot be zero', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 0, - }).error.message - ).toEqual('child "max_signals" fails because ["max_signals" must be greater than 0]'); - }); - - test('max_signals can be 1', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error - ).toBeFalsy(); - }); - - test('You can optionally send in an array of tags', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - tags: ['tag_1', 'tag_2'], - }).error - ).toBeFalsy(); - }); - - test('You cannot send in an array of tags that are numbers', () => { - expect( - importRulesSchema.validate> & { tags: number[] }>( - { - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - tags: [0, 1, 2], - } - ).error.message - ).toEqual( - 'child "tags" fails because ["tags" at position 0 fails because ["0" must be a string]]' - ); - }); - - test('You cannot send in an array of threat that are missing "framework"', () => { - expect( - importRulesSchema.validate< - Partial> & { - threat: Array>>; - } - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [ - { - tactic: { - id: 'fakeId', - name: 'fakeName', - reference: 'fakeRef', - }, - technique: [ - { - id: 'techniqueId', - name: 'techniqueName', - reference: 'techniqueRef', - }, - ], - }, - ], - }).error.message - ).toEqual( - 'child "threat" fails because ["threat" at position 0 fails because [child "framework" fails because ["framework" is required]]]' - ); - }); - - test('You cannot send in an array of threat that are missing "tactic"', () => { - expect( - importRulesSchema.validate< - Partial> & { - threat: Array>>; - } - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [ - { - framework: 'fake', - technique: [ - { - id: 'techniqueId', - name: 'techniqueName', - reference: 'techniqueRef', - }, - ], - }, - ], - }).error.message - ).toEqual( - 'child "threat" fails because ["threat" at position 0 fails because [child "tactic" fails because ["tactic" is required]]]' - ); - }); - - test('You cannot send in an array of threat that are missing "technique"', () => { - expect( - importRulesSchema.validate< - Partial> & { - threat: Array>>; - } - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [ - { - framework: 'fake', - tactic: { - id: 'fakeId', - name: 'fakeName', - reference: 'fakeRef', - }, - }, - ], - }).error.message - ).toEqual( - 'child "threat" fails because ["threat" at position 0 fails because [child "technique" fails because ["technique" is required]]]' - ); - }); - - test('You can optionally send in an array of false positives', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - false_positives: ['false_1', 'false_2'], - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error - ).toBeFalsy(); - }); - - test('You cannot send in an array of false positives that are numbers', () => { - expect( - importRulesSchema.validate< - Partial> & { false_positives: number[] } - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - false_positives: [5, 4], - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error.message - ).toEqual( - 'child "false_positives" fails because ["false_positives" at position 0 fails because ["0" must be a string]]' - ); - }); - - test('You can optionally set the immutable to be false', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - immutable: false, - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error - ).toBeFalsy(); - }); - - test('You cannnot set immutable to be true', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - immutable: true, - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error.message - ).toEqual('child "immutable" fails because ["immutable" must be one of [false]]'); - }); - - test('You cannot set the immutable to be a number', () => { - expect( - importRulesSchema.validate< - Partial> & { immutable: number } - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - immutable: 5, - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error.message - ).toEqual('child "immutable" fails because ["immutable" must be a boolean]'); - }); - - test('You cannot set the risk_score to 101', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 101, - description: 'some description', - from: 'now-5m', - to: 'now', - immutable: false, - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error.message - ).toEqual('child "risk_score" fails because ["risk_score" must be less than 101]'); - }); - - test('You cannot set the risk_score to -1', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: -1, - description: 'some description', - from: 'now-5m', - to: 'now', - immutable: false, - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error.message - ).toEqual('child "risk_score" fails because ["risk_score" must be greater than -1]'); - }); - - test('You can set the risk_score to 0', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 0, - description: 'some description', - from: 'now-5m', - to: 'now', - immutable: false, - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error - ).toBeFalsy(); - }); - - test('You can set the risk_score to 100', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 100, - description: 'some description', - from: 'now-5m', - to: 'now', - immutable: false, - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error - ).toBeFalsy(); - }); - - test('You can set meta to any object you want', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - immutable: false, - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - meta: { - somethingMadeUp: { somethingElse: true }, - }, - }).error - ).toBeFalsy(); - }); - - test('You cannot create meta as a string', () => { - expect( - importRulesSchema.validate & { meta: string }>>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - immutable: false, - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - meta: 'should not work', - }).error.message - ).toEqual('child "meta" fails because ["meta" must be an object]'); - }); - - test('You can omit the query string when filters are present', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - immutable: false, - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - language: 'kuery', - filters: [], - max_signals: 1, - }).error - ).toBeFalsy(); - }); - - test('validates with timeline_id and timeline_title', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - timeline_id: 'timeline-id', - timeline_title: 'timeline-title', - }).error - ).toBeFalsy(); - }); - - test('You cannot omit timeline_title when timeline_id is present', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - timeline_id: 'some_id', - }).error.message - ).toEqual('child "timeline_title" fails because ["timeline_title" is required]'); - }); - - test('You cannot have a null value for timeline_title when timeline_id is present', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - timeline_id: 'some_id', - timeline_title: null, - }).error.message - ).toEqual('child "timeline_title" fails because ["timeline_title" must be a string]'); - }); - - test('You cannot have empty string for timeline_title when timeline_id is present', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - timeline_id: 'some_id', - timeline_title: '', - }).error.message - ).toEqual( - 'child "timeline_title" fails because ["timeline_title" is not allowed to be empty]' - ); - }); - - test('You cannot have timeline_title with an empty timeline_id', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - timeline_id: '', - timeline_title: 'some-title', - }).error.message - ).toEqual('child "timeline_id" fails because ["timeline_id" is not allowed to be empty]'); - }); - - test('You cannot have timeline_title without timeline_id', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - timeline_title: 'some-title', - }).error.message - ).toEqual('child "timeline_title" fails because ["timeline_title" is not allowed]'); - }); - - test('rule_id is required and you cannot get by with just id', () => { - expect( - importRulesSchema.validate>({ - id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - }).error.message - ).toEqual('child "rule_id" fails because ["rule_id" is required]'); - }); - - test('it validates with created_at, updated_at, created_by, updated_by values', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - created_at: '2020-01-09T06:15:24.749Z', - updated_at: '2020-01-09T06:15:24.749Z', - created_by: 'Braden Hassanabad', - updated_by: 'Evan Hassanabad', - }).error - ).toBeFalsy(); - }); - - test('it does not validate with epoch strings for created_at', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - created_at: '1578550728650', - updated_at: '2020-01-09T06:15:24.749Z', - created_by: 'Braden Hassanabad', - updated_by: 'Evan Hassanabad', - }).error.message - ).toEqual('child "created_at" fails because ["created_at" must be a valid ISO 8601 date]'); - }); - - test('it does not validate with epoch strings for updated_at', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - created_at: '2020-01-09T06:15:24.749Z', - updated_at: '1578550728650', - created_by: 'Braden Hassanabad', - updated_by: 'Evan Hassanabad', - }).error.message - ).toEqual('child "updated_at" fails because ["updated_at" must be a valid ISO 8601 date]'); - }); - }); - - describe('importRulesQuerySchema', () => { - test('overwrite gets a default value of false', () => { - expect( - importRulesQuerySchema.validate>({}).value - .overwrite - ).toEqual(false); - }); - - test('overwrite validates with a boolean true', () => { - expect( - importRulesQuerySchema.validate>({ - overwrite: true, - }).error - ).toBeFalsy(); - }); - - test('overwrite does not validate with a weird string', () => { - expect( - importRulesQuerySchema.validate< - Partial< - Omit & { - overwrite: string; - } - > - >({ - overwrite: 'blah', - }).error - ).toBeTruthy(); - }); - }); - - describe('importRulesPayloadSchema', () => { - test('does not validate with an empty object', () => { - expect(importRulesPayloadSchema.validate({}).error).toBeTruthy(); - }); - - test('does validate with a file object', () => { - expect(importRulesPayloadSchema.validate({ file: {} }).error).toBeFalsy(); - }); - }); - - test('The default for "from" will be "now-6m"', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).value.from - ).toEqual('now-6m'); - }); - - test('The default for "to" will be "now"', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - language: 'kuery', - max_signals: 1, - version: 1, - }).value.to - ).toEqual('now'); - }); - - test('You cannot set the severity to a value other than low, medium, high, or critical', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'junk', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "severity" fails because ["severity" must be one of [low, medium, high, critical]]' - ); - }); - - test('The default for "actions" will be an empty array', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).value.actions - ).toEqual([]); - }); - - test('You cannot send in an array of actions that are missing "group"', () => { - expect( - importRulesSchema.validate< - Partial< - Omit & { - actions: Array>; - } - > - >({ - actions: [{ id: 'id', action_type_id: 'action_type_id', params: {} }], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'junk', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "group" fails because ["group" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are missing "id"', () => { - expect( - importRulesSchema.validate< - Partial< - Omit & { - actions: Array>; - } - > - >({ - actions: [{ group: 'group', action_type_id: 'action_type_id', params: {} }], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "id" fails because ["id" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are missing "action_type_id"', () => { - expect( - importRulesSchema.validate< - Partial< - Omit & { - actions: Array>; - } - > - >({ - actions: [{ group: 'group', id: 'id', params: {} }], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "action_type_id" fails because ["action_type_id" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are missing "params"', () => { - expect( - importRulesSchema.validate< - Partial< - Omit & { - actions: Array>; - } - > - >({ - actions: [{ group: 'group', id: 'id', action_type_id: 'action_type_id' }], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "params" fails because ["params" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are including "actionTypeId', () => { - expect( - importRulesSchema.validate< - Partial< - Omit & { - actions: AlertAction[]; - } - > - >({ - actions: [ - { - group: 'group', - id: 'id', - actionTypeId: 'actionTypeId', - params: {}, - }, - ], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "action_type_id" fails because ["action_type_id" is required]]]' - ); - }); - - test('The default for "throttle" will be null', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).value.throttle - ).toEqual(null); - }); - - describe('note', () => { - test('You can set note to a string', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - immutable: false, - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - meta: { - somethingMadeUp: { somethingElse: true }, - }, - note: '# test header', - }).error - ).toBeFalsy(); - }); - - test('You can set note to an empty string', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - immutable: false, - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - meta: { - somethingMadeUp: { somethingElse: true }, - }, - note: '', - }).error - ).toBeFalsy(); - }); - - test('You cannot create note set to null', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - immutable: false, - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - meta: { - somethingMadeUp: { somethingElse: true }, - }, - note: null, - }).error.message - ).toEqual('child "note" fails because ["note" must be a string]'); - }); - - test('You cannot create note as something other than a string', () => { - expect( - importRulesSchema.validate & { note: object }>>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - immutable: false, - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - meta: { - somethingMadeUp: { somethingElse: true }, - }, - note: { - somethingMadeUp: { somethingElse: true }, - }, - }).error.message - ).toEqual('child "note" fails because ["note" must be a string]'); - }); - }); - - // TODO: (LIST-FEATURE) We can enable this once we change the schema's to not be global per module but rather functions that can create the schema - // on demand. Since they are per module, we have a an issue where the ENV variables do not take effect. It is better we change all the - // schema's to be function calls to avoid global side effects or just wait until the feature is available. If you want to test this early, - // you can remove the .skip and set your env variable of export ELASTIC_XPACK_SIEM_LISTS_FEATURE=true locally - describe.skip('exceptions_list', () => { - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and exceptions_list] does validate', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - exceptions_list: [ - { - field: 'source.ip', - values_operator: 'included', - values_type: 'exists', - }, - { - field: 'host.name', - values_operator: 'excluded', - values_type: 'match', - values: [ - { - name: 'rock01', - }, - ], - and: [ - { - field: 'host.id', - values_operator: 'included', - values_type: 'match_all', - values: [ - { - name: '123', - }, - { - name: '678', - }, - ], - }, - ], - }, - ], - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and empty exceptions_list] does validate', () => { - expect( - importRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - exceptions_list: [], - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and invalid exceptions_list] does NOT validate and exceptions_list is empty', () => { - expect( - importRulesSchema.validate>>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - exceptions_list: [{ invalid_value: 'invalid value' }], - }).error.message - ).toEqual( - 'child "exceptions_list" fails because ["exceptions_list" at position 0 fails because [child "field" fails because ["field" is required]]]' - ); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and non-existent exceptions_list] does validate', () => { - expect( - importRulesSchema.validate>>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - }).value.exceptions_list - ).toEqual([]); - }); - }); -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/import_rules_schema.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/import_rules_schema.ts deleted file mode 100644 index d3c728ebac1a9..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/import_rules_schema.ts +++ /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; - * you may not use this file except in compliance with the Elastic License. - */ - -import Joi from 'joi'; - -/* eslint-disable @typescript-eslint/camelcase */ -import { - id, - actions, - created_at, - updated_at, - created_by, - updated_by, - enabled, - description, - false_positives, - filters, - from, - immutable, - index, - rule_id, - interval, - query, - language, - output_index, - saved_id, - timeline_id, - timeline_title, - meta, - risk_score, - max_signals, - name, - severity, - tags, - to, - type, - threat, - throttle, - references, - note, - version, - lists, - anomaly_threshold, - machine_learning_job_id, -} from './schemas'; -/* eslint-enable @typescript-eslint/camelcase */ - -import { DEFAULT_MAX_SIGNALS } from '../../../../../common/constants'; -import { hasListsFeature } from '../../feature_flags'; - -/** - * Differences from this and the createRulesSchema are - * - rule_id is required - * - id is optional (but ignored in the import code - rule_id is exclusively used for imports) - * - created_at is optional (but ignored in the import code) - * - updated_at is optional (but ignored in the import code) - * - created_by is optional (but ignored in the import code) - * - updated_by is optional (but ignored in the import code) - */ -export const importRulesSchema = Joi.object({ - anomaly_threshold: anomaly_threshold.when('type', { - is: 'machine_learning', - then: Joi.required(), - otherwise: Joi.forbidden(), - }), - id, - actions: actions.default([]), - description: description.required(), - enabled: enabled.default(true), - false_positives: false_positives.default([]), - filters, - from: from.default('now-6m'), - rule_id: rule_id.required(), - immutable: immutable.default(false).valid(false), - index, - interval: interval.default('5m'), - query: query.when('type', { - is: 'machine_learning', - then: Joi.forbidden(), - otherwise: query.allow('').default(''), - }), - language: language.when('type', { - is: 'machine_learning', - then: Joi.forbidden(), - otherwise: language.default('kuery'), - }), - output_index, - machine_learning_job_id: machine_learning_job_id.when('type', { - is: 'machine_learning', - then: Joi.required(), - otherwise: Joi.forbidden(), - }), - saved_id: saved_id.when('type', { - is: 'saved_query', - then: Joi.required(), - otherwise: Joi.forbidden(), - }), - timeline_id, - timeline_title, - meta, - risk_score: risk_score.required(), - max_signals: max_signals.default(DEFAULT_MAX_SIGNALS), - name: name.required(), - severity: severity.required(), - tags: tags.default([]), - to: to.default('now'), - type: type.required(), - threat: threat.default([]), - throttle: throttle.default(null), - references: references.default([]), - note: note.allow(''), - version: version.default(1), - created_at, - updated_at, - created_by, - updated_by, - - // TODO: (LIST-FEATURE) Remove the hasListsFeatures once this is ready for release - exceptions_list: hasListsFeature() ? lists.default([]) : lists.forbidden().default([]), -}); - -export const importRulesQuerySchema = Joi.object({ - overwrite: Joi.boolean().default(false), -}); - -export const importRulesPayloadSchema = Joi.object({ - file: Joi.object().required(), -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/patch_rules_bulk_schema.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/patch_rules_bulk_schema.test.ts deleted file mode 100644 index e87c732e8a2f7..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/patch_rules_bulk_schema.test.ts +++ /dev/null @@ -1,100 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { patchRulesBulkSchema } from './patch_rules_bulk_schema'; -import { PatchRuleAlertParamsRest } from '../../rules/types'; -import { setFeatureFlagsForTestsOnly, unSetFeatureFlagsForTestsOnly } from '../../feature_flags'; - -// only the basics of testing are here. -// see: patch_rules_schema.test.ts for the bulk of the validation tests -// this just wraps patchRulesSchema in an array -describe('patch_rules_bulk_schema', () => { - beforeAll(() => { - setFeatureFlagsForTestsOnly(); - }); - - afterAll(() => { - unSetFeatureFlagsForTestsOnly(); - }); - - test('can take an empty array and validate it', () => { - expect( - patchRulesBulkSchema.validate>>([]).error - ).toBeFalsy(); - }); - - test('made up values do not validate', () => { - expect( - patchRulesBulkSchema.validate<[{ madeUp: string }]>([ - { - madeUp: 'hi', - }, - ]).error - ).toBeTruthy(); - }); - - test('single array of [id] does validate', () => { - expect( - patchRulesBulkSchema.validate>>([ - { - id: 'rule-1', - }, - ]).error - ).toBeFalsy(); - }); - - test('two values of [id] does validate', () => { - expect( - patchRulesBulkSchema.validate>>([ - { - id: 'rule-1', - }, - { - id: 'rule-2', - }, - ]).error - ).toBeFalsy(); - }); - - test('can set "note" to be a string', () => { - expect( - patchRulesBulkSchema.validate>>([ - { - id: 'rule-1', - note: 'hi', - }, - ]).error - ).toBeFalsy(); - }); - - test('can set "note" to be an empty string', () => { - expect( - patchRulesBulkSchema.validate>>([ - { - id: 'rule-1', - note: '', - }, - ]).error - ).toBeFalsy(); - }); - - test('cannot set "note" to be anything other than a string', () => { - expect( - patchRulesBulkSchema.validate< - Array & { note: object }>> - >([ - { - id: 'rule-1', - note: { - someprop: 'some value here', - }, - }, - ]).error.message - ).toEqual( - '"value" at position 0 fails because [child "note" fails because ["note" must be a string]]' - ); - }); -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/patch_rules_bulk_schema.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/patch_rules_bulk_schema.ts deleted file mode 100644 index ff813bce84add..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/patch_rules_bulk_schema.ts +++ /dev/null @@ -1,11 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import Joi from 'joi'; - -import { patchRulesSchema } from './patch_rules_schema'; - -export const patchRulesBulkSchema = Joi.array().items(patchRulesSchema); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/patch_rules_schema.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/patch_rules_schema.test.ts deleted file mode 100644 index 218cae68db036..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/patch_rules_schema.test.ts +++ /dev/null @@ -1,1362 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { AlertAction } from '../../../../../../alerts/common'; -import { patchRulesSchema } from './patch_rules_schema'; -import { PatchRuleAlertParamsRest } from '../../rules/types'; -import { RuleAlertAction } from '../../../../../common/detection_engine/types'; -import { ThreatParams } from '../../types'; -import { setFeatureFlagsForTestsOnly, unSetFeatureFlagsForTestsOnly } from '../../feature_flags'; - -describe('patch rules schema', () => { - beforeAll(() => { - setFeatureFlagsForTestsOnly(); - }); - - afterAll(() => { - unSetFeatureFlagsForTestsOnly(); - }); - - test('empty objects do not validate as they require at least id or rule_id', () => { - expect(patchRulesSchema.validate>({}).error).toBeTruthy(); - }); - - test('made up values do not validate', () => { - expect( - patchRulesSchema.validate>({ - madeUp: 'hi', - }).error - ).toBeTruthy(); - }); - - test('[id] does validate', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - }).error - ).toBeFalsy(); - }); - - test('[rule_id] does validate', () => { - expect( - patchRulesSchema.validate>({ - rule_id: 'rule-1', - }).error - ).toBeFalsy(); - }); - - test('[id] and [rule_id] does not validate', () => { - expect( - patchRulesSchema.validate>({ - id: 'id-1', - rule_id: 'rule-1', - }).error.message - ).toEqual('"value" contains a conflict between exclusive peers [id, rule_id]'); - }); - - test('[rule_id, description] does validate', () => { - expect( - patchRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - }).error - ).toBeFalsy(); - }); - - test('[id, description] does validate', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - }).error - ).toBeFalsy(); - }); - - test('[id, risk_score] does validate', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - risk_score: 10, - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from] does validate', () => { - expect( - patchRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - }).error - ).toBeFalsy(); - }); - - test('[id, description, from] does validate', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to] does validate', () => { - expect( - patchRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - }).error - ).toBeFalsy(); - }); - - test('[id, description, from, to] does validate', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, name] does validate', () => { - expect( - patchRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - }).error - ).toBeFalsy(); - }); - - test('[id, description, from, to, name] does validate', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, name, severity] does validate', () => { - expect( - patchRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - }).error - ).toBeFalsy(); - }); - - test('[id, description, from, to, name, severity] does validate', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, name, severity, type] does validate', () => { - expect( - patchRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - }).error - ).toBeFalsy(); - }); - - test('[id, description, from, to, name, severity, type] does validate', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, name, severity, type, interval] does validate', () => { - expect( - patchRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - }).error - ).toBeFalsy(); - }); - - test('[id, description, from, to, name, severity, type, interval] does validate', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type] does validate', () => { - expect( - patchRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - }).error - ).toBeFalsy(); - }); - - test('[id, description, from, to, index, name, severity, interval, type] does validate', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, query] does validate', () => { - expect( - patchRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some query', - }).error - ).toBeFalsy(); - }); - - test('[id, description, from, to, index, name, severity, interval, type, query] does validate', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some query', - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, query, language] does validate', () => { - expect( - patchRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some query', - language: 'kuery', - }).error - ).toBeFalsy(); - }); - - test('[id, description, from, to, index, name, severity, interval, type, query, language] does validate', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some query', - language: 'kuery', - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, type, filter] does validate', () => { - expect( - patchRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - }).error - ).toBeFalsy(); - }); - - test('[id, description, from, to, index, name, severity, type, filter] does validate', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - }).error - ).toBeFalsy(); - }); - - test('allows references to be sent as a valid value to patch with', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - }).error - ).toBeFalsy(); - }); - - test('does not default references to an array', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some-query', - language: 'kuery', - }).value.references - ).toEqual(undefined); - }); - - test('does not default interval', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - type: 'query', - }).value.interval - ).toEqual(undefined); - }); - - test('does not default max signal', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - }).value.max_signals - ).toEqual(undefined); - }); - - test('references cannot be numbers', () => { - expect( - patchRulesSchema.validate< - Partial> & { references: number[] } - >({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some-query', - language: 'kuery', - references: [5], - }).error.message - ).toEqual( - 'child "references" fails because ["references" at position 0 fails because ["0" must be a string]]' - ); - }); - - test('indexes cannot be numbers', () => { - expect( - patchRulesSchema.validate< - Partial> & { index: number[] } - >({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: [5], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some-query', - language: 'kuery', - }).error.message - ).toEqual( - 'child "index" fails because ["index" at position 0 fails because ["0" must be a string]]' - ); - }); - - test('saved_id is not required when type is saved_query and will validate without it', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - }).error - ).toBeFalsy(); - }); - - test('saved_id validates with saved_query', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - }).error - ).toBeFalsy(); - }); - - test('saved_query type can have filters with it', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - filters: [], - }).error - ).toBeFalsy(); - }); - - test('language validates with kuery', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - }).error - ).toBeFalsy(); - }); - - test('language validates with lucene', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'lucene', - }).error - ).toBeFalsy(); - }); - - test('language does not validate with something made up', () => { - expect( - patchRulesSchema.validate< - Partial & { language: string }> - >({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'something-made-up', - }).error.message - ).toEqual('child "language" fails because ["language" must be one of [kuery, lucene]]'); - }); - - test('max_signals cannot be negative', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: -1, - }).error.message - ).toEqual('child "max_signals" fails because ["max_signals" must be greater than 0]'); - }); - - test('max_signals cannot be zero', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 0, - }).error.message - ).toEqual('child "max_signals" fails because ["max_signals" must be greater than 0]'); - }); - - test('max_signals can be 1', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error - ).toBeFalsy(); - }); - - test('meta can be patched', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - meta: { whateverYouWant: 'anything_at_all' }, - }).error - ).toBeFalsy(); - }); - - test('You cannot patch meta as a string', () => { - expect( - patchRulesSchema.validate & { meta: string }>>( - { - id: 'rule-1', - meta: 'should not work', - } - ).error.message - ).toEqual('child "meta" fails because ["meta" must be an object]'); - }); - - test('filters cannot be a string', () => { - expect( - patchRulesSchema.validate< - Partial & { filters: string }> - >({ - rule_id: 'rule-1', - type: 'query', - filters: 'some string', - }).error.message - ).toEqual('child "filters" fails because ["filters" must be an array]'); - }); - - test('threat is not defaulted to empty array on patch', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).value.threat - ).toBe(undefined); - }); - - test('threat is not defaulted to undefined on patch with empty array', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [], - }).value.threat - ).toMatchObject([]); - }); - - test('threat is valid when updated with all sub-objects', () => { - const expected: ThreatParams[] = [ - { - framework: 'fake', - tactic: { - id: 'fakeId', - name: 'fakeName', - reference: 'fakeRef', - }, - technique: [ - { - id: 'techniqueId', - name: 'techniqueName', - reference: 'techniqueRef', - }, - ], - }, - ]; - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [ - { - framework: 'fake', - tactic: { - id: 'fakeId', - name: 'fakeName', - reference: 'fakeRef', - }, - technique: [ - { - id: 'techniqueId', - name: 'techniqueName', - reference: 'techniqueRef', - }, - ], - }, - ], - }).value.threat - ).toMatchObject(expected); - }); - - test('threat is invalid when updated with missing property framework', () => { - expect( - patchRulesSchema.validate< - Partial> & { - threat: Array>>; - } - >({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [ - { - tactic: { - id: 'fakeId', - name: 'fakeName', - reference: 'fakeRef', - }, - technique: [ - { - id: 'techniqueId', - name: 'techniqueName', - reference: 'techniqueRef', - }, - ], - }, - ], - }).error.message - ).toEqual( - 'child "threat" fails because ["threat" at position 0 fails because [child "framework" fails because ["framework" is required]]]' - ); - }); - - test('threat is invalid when updated with missing tactic sub-object', () => { - expect( - patchRulesSchema.validate< - Partial> & { - threat: Array>>; - } - >({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [ - { - framework: 'fake', - technique: [ - { - id: 'techniqueId', - name: 'techniqueName', - reference: 'techniqueRef', - }, - ], - }, - ], - }).error.message - ).toEqual( - 'child "threat" fails because ["threat" at position 0 fails because [child "tactic" fails because ["tactic" is required]]]' - ); - }); - - test('threat is invalid when updated with missing technique', () => { - expect( - patchRulesSchema.validate< - Partial> & { - threat: Array>>; - } - >({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [ - { - framework: 'fake', - tactic: { - id: 'techniqueId', - name: 'techniqueName', - reference: 'techniqueRef', - }, - }, - ], - }).error.message - ).toEqual( - 'child "threat" fails because ["threat" at position 0 fails because [child "technique" fails because ["technique" is required]]]' - ); - }); - - test('validates with timeline_id and timeline_title', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - timeline_id: 'some-id', - timeline_title: 'some-title', - }).error - ).toBeFalsy(); - }); - - test('You cannot omit timeline_title when timeline_id is present', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - timeline_id: 'some-id', - }).error.message - ).toEqual('child "timeline_title" fails because ["timeline_title" is required]'); - }); - - test('You cannot have a null value for timeline_title when timeline_id is present', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - timeline_id: 'timeline-id', - timeline_title: null, - }).error.message - ).toEqual('child "timeline_title" fails because ["timeline_title" must be a string]'); - }); - - test('You cannot have empty string for timeline_title when timeline_id is present', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - timeline_id: 'some-id', - timeline_title: '', - }).error.message - ).toEqual('child "timeline_title" fails because ["timeline_title" is not allowed to be empty]'); - }); - - test('You cannot have timeline_title with an empty timeline_id', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - timeline_id: '', - timeline_title: 'some-title', - }).error.message - ).toEqual('child "timeline_id" fails because ["timeline_id" is not allowed to be empty]'); - }); - - test('You cannot have timeline_title without timeline_id', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - timeline_title: 'some-title', - }).error.message - ).toEqual('child "timeline_title" fails because ["timeline_title" is not allowed]'); - }); - - test('You cannot set the severity to a value other than low, medium, high, or critical', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'junk', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "severity" fails because ["severity" must be one of [low, medium, high, critical]]' - ); - }); - - describe('note', () => { - test('[rule_id, description, from, to, index, name, severity, interval, type, note] does validate', () => { - expect( - patchRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - note: '# some documentation markdown', - }).error - ).toBeFalsy(); - }); - - test('note can be patched', () => { - expect( - patchRulesSchema.validate>({ - id: 'rule-1', - note: '# new documentation markdown', - }).error - ).toBeFalsy(); - }); - - test('You cannot patch note as an object', () => { - expect( - patchRulesSchema.validate< - Partial & { note: object }> - >({ - id: 'rule-1', - note: { - someProperty: 'something else here', - }, - }).error.message - ).toEqual('child "note" fails because ["note" must be a string]'); - }); - }); - - test('You cannot send in an array of actions that are missing "group"', () => { - expect( - patchRulesSchema.validate< - Partial< - Omit & { - actions: Array>; - } - > - >({ - actions: [{ id: 'id', action_type_id: 'action_type_id', params: {} }], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "group" fails because ["group" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are missing "id"', () => { - expect( - patchRulesSchema.validate< - Partial< - Omit & { - actions: Array>; - } - > - >({ - actions: [{ group: 'group', action_type_id: 'action_type_id', params: {} }], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "id" fails because ["id" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are missing "action_type_id"', () => { - expect( - patchRulesSchema.validate< - Partial< - Omit & { - actions: Array>; - } - > - >({ - actions: [{ group: 'group', id: 'id', params: {} }], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "action_type_id" fails because ["action_type_id" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are missing "params"', () => { - expect( - patchRulesSchema.validate< - Partial< - Omit & { - actions: Array>; - } - > - >({ - actions: [{ group: 'group', id: 'id', action_type_id: 'action_type_id' }], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "params" fails because ["params" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are including "actionTypeId', () => { - expect( - patchRulesSchema.validate< - Partial< - Omit & { - actions: AlertAction[]; - } - > - >({ - actions: [ - { - group: 'group', - id: 'id', - actionTypeId: 'actionTypeId', - params: {}, - }, - ], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "action_type_id" fails because ["action_type_id" is required]]]' - ); - }); - - // TODO: (LIST-FEATURE) We can enable this once we change the schema's to not be global per module but rather functions that can create the schema - // on demand. Since they are per module, we have a an issue where the ENV variables do not take effect. It is better we change all the - // schema's to be function calls to avoid global side effects or just wait until the feature is available. If you want to test this early, - // you can remove the .skip and set your env variable of export ELASTIC_XPACK_SIEM_LISTS_FEATURE=true locally - describe.skip('exceptions_list', () => { - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and exceptions_list] does validate', () => { - expect( - patchRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - exceptions_list: [ - { - field: 'source.ip', - values_operator: 'included', - values_type: 'exists', - }, - { - field: 'host.name', - values_operator: 'excluded', - values_type: 'match', - values: [ - { - name: 'rock01', - }, - ], - and: [ - { - field: 'host.id', - values_operator: 'included', - values_type: 'match_all', - values: [ - { - name: '123', - }, - { - name: '678', - }, - ], - }, - ], - }, - ], - }).error - ).toBeFalsy(); - }); - - test('exceptions_list can be patched', () => { - expect( - patchRulesSchema.validate>({ - rule_id: 'some id', - exceptions_list: [ - { - field: 'source.ip', - values_operator: 'included', - values_type: 'exists', - }, - { - field: 'host.name', - values_operator: 'excluded', - values_type: 'match', - values: [ - { - name: 'rock01', - }, - ], - and: [ - { - field: 'host.id', - values_operator: 'included', - values_type: 'match_all', - values: [ - { - name: '123', - }, - ], - }, - ], - }, - ], - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and empty exceptions_list] does validate', () => { - expect( - patchRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - exceptions_list: [], - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and invalid exceptions_list] does NOT validate', () => { - expect( - patchRulesSchema.validate>>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - exceptions_list: [{ invalid_value: 'invalid value' }], - }).error.message - ).toEqual( - 'child "exceptions_list" fails because ["exceptions_list" at position 0 fails because [child "field" fails because ["field" is required]]]' - ); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and non-existent exceptions_list] does validate with empty exceptions_list', () => { - expect( - patchRulesSchema.validate>>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - }).value.exceptions_list - ).toEqual([]); - }); - }); -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/patch_rules_schema.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/patch_rules_schema.ts deleted file mode 100644 index 503bc64df237c..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/patch_rules_schema.ts +++ /dev/null @@ -1,82 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import Joi from 'joi'; - -/* eslint-disable @typescript-eslint/camelcase */ -import { - actions, - enabled, - description, - false_positives, - filters, - from, - index, - rule_id, - interval, - query, - language, - output_index, - saved_id, - timeline_id, - timeline_title, - meta, - risk_score, - max_signals, - name, - severity, - tags, - to, - type, - threat, - throttle, - references, - note, - id, - version, - lists, - anomaly_threshold, - machine_learning_job_id, -} from './schemas'; -import { hasListsFeature } from '../../feature_flags'; -/* eslint-enable @typescript-eslint/camelcase */ - -export const patchRulesSchema = Joi.object({ - actions, - anomaly_threshold, - description, - enabled, - false_positives, - filters, - from, - rule_id, - id, - index, - interval, - query: query.allow(''), - language, - machine_learning_job_id, - output_index, - saved_id, - timeline_id, - timeline_title, - meta, - risk_score, - max_signals, - name, - severity, - tags, - to, - type, - threat, - throttle, - references, - note: note.allow(''), - version, - - // TODO: (LIST-FEATURE) Remove the hasListsFeatures once this is ready for release - exceptions_list: hasListsFeature() ? lists.default([]) : lists.forbidden().default([]), -}).xor('id', 'rule_id'); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/query_rules_bulk_schema.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/query_rules_bulk_schema.test.ts deleted file mode 100644 index 389c5ff7ea617..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/query_rules_bulk_schema.test.ts +++ /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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { queryRulesBulkSchema } from './query_rules_bulk_schema'; -import { PatchRuleAlertParamsRest } from '../../rules/types'; -import { setFeatureFlagsForTestsOnly, unSetFeatureFlagsForTestsOnly } from '../../feature_flags'; - -// only the basics of testing are here. -// see: query_rules_bulk_schema.test.ts for the bulk of the validation tests -// this just wraps queryRulesSchema in an array -describe('query_rules_bulk_schema', () => { - beforeAll(() => { - setFeatureFlagsForTestsOnly(); - }); - - afterAll(() => { - unSetFeatureFlagsForTestsOnly(); - }); - - test('can take an empty array and validate it', () => { - expect( - queryRulesBulkSchema.validate>>([]).error - ).toBeFalsy(); - }); - - test('both rule_id and id being supplied do not validate', () => { - expect( - queryRulesBulkSchema.validate>>([ - { - rule_id: '1', - id: '1', - }, - ]).error.message - ).toEqual( - '"value" at position 0 fails because ["value" contains a conflict between exclusive peers [id, rule_id]]' - ); - }); - - test('both rule_id and id being supplied do not validate if one array element works but the second does not', () => { - expect( - queryRulesBulkSchema.validate>>([ - { - id: '1', - }, - { - rule_id: '1', - id: '1', - }, - ]).error.message - ).toEqual( - '"value" at position 1 fails because ["value" contains a conflict between exclusive peers [id, rule_id]]' - ); - }); - - test('only id validates', () => { - expect( - queryRulesBulkSchema.validate>>([{ id: '1' }]).error - ).toBeFalsy(); - }); - - test('only id validates with two elements', () => { - expect( - queryRulesBulkSchema.validate>>([ - { id: '1' }, - { id: '2' }, - ]).error - ).toBeFalsy(); - }); - - test('only rule_id validates', () => { - expect( - queryRulesBulkSchema.validate>>([{ rule_id: '1' }]) - .error - ).toBeFalsy(); - }); - - test('only rule_id validates with two elements', () => { - expect( - queryRulesBulkSchema.validate>>([ - { rule_id: '1' }, - { rule_id: '2' }, - ]).error - ).toBeFalsy(); - }); - - test('both id and rule_id validates with two separate elements', () => { - expect( - queryRulesBulkSchema.validate>>([ - { id: '1' }, - { rule_id: '2' }, - ]).error - ).toBeFalsy(); - }); -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/query_rules_bulk_schema.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/query_rules_bulk_schema.ts deleted file mode 100644 index 13ccac282281d..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/query_rules_bulk_schema.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; - * you may not use this file except in compliance with the Elastic License. - */ -import Joi from 'joi'; - -import { queryRulesSchema } from './query_rules_schema'; - -export const queryRulesBulkSchema = Joi.array().items(queryRulesSchema); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/query_rules_schema.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/query_rules_schema.test.ts deleted file mode 100644 index 68be4c627780c..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/query_rules_schema.test.ts +++ /dev/null @@ -1,42 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { queryRulesSchema } from './query_rules_schema'; -import { PatchRuleAlertParamsRest } from '../../rules/types'; -import { setFeatureFlagsForTestsOnly, unSetFeatureFlagsForTestsOnly } from '../../feature_flags'; - -describe('queryRulesSchema', () => { - beforeAll(() => { - setFeatureFlagsForTestsOnly(); - }); - - afterAll(() => { - unSetFeatureFlagsForTestsOnly(); - }); - - test('empty objects do not validate', () => { - expect(queryRulesSchema.validate>({}).error).toBeTruthy(); - }); - - test('both rule_id and id being supplied do not validate', () => { - expect( - queryRulesSchema.validate>({ rule_id: '1', id: '1' }).error - .message - ).toEqual('"value" contains a conflict between exclusive peers [id, rule_id]'); - }); - - test('only id validates', () => { - expect( - queryRulesSchema.validate>({ id: '1' }).error - ).toBeFalsy(); - }); - - test('only rule_id validates', () => { - expect( - queryRulesSchema.validate>({ rule_id: '1' }).error - ).toBeFalsy(); - }); -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/query_signals_index_schema.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/query_signals_index_schema.test.ts deleted file mode 100644 index 4752d1794ff28..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/query_signals_index_schema.test.ts +++ /dev/null @@ -1,75 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { querySignalsSchema } from './query_signals_index_schema'; -import { SignalsQueryRestParams } from '../../signals/types'; -import { setFeatureFlagsForTestsOnly, unSetFeatureFlagsForTestsOnly } from '../../feature_flags'; - -describe('query, aggs, size, _source and track_total_hits on signals index', () => { - beforeAll(() => { - setFeatureFlagsForTestsOnly(); - }); - - afterAll(() => { - unSetFeatureFlagsForTestsOnly(); - }); - - test('query, aggs, size, _source and track_total_hits simultaneously', () => { - expect( - querySignalsSchema.validate>({ - query: {}, - aggs: {}, - size: 1, - track_total_hits: true, - _source: ['field'], - }).error - ).toBeFalsy(); - }); - - test('query only', () => { - expect( - querySignalsSchema.validate>({ - query: {}, - }).error - ).toBeFalsy(); - }); - - test('aggs only', () => { - expect( - querySignalsSchema.validate>({ - aggs: {}, - }).error - ).toBeFalsy(); - }); - - test('size only', () => { - expect( - querySignalsSchema.validate>({ - size: 1, - }).error - ).toBeFalsy(); - }); - - test('track_total_hits only', () => { - expect( - querySignalsSchema.validate>({ - track_total_hits: true, - }).error - ).toBeFalsy(); - }); - - test('_source only', () => { - expect( - querySignalsSchema.validate>({ - _source: ['field'], - }).error - ).toBeFalsy(); - }); - - test('missing query, aggs, size, _source and track_total_hits is invalid', () => { - expect(querySignalsSchema.validate>({}).error).toBeTruthy(); - }); -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/query_signals_index_schema.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/query_signals_index_schema.ts deleted file mode 100644 index 26a32d2e4980b..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/query_signals_index_schema.ts +++ /dev/null @@ -1,15 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import Joi from 'joi'; - -export const querySignalsSchema = Joi.object({ - query: Joi.object(), - aggs: Joi.object(), - size: Joi.number().integer(), - track_total_hits: Joi.boolean(), - _source: Joi.array().items(Joi.string()), -}).min(1); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/schemas.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/schemas.ts deleted file mode 100644 index ae951ea5e33d2..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/schemas.ts +++ /dev/null @@ -1,125 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import Joi from 'joi'; - -/* eslint-disable @typescript-eslint/camelcase */ -export const anomaly_threshold = Joi.number().integer().greater(-1).less(101); -export const description = Joi.string(); -export const enabled = Joi.boolean(); -export const exclude_export_details = Joi.boolean(); -export const false_positives = Joi.array().items(Joi.string()); -export const file_name = Joi.string(); -export const filters = Joi.array(); -export const from = Joi.string(); -export const immutable = Joi.boolean(); -export const rule_id = Joi.string(); -export const id = Joi.string(); -export const index = Joi.array().items(Joi.string()).single(); -export const interval = Joi.string(); -export const query = Joi.string(); -export const language = Joi.string().valid('kuery', 'lucene'); -export const objects = Joi.array().items( - Joi.object({ - rule_id, - }).required() -); -export const output_index = Joi.string(); -export const saved_id = Joi.string(); -export const timeline_id = Joi.string(); -export const timeline_title = Joi.string().when('timeline_id', { - is: Joi.exist(), - then: Joi.required(), - otherwise: Joi.forbidden(), -}); -export const meta = Joi.object(); -export const max_signals = Joi.number().integer().greater(0); -export const name = Joi.string(); -export const risk_score = Joi.number().integer().greater(-1).less(101); -export const severity = Joi.string().valid('low', 'medium', 'high', 'critical'); -export const status = Joi.string().valid('open', 'closed'); -export const to = Joi.string(); -export const type = Joi.string().valid('query', 'saved_query', 'machine_learning'); -export const machine_learning_job_id = Joi.string(); -export const queryFilter = Joi.string(); -export const references = Joi.array().items(Joi.string()).single(); -export const per_page = Joi.number().integer().min(0).default(20); -export const page = Joi.number().integer().min(1).default(1); -export const signal_ids = Joi.array().items(Joi.string()); -export const signal_status_query = Joi.object(); -export const sort_field = Joi.string(); -export const sort_order = Joi.string().valid('asc', 'desc'); -export const tags = Joi.array().items(Joi.string()); -export const fields = Joi.array().items(Joi.string()).single(); -export const threat_framework = Joi.string(); -export const threat_tactic_id = Joi.string(); -export const threat_tactic_name = Joi.string(); -export const threat_tactic_reference = Joi.string(); -export const threat_tactic = Joi.object({ - id: threat_tactic_id.required(), - name: threat_tactic_name.required(), - reference: threat_tactic_reference.required(), -}); -export const threat_technique_id = Joi.string(); -export const threat_technique_name = Joi.string(); -export const threat_technique_reference = Joi.string(); -export const threat_technique = Joi.object({ - id: threat_technique_id.required(), - name: threat_technique_name.required(), - reference: threat_technique_reference.required(), -}); -export const threat_techniques = Joi.array().items(threat_technique.required()); -export const threat = Joi.array().items( - Joi.object({ - framework: threat_framework.required(), - tactic: threat_tactic.required(), - technique: threat_techniques.required(), - }) -); -export const created_at = Joi.string().isoDate().strict(); -export const updated_at = Joi.string().isoDate().strict(); -export const created_by = Joi.string(); -export const updated_by = Joi.string(); -export const version = Joi.number().integer().min(1); -export const action_group = Joi.string(); -export const action_id = Joi.string(); -export const action_action_type_id = Joi.string(); -export const action_params = Joi.object(); -export const action = Joi.object({ - group: action_group.required(), - id: action_id.required(), - action_type_id: action_action_type_id.required(), - params: action_params.required(), -}); -export const actions = Joi.array().items(action); -export const throttle = Joi.string().allow(null); -export const note = Joi.string(); - -// NOTE: Experimental list support not being shipped currently and behind a feature flag -// TODO: (LIST-FEATURE) Remove this comment once we lists have passed testing and is ready for the release -export const list_field = Joi.string(); -export const list_values_operator = Joi.string().valid(['included', 'excluded']); -export const list_values_types = Joi.string().valid(['match', 'match_all', 'list', 'exists']); -export const list_values = Joi.object({ - name: Joi.string().required(), - id: Joi.string(), - description: Joi.string(), - created_at, -}); -export const list = Joi.object({ - field: list_field.required(), - values_operator: list_values_operator.required(), - values_type: list_values_types.required(), - values: Joi.when('values_type', { - is: 'exists', - then: Joi.forbidden(), - otherwise: Joi.array().items(list_values).required(), - }), -}); -export const list_and = Joi.object({ - and: Joi.array().items(list), -}); -export const lists = Joi.array().items(list.concat(list_and)); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/set_signal_status_schema.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/set_signal_status_schema.test.ts deleted file mode 100644 index 953532a6e1c26..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/set_signal_status_schema.test.ts +++ /dev/null @@ -1,75 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { setSignalsStatusSchema } from './set_signal_status_schema'; -import { SignalsStatusRestParams } from '../../signals/types'; -import { setFeatureFlagsForTestsOnly, unSetFeatureFlagsForTestsOnly } from '../../feature_flags'; - -describe('set signal status schema', () => { - beforeAll(() => { - setFeatureFlagsForTestsOnly(); - }); - - afterAll(() => { - unSetFeatureFlagsForTestsOnly(); - }); - - test('signal_ids and status is valid', () => { - expect( - setSignalsStatusSchema.validate>({ - signal_ids: ['somefakeid'], - status: 'open', - }).error - ).toBeFalsy(); - }); - - test('query and status is valid', () => { - expect( - setSignalsStatusSchema.validate>({ - query: {}, - status: 'open', - }).error - ).toBeFalsy(); - }); - - test('signal_ids and missing status is invalid', () => { - expect( - setSignalsStatusSchema.validate>({ - signal_ids: ['somefakeid'], - }).error.message - ).toEqual('child "status" fails because ["status" is required]'); - }); - - test('query and missing status is invalid', () => { - expect( - setSignalsStatusSchema.validate>({ - query: {}, - }).error.message - ).toEqual('child "status" fails because ["status" is required]'); - }); - - test('status is present but query or signal_ids is missing is invalid', () => { - expect( - setSignalsStatusSchema.validate>({ - status: 'closed', - }).error.message - ).toEqual('"value" must contain at least one of [signal_ids, query]'); - }); - - test('signal_ids is present but status has wrong value', () => { - expect( - setSignalsStatusSchema.validate< - Partial< - Omit & { - status: string; - } - > - >({ - status: 'fakeVal', - }).error.message - ).toEqual('child "status" fails because ["status" must be one of [open, closed]]'); - }); -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/set_signal_status_schema.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/set_signal_status_schema.ts deleted file mode 100644 index c8a06619287df..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/set_signal_status_schema.ts +++ /dev/null @@ -1,17 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import Joi from 'joi'; - -/* eslint-disable @typescript-eslint/camelcase */ -import { signal_ids, signal_status_query, status } from './schemas'; -/* eslint-enable @typescript-eslint/camelcase */ - -export const setSignalsStatusSchema = Joi.object({ - signal_ids, - query: signal_status_query, - status: status.required(), -}).xor('signal_ids', 'query'); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/update_rules_bulk_schema.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/update_rules_bulk_schema.test.ts deleted file mode 100644 index d329070eaaa0a..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/update_rules_bulk_schema.test.ts +++ /dev/null @@ -1,91 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { updateRulesBulkSchema } from './update_rules_bulk_schema'; -import { UpdateRuleAlertParamsRest } from '../../rules/types'; -import { setFeatureFlagsForTestsOnly, unSetFeatureFlagsForTestsOnly } from '../../feature_flags'; - -// only the basics of testing are here. -// see: update_rules_schema.test.ts for the bulk of the validation tests -// this just wraps updateRulesSchema in an array -describe('update_rules_bulk_schema', () => { - beforeAll(() => { - setFeatureFlagsForTestsOnly(); - }); - - afterAll(() => { - unSetFeatureFlagsForTestsOnly(); - }); - - test('can take an empty array and validate it', () => { - expect( - updateRulesBulkSchema.validate>>([]).error - ).toBeFalsy(); - }); - - test('made up values do not validate', () => { - expect( - updateRulesBulkSchema.validate<[{ madeUp: string }]>([ - { - madeUp: 'hi', - }, - ]).error - ).toBeTruthy(); - }); - - test('single array of [id] does validate', () => { - expect( - updateRulesBulkSchema.validate>>([ - { - id: 'id-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - query: 'some query', - index: ['index-1'], - interval: '5m', - }, - ]).error - ).toBeFalsy(); - }); - - test('two values of [id] does validate', () => { - expect( - updateRulesBulkSchema.validate>>([ - { - id: 'id-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - query: 'some query', - index: ['index-1'], - interval: '5m', - }, - { - id: 'id-2', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - query: 'some query', - index: ['index-1'], - interval: '5m', - }, - ]).error - ).toBeFalsy(); - }); -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/update_rules_schema.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/update_rules_schema.test.ts deleted file mode 100644 index 8bda16de97775..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/update_rules_schema.test.ts +++ /dev/null @@ -1,1645 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { AlertAction } from '../../../../../../alerts/common'; -import { updateRulesSchema } from './update_rules_schema'; -import { PatchRuleAlertParamsRest } from '../../rules/types'; -import { RuleAlertAction } from '../../../../../common/detection_engine/types'; -import { ThreatParams, RuleAlertParamsRest } from '../../types'; -import { setFeatureFlagsForTestsOnly, unSetFeatureFlagsForTestsOnly } from '../../feature_flags'; - -describe('create rules schema', () => { - beforeAll(() => { - setFeatureFlagsForTestsOnly(); - }); - - afterAll(() => { - unSetFeatureFlagsForTestsOnly(); - }); - - test('empty objects do not validate as they require at least id or rule_id', () => { - expect(updateRulesSchema.validate>({}).error).toBeTruthy(); - }); - - test('made up values do not validate', () => { - expect( - updateRulesSchema.validate>({ - madeUp: 'hi', - }).error - ).toBeTruthy(); - }); - - test('[rule_id] does not validate', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - }).error - ).toBeTruthy(); - }); - - test('[id] and [rule_id] does not validate', () => { - expect( - updateRulesSchema.validate>({ - id: 'id-1', - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - query: 'some query', - index: ['index-1'], - interval: '5m', - }).error.message - ).toEqual('"value" contains a conflict between exclusive peers [id, rule_id]'); - }); - - test('[rule_id, description] does not validate', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from] does not validate', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to] does not validate', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name] does not validate', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity] does not validate', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity, type] does not validate', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity, type, interval] does not validate', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity, type, interval, index] does not validate', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - interval: '5m', - index: ['index-1'], - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, name, severity, type, query, index, interval] does validate', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - name: 'some-name', - severity: 'low', - type: 'query', - query: 'some query', - index: ['index-1'], - interval: '5m', - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, query, language] does not validate', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some query', - language: 'kuery', - }).error - ).toBeTruthy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, query, language, risk_score] does validate', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some query', - language: 'kuery', - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, query, language, risk_score, output_index] does validate', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some query', - language: 'kuery', - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score] does validate', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, output_index] does validate', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - }).error - ).toBeFalsy(); - }); - - test('You can send in an empty array to threat', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [], - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, output_index, threat] does validate', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - threat: [ - { - framework: 'someFramework', - tactic: { - id: 'fakeId', - name: 'fakeName', - reference: 'fakeRef', - }, - technique: [ - { - id: 'techniqueId', - name: 'techniqueName', - reference: 'techniqueRef', - }, - ], - }, - ], - }).error - ).toBeFalsy(); - }); - - test('allows references to be sent as valid', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - }).error - ).toBeFalsy(); - }); - - test('defaults references to an array', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some-query', - language: 'kuery', - }).value.references - ).toEqual([]); - }); - - test('references cannot be numbers', () => { - expect( - updateRulesSchema.validate< - Partial> & { references: number[] } - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some-query', - language: 'kuery', - references: [5], - }).error.message - ).toEqual( - 'child "references" fails because ["references" at position 0 fails because ["0" must be a string]]' - ); - }); - - test('indexes cannot be numbers', () => { - expect( - updateRulesSchema.validate> & { index: number[] }>( - { - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: [5], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - query: 'some-query', - language: 'kuery', - } - ).error.message - ).toEqual( - 'child "index" fails because ["index" at position 0 fails because ["0" must be a string]]' - ); - }); - - test('defaults interval to 5 min', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - type: 'query', - }).value.interval - ).toEqual('5m'); - }); - - test('defaults max signals to 100', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - }).value.max_signals - ).toEqual(100); - }); - - test('saved_id is required when type is saved_query and will not validate without out', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - }).error.message - ).toEqual('child "saved_id" fails because ["saved_id" is required]'); - }); - - test('saved_id is required when type is saved_query and validates with it', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - output_index: '.siem-signals', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - }).error - ).toBeFalsy(); - }); - - test('saved_query type can have filters with it', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - filters: [], - }).error - ).toBeFalsy(); - }); - - test('filters cannot be a string', () => { - expect( - updateRulesSchema.validate< - Partial & { filters: string }> - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'saved_query', - saved_id: 'some id', - filters: 'some string', - }).error.message - ).toEqual('child "filters" fails because ["filters" must be an array]'); - }); - - test('language validates with kuery', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - }).error - ).toBeFalsy(); - }); - - test('language validates with lucene', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - output_index: '.siem-signals', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'lucene', - }).error - ).toBeFalsy(); - }); - - test('language does not validate with something made up', () => { - expect( - updateRulesSchema.validate< - Partial & { language: string }> - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'something-made-up', - }).error.message - ).toEqual('child "language" fails because ["language" must be one of [kuery, lucene]]'); - }); - - test('max_signals cannot be negative', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: -1, - }).error.message - ).toEqual('child "max_signals" fails because ["max_signals" must be greater than 0]'); - }); - - test('max_signals cannot be zero', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 0, - }).error.message - ).toEqual('child "max_signals" fails because ["max_signals" must be greater than 0]'); - }); - - test('max_signals can be 1', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error - ).toBeFalsy(); - }); - - test('You can optionally send in an array of tags', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - tags: ['tag_1', 'tag_2'], - }).error - ).toBeFalsy(); - }); - - test('You cannot send in an array of tags that are numbers', () => { - expect( - updateRulesSchema.validate> & { tags: number[] }>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - tags: [0, 1, 2], - }).error.message - ).toEqual( - 'child "tags" fails because ["tags" at position 0 fails because ["0" must be a string]]' - ); - }); - - test('You cannot send in an array of threat that are missing "framework"', () => { - expect( - updateRulesSchema.validate< - Partial> & { - threat: Array>>; - } - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [ - { - tactic: { - id: 'fakeId', - name: 'fakeName', - reference: 'fakeRef', - }, - technique: [ - { - id: 'techniqueId', - name: 'techniqueName', - reference: 'techniqueRef', - }, - ], - }, - ], - }).error.message - ).toEqual( - 'child "threat" fails because ["threat" at position 0 fails because [child "framework" fails because ["framework" is required]]]' - ); - }); - - test('You cannot send in an array of threat that are missing "tactic"', () => { - expect( - updateRulesSchema.validate< - Partial> & { - threat: Array>>; - } - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [ - { - framework: 'fake', - technique: [ - { - id: 'techniqueId', - name: 'techniqueName', - reference: 'techniqueRef', - }, - ], - }, - ], - }).error.message - ).toEqual( - 'child "threat" fails because ["threat" at position 0 fails because [child "tactic" fails because ["tactic" is required]]]' - ); - }); - - test('You cannot send in an array of threat that are missing "technique"', () => { - expect( - updateRulesSchema.validate< - Partial> & { - threat: Array>>; - } - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - threat: [ - { - framework: 'fake', - tactic: { - id: 'fakeId', - name: 'fakeName', - reference: 'fakeRef', - }, - }, - ], - }).error.message - ).toEqual( - 'child "threat" fails because ["threat" at position 0 fails because [child "technique" fails because ["technique" is required]]]' - ); - }); - - test('You can optionally send in an array of false positives', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - false_positives: ['false_1', 'false_2'], - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error - ).toBeFalsy(); - }); - - test('You cannot send in an array of false positives that are numbers', () => { - expect( - updateRulesSchema.validate< - Partial> & { false_positives: number[] } - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - false_positives: [5, 4], - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error.message - ).toEqual( - 'child "false_positives" fails because ["false_positives" at position 0 fails because ["0" must be a string]]' - ); - }); - - test('You cannot set the immutable when trying to create a rule', () => { - expect( - updateRulesSchema.validate< - Partial> & { immutable: number } - >({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - immutable: 5, - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error.message - ).toEqual('"immutable" is not allowed'); - }); - - test('You cannot set the risk_score to 101', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 101, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error.message - ).toEqual('child "risk_score" fails because ["risk_score" must be less than 101]'); - }); - - test('You cannot set the risk_score to -1', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: -1, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error.message - ).toEqual('child "risk_score" fails because ["risk_score" must be greater than -1]'); - }); - - test('You can set the risk_score to 0', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 0, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error - ).toBeFalsy(); - }); - - test('You can set the risk_score to 100', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 100, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - }).error - ).toBeFalsy(); - }); - - test('You can set meta to any object you want', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - meta: { - somethingMadeUp: { somethingElse: true }, - }, - }).error - ).toBeFalsy(); - }); - - test('You cannot create meta as a string', () => { - expect( - updateRulesSchema.validate & { meta: string }>>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - meta: 'should not work', - }).error.message - ).toEqual('child "meta" fails because ["meta" must be an object]'); - }); - - test('You can omit the query string when filters are present', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - language: 'kuery', - filters: [], - max_signals: 1, - }).error - ).toBeFalsy(); - }); - - test('validates with timeline_id and timeline_title', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - timeline_id: 'timeline-id', - timeline_title: 'timeline-title', - }).error - ).toBeFalsy(); - }); - - test('You cannot omit timeline_title when timeline_id is present', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - timeline_id: 'some_id', - }).error.message - ).toEqual('child "timeline_title" fails because ["timeline_title" is required]'); - }); - - test('You cannot have a null value for timeline_title when timeline_id is present', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - timeline_id: 'some_id', - timeline_title: null, - }).error.message - ).toEqual('child "timeline_title" fails because ["timeline_title" must be a string]'); - }); - - test('You cannot have empty string for timeline_title when timeline_id is present', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - timeline_id: 'some_id', - timeline_title: '', - }).error.message - ).toEqual('child "timeline_title" fails because ["timeline_title" is not allowed to be empty]'); - }); - - test('You cannot have timeline_title with an empty timeline_id', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - timeline_id: '', - timeline_title: 'some-title', - }).error.message - ).toEqual('child "timeline_id" fails because ["timeline_id" is not allowed to be empty]'); - }); - - test('You cannot have timeline_title without timeline_id', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - timeline_title: 'some-title', - }).error.message - ).toEqual('child "timeline_title" fails because ["timeline_title" is not allowed]'); - }); - - test('The default for "from" will be "now-6m"', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).value.from - ).toEqual('now-6m'); - }); - - test('The default for "to" will be "now"', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).value.to - ).toEqual('now'); - }); - - test('You cannot set the severity to a value other than low, medium, high, or critical', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'junk', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "severity" fails because ["severity" must be one of [low, medium, high, critical]]' - ); - }); - - test('The default for "actions" will be an empty array', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).value.actions - ).toEqual([]); - }); - - test('You cannot send in an array of actions that are missing "group"', () => { - expect( - updateRulesSchema.validate< - Partial< - Omit & { - actions: Array>; - } - > - >({ - actions: [{ id: 'id', action_type_id: 'action_type_id', params: {} }], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "group" fails because ["group" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are missing "id"', () => { - expect( - updateRulesSchema.validate< - Partial< - Omit & { - actions: Array>; - } - > - >({ - actions: [{ group: 'group', action_type_id: 'action_type_id', params: {} }], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "id" fails because ["id" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are missing "action_type_id"', () => { - expect( - updateRulesSchema.validate< - Partial< - Omit & { - actions: Array>; - } - > - >({ - actions: [{ group: 'group', id: 'id', params: {} }], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "action_type_id" fails because ["action_type_id" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are missing "params"', () => { - expect( - updateRulesSchema.validate< - Partial< - Omit & { - actions: Array>; - } - > - >({ - actions: [{ group: 'group', id: 'id', action_type_id: 'action_type_id' }], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "params" fails because ["params" is required]]]' - ); - }); - - test('You cannot send in an array of actions that are including "actionTypeId"', () => { - expect( - updateRulesSchema.validate< - Partial< - Omit & { - actions: AlertAction[]; - } - > - >({ - actions: [ - { - group: 'group', - id: 'id', - actionTypeId: 'actionTypeId', - params: {}, - }, - ], - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).error.message - ).toEqual( - 'child "actions" fails because ["actions" at position 0 fails because [child "action_type_id" fails because ["action_type_id" is required]]]' - ); - }); - - test('The default for "throttle" will be null', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - risk_score: 50, - description: 'some description', - name: 'some-name', - severity: 'low', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - version: 1, - }).value.throttle - ).toEqual(null); - }); - - describe('note', () => { - test('You can set note to a string', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - note: '# some documentation title', - }).error - ).toBeFalsy(); - }); - - test('You can set note to an empty string', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - note: '', - }).error - ).toBeFalsy(); - }); - - // Note: If you're looking to remove `note`, omit `note` entirely - test('You cannot set note to null', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - note: null, - }).error.message - ).toEqual('child "note" fails because ["note" must be a string]'); - }); - - test('You cannot set note as an object', () => { - expect( - updateRulesSchema.validate & { note: object }>>({ - rule_id: 'rule-1', - output_index: '.siem-signals', - risk_score: 50, - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - references: ['index-1'], - query: 'some query', - language: 'kuery', - max_signals: 1, - note: { - somethingMadeUp: { somethingElse: true }, - }, - }).error.message - ).toEqual('child "note" fails because ["note" must be a string]'); - }); - }); - - // TODO: (LIST-FEATURE) We can enable this once we change the schema's to not be global per module but rather functions that can create the schema - // on demand. Since they are per module, we have a an issue where the ENV variables do not take effect. It is better we change all the - // schema's to be function calls to avoid global side effects or just wait until the feature is available. If you want to test this early, - // you can remove the .skip and set your env variable of export ELASTIC_XPACK_SIEM_LISTS_FEATURE=true locally - describe.skip('exceptions_list', () => { - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and exceptions_list] does validate', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - exceptions_list: [ - { - field: 'source.ip', - values_operator: 'included', - values_type: 'exists', - }, - { - field: 'host.name', - values_operator: 'excluded', - values_type: 'match', - values: [ - { - name: 'rock01', - }, - ], - and: [ - { - field: 'host.id', - values_operator: 'included', - values_type: 'match_all', - values: [ - { - name: '123', - }, - ], - }, - ], - }, - ], - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and empty exceptions_list] does validate', () => { - expect( - updateRulesSchema.validate>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - exceptions_list: [], - }).error - ).toBeFalsy(); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and invalid exceptions_list] does NOT validate', () => { - expect( - updateRulesSchema.validate>>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - exceptions_list: [{ invalid_value: 'invalid value' }], - }).error.message - ).toEqual( - 'child "exceptions_list" fails because ["exceptions_list" at position 0 fails because [child "field" fails because ["field" is required]]]' - ); - }); - - test('[rule_id, description, from, to, index, name, severity, interval, type, filter, risk_score, note, and non-existent exceptions_list] does validate with empty exceptions_list', () => { - expect( - updateRulesSchema.validate>>({ - rule_id: 'rule-1', - description: 'some description', - from: 'now-5m', - to: 'now', - index: ['index-1'], - name: 'some-name', - severity: 'low', - interval: '5m', - type: 'query', - risk_score: 50, - note: '# some markdown', - }).value.exceptions_list - ).toEqual([]); - }); - }); -}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/update_rules_schema.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/update_rules_schema.ts deleted file mode 100644 index b1b37801b644f..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/schemas/update_rules_schema.ts +++ /dev/null @@ -1,111 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import Joi from 'joi'; - -/* eslint-disable @typescript-eslint/camelcase */ -import { - actions, - enabled, - description, - false_positives, - filters, - from, - index, - rule_id, - interval, - query, - language, - output_index, - saved_id, - timeline_id, - timeline_title, - meta, - risk_score, - max_signals, - name, - severity, - tags, - to, - type, - threat, - throttle, - references, - id, - note, - version, - lists, - anomaly_threshold, - machine_learning_job_id, -} from './schemas'; -/* eslint-enable @typescript-eslint/camelcase */ - -import { DEFAULT_MAX_SIGNALS } from '../../../../../common/constants'; -import { hasListsFeature } from '../../feature_flags'; - -/** - * This almost identical to the create_rules_schema except for a few details. - * - The version will not be defaulted to a 1. If it is not given then its default will become the previous version auto-incremented - * This does break idempotency slightly as calls repeatedly without it will increment the number. If the version number is passed in - * this will update the rule's version number. - * - id is on here because you can pass in an id to update using it instead of rule_id. - */ -export const updateRulesSchema = Joi.object({ - actions: actions.default([]), - anomaly_threshold: anomaly_threshold.when('type', { - is: 'machine_learning', - then: Joi.required(), - otherwise: Joi.forbidden(), - }), - description: description.required(), - enabled: enabled.default(true), - id, - false_positives: false_positives.default([]), - filters, - from: from.default('now-6m'), - rule_id, - index, - interval: interval.default('5m'), - query: query.when('type', { - is: 'machine_learning', - then: Joi.forbidden(), - otherwise: query.allow('').default(''), - }), - language: language.when('type', { - is: 'machine_learning', - then: Joi.forbidden(), - otherwise: language.default('kuery'), - }), - machine_learning_job_id: machine_learning_job_id.when('type', { - is: 'machine_learning', - then: Joi.required(), - otherwise: Joi.forbidden(), - }), - output_index, - saved_id: saved_id.when('type', { - is: 'saved_query', - then: Joi.required(), - otherwise: Joi.forbidden(), - }), - timeline_id, - timeline_title, - meta, - risk_score: risk_score.required(), - max_signals: max_signals.default(DEFAULT_MAX_SIGNALS), - name: name.required(), - severity: severity.required(), - tags: tags.default([]), - to: to.default('now'), - type: type.required(), - threat: threat.default([]), - throttle: throttle.default(null), - references: references.default([]), - note: note.allow(''), - version, - - // TODO: (LIST-FEATURE) Remove the hasListsFeatures once this is ready for release - exceptions_list: hasListsFeature() ? lists.default([]) : lists.forbidden().default([]), -}).xor('id', 'rule_id'); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals.test.ts index a8819bbd7432c..f3109a911203d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals.test.ts @@ -101,11 +101,12 @@ describe('set signal status', () => { path: DETECTION_ENGINE_SIGNALS_STATUS_URL, body: setStatusSignalMissingIdsAndQueryPayload(), }); - const result = server.validate(request); - - expect(result.badRequest).toHaveBeenCalledWith( - '"value" must contain at least one of [signal_ids, query]' - ); + const response = await server.inject(request, context); + expect(response.status).toEqual(400); + expect(response.body).toEqual({ + message: ['either "signal_ids" or "query" must be set'], + status_code: 400, + }); }); test('rejects if signal_ids but no status', async () => { @@ -118,7 +119,7 @@ describe('set signal status', () => { const result = server.validate(request); expect(result.badRequest).toHaveBeenCalledWith( - 'child "status" fails because ["status" is required]' + 'Invalid value "undefined" supplied to "status"' ); }); @@ -132,7 +133,7 @@ describe('set signal status', () => { const result = server.validate(request); expect(result.badRequest).toHaveBeenCalledWith( - 'child "status" fails because ["status" is required]' + 'Invalid value "undefined" supplied to "status"' ); }); @@ -150,7 +151,7 @@ describe('set signal status', () => { const result = server.validate(request); expect(result.badRequest).toHaveBeenCalledWith( - 'child "status" fails because ["status" is required]' + 'Invalid value "undefined" supplied to "status"' ); }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals_route.ts index e3e19d83d8f0d..18c3440ab93e1 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/open_close_signals_route.ts @@ -4,18 +4,24 @@ * you may not use this file except in compliance with the Elastic License. */ +import { setSignalStatusValidateTypeDependents } from '../../../../../common/detection_engine/schemas/request/set_signal_status_type_dependents'; +import { + SetSignalsStatusSchemaDecoded, + setSignalsStatusSchema, +} from '../../../../../common/detection_engine/schemas/request/set_signal_status_schema'; import { IRouter } from '../../../../../../../../src/core/server'; import { DETECTION_ENGINE_SIGNALS_STATUS_URL } from '../../../../../common/constants'; -import { SignalsStatusRestParams } from '../../signals/types'; -import { setSignalsStatusSchema } from '../schemas/set_signal_status_schema'; -import { transformError, buildRouteValidation, buildSiemResponse } from '../utils'; +import { transformError, buildSiemResponse } from '../utils'; +import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; export const setSignalsStatusRoute = (router: IRouter) => { router.post( { path: DETECTION_ENGINE_SIGNALS_STATUS_URL, validate: { - body: buildRouteValidation(setSignalsStatusSchema), + body: buildRouteValidation( + setSignalsStatusSchema + ), }, options: { tags: ['access:securitySolution'], @@ -26,6 +32,10 @@ export const setSignalsStatusRoute = (router: IRouter) => { const clusterClient = context.core.elasticsearch.legacy.client; const siemClient = context.securitySolution?.getAppClient(); const siemResponse = buildSiemResponse(response); + const validationErrors = setSignalStatusValidateTypeDependents(request.body); + if (validationErrors.length) { + return siemResponse.error({ statusCode: 400, body: validationErrors }); + } if (!siemClient) { return siemResponse.error({ statusCode: 404 }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.test.ts index 8d7b171a8537b..f0863164a3f23 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.test.ts @@ -128,9 +128,12 @@ describe('query for signal', () => { path: DETECTION_ENGINE_QUERY_SIGNALS_URL, body: {}, }); - const result = server.validate(request); - - expect(result.badRequest).toHaveBeenCalledWith('"value" must have at least 1 children'); + const response = await server.inject(request, context); + expect(response.status).toEqual(400); + expect(response.body).toEqual({ + message: '"value" must have at least 1 children', + status_code: 400, + }); }); }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.ts index a93f4ebff58d4..5f62ff426ecd0 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/signals/query_signals_route.ts @@ -6,16 +6,22 @@ import { IRouter } from '../../../../../../../../src/core/server'; import { DETECTION_ENGINE_QUERY_SIGNALS_URL } from '../../../../../common/constants'; -import { SignalsQueryRestParams } from '../../signals/types'; -import { querySignalsSchema } from '../schemas/query_signals_index_schema'; -import { transformError, buildRouteValidation, buildSiemResponse } from '../utils'; +import { transformError, buildSiemResponse } from '../utils'; +import { buildRouteValidation } from '../../../../utils/build_validation/route_validation'; + +import { + querySignalsSchema, + QuerySignalsSchemaDecoded, +} from '../../../../../common/detection_engine/schemas/request/query_signals_index_schema'; export const querySignalsRoute = (router: IRouter) => { router.post( { path: DETECTION_ENGINE_QUERY_SIGNALS_URL, validate: { - body: buildRouteValidation(querySignalsSchema), + body: buildRouteValidation( + querySignalsSchema + ), }, options: { tags: ['access:securitySolution'], @@ -23,9 +29,22 @@ export const querySignalsRoute = (router: IRouter) => { }, async (context, request, response) => { const { query, aggs, _source, track_total_hits, size } = request.body; + const siemResponse = buildSiemResponse(response); + if ( + query == null && + aggs == null && + _source == null && + // eslint-disable-next-line @typescript-eslint/camelcase + track_total_hits == null && + size == null + ) { + return siemResponse.error({ + statusCode: 400, + body: '"value" must have at least 1 children', + }); + } const clusterClient = context.core.elasticsearch.legacy.client; const siemClient = context.securitySolution!.getAppClient(); - const siemResponse = buildSiemResponse(response); try { const result = await clusterClient.callAsCurrentUser('search', { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.mock.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.mock.ts new file mode 100644 index 0000000000000..d00bffb96ad05 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.mock.ts @@ -0,0 +1,78 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { CreateRulesOptions } from './types'; +import { alertsClientMock } from '../../../../../alerts/server/mocks'; + +export const getCreateRulesOptionsMock = (): CreateRulesOptions => ({ + alertsClient: alertsClientMock.create(), + anomalyThreshold: undefined, + description: 'some description', + enabled: true, + falsePositives: ['false positive 1', 'false positive 2'], + from: 'now-6m', + query: 'user.name: root or user.name: admin', + language: 'kuery', + savedId: 'savedId-123', + timelineId: 'timelineid-123', + timelineTitle: 'timeline-title-123', + meta: {}, + machineLearningJobId: undefined, + filters: [], + ruleId: 'rule-1', + immutable: false, + index: ['index-123'], + interval: '5m', + maxSignals: 100, + riskScore: 80, + outputIndex: 'output-1', + name: 'Query with a rule id', + severity: 'high', + tags: [], + threat: [], + to: 'now', + type: 'query', + references: ['http://www.example.com'], + note: '# sample markdown', + version: 1, + exceptionsList: [], + actions: [], +}); + +export const getCreateMlRulesOptionsMock = (): CreateRulesOptions => ({ + alertsClient: alertsClientMock.create(), + anomalyThreshold: 55, + description: 'some description', + enabled: true, + falsePositives: ['false positive 1', 'false positive 2'], + from: 'now-6m', + query: undefined, + language: undefined, + savedId: 'savedId-123', + timelineId: 'timelineid-123', + timelineTitle: 'timeline-title-123', + meta: {}, + machineLearningJobId: 'new_job_id', + filters: [], + ruleId: 'rule-1', + immutable: false, + index: ['index-123'], + interval: '5m', + maxSignals: 100, + riskScore: 80, + outputIndex: 'output-1', + name: 'Machine Learning Job', + severity: 'high', + tags: [], + threat: [], + to: 'now', + type: 'machine_learning', + references: ['http://www.example.com'], + note: '# sample markdown', + version: 1, + exceptionsList: [], + actions: [], +}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.test.ts index f086166d0685e..b58d64c86142d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.test.ts @@ -4,36 +4,14 @@ * you may not use this file except in compliance with the Elastic License. */ -import { alertsClientMock } from '../../../../../alerts/server/mocks'; -import { getMlResult } from '../routes/__mocks__/request_responses'; import { createRules } from './create_rules'; +import { getCreateMlRulesOptionsMock } from './create_rules.mock'; describe('createRules', () => { - let alertsClient: ReturnType; - - beforeEach(() => { - alertsClient = alertsClientMock.create(); - }); - it('calls the alertsClient with ML params', async () => { - const params = { - ...getMlResult().params, - anomalyThreshold: 55, - machineLearningJobId: 'new_job_id', - }; - - await createRules({ - alertsClient, - ...params, - ruleId: 'new-rule-id', - enabled: true, - interval: '', - name: '', - tags: [], - actions: [], - }); - - expect(alertsClient.create).toHaveBeenCalledWith( + const ruleOptions = getCreateMlRulesOptionsMock(); + await createRules(ruleOptions); + expect(ruleOptions.alertsClient.create).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ params: expect.objectContaining({ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.ts index 67e066c6670fb..83e9b0de16f06 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.ts @@ -7,7 +7,7 @@ import { transformRuleToAlertAction } from '../../../../common/detection_engine/transform_actions'; import { Alert } from '../../../../../alerts/common'; import { APP_ID, SIGNALS_ID } from '../../../../common/constants'; -import { CreateRuleParams } from './types'; +import { CreateRulesOptions } from './types'; import { addTags } from './add_tags'; import { hasListsFeature } from '../feature_flags'; @@ -42,11 +42,11 @@ export const createRules = async ({ references, note, version, - exceptions_list, + exceptionsList, actions, -}: CreateRuleParams): Promise => { +}: CreateRulesOptions): Promise => { // TODO: Remove this and use regular exceptions_list once the feature is stable for a release - const exceptionsListParam = hasListsFeature() ? { exceptions_list } : {}; + const exceptionsListParam = hasListsFeature() ? { exceptionsList } : {}; return alertsClient.create({ data: { name, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules_stream_from_ndjson.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules_stream_from_ndjson.test.ts index 8044692ab90b1..73d3c65774b3d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules_stream_from_ndjson.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules_stream_from_ndjson.test.ts @@ -6,12 +6,12 @@ import { Readable } from 'stream'; import { createRulesStreamFromNdJson } from './create_rules_stream_from_ndjson'; import { createPromiseFromStreams } from 'src/legacy/utils/streams'; -import { ImportRuleAlertRest } from '../types'; import { BadRequestError } from '../errors/bad_request_error'; +import { ImportRulesSchemaDecoded } from '../../../../common/detection_engine/schemas/request/import_rules_schema'; -type PromiseFromStreams = ImportRuleAlertRest | Error; +type PromiseFromStreams = ImportRulesSchemaDecoded | Error; -export const getOutputSample = (): Partial => ({ +export const getOutputSample = (): Partial => ({ rule_id: 'rule-1', output_index: '.siem-signals', risk_score: 50, @@ -25,7 +25,7 @@ export const getOutputSample = (): Partial => ({ type: 'query', }); -export const getSampleAsNdjson = (sample: Partial): string => { +export const getSampleAsNdjson = (sample: Partial): string => { return `${JSON.stringify(sample)}\n`; }; @@ -64,8 +64,6 @@ describe('create_rules_stream_from_ndjson', () => { enabled: true, false_positives: [], immutable: false, - query: '', - language: 'kuery', exceptions_list: [], max_signals: 100, tags: [], @@ -90,8 +88,6 @@ describe('create_rules_stream_from_ndjson', () => { enabled: true, false_positives: [], immutable: false, - query: '', - language: 'kuery', exceptions_list: [], max_signals: 100, tags: [], @@ -154,8 +150,6 @@ describe('create_rules_stream_from_ndjson', () => { enabled: true, false_positives: [], immutable: false, - query: '', - language: 'kuery', max_signals: 100, tags: [], exceptions_list: [], @@ -180,8 +174,6 @@ describe('create_rules_stream_from_ndjson', () => { enabled: true, false_positives: [], immutable: false, - query: '', - language: 'kuery', max_signals: 100, exceptions_list: [], tags: [], @@ -227,8 +219,6 @@ describe('create_rules_stream_from_ndjson', () => { enabled: true, false_positives: [], immutable: false, - query: '', - language: 'kuery', max_signals: 100, exceptions_list: [], tags: [], @@ -253,8 +243,6 @@ describe('create_rules_stream_from_ndjson', () => { enabled: true, false_positives: [], immutable: false, - query: '', - language: 'kuery', max_signals: 100, exceptions_list: [], tags: [], @@ -300,8 +288,6 @@ describe('create_rules_stream_from_ndjson', () => { enabled: true, false_positives: [], immutable: false, - query: '', - language: 'kuery', max_signals: 100, exceptions_list: [], tags: [], @@ -327,8 +313,6 @@ describe('create_rules_stream_from_ndjson', () => { enabled: true, false_positives: [], immutable: false, - query: '', - language: 'kuery', max_signals: 100, exceptions_list: [], tags: [], @@ -373,8 +357,6 @@ describe('create_rules_stream_from_ndjson', () => { enabled: true, false_positives: [], immutable: false, - query: '', - language: 'kuery', max_signals: 100, exceptions_list: [], tags: [], @@ -383,8 +365,9 @@ describe('create_rules_stream_from_ndjson', () => { references: [], version: 1, }); + // TODO: Change the formatter to output something better than [object Object] expect(resultOrError[1].message).toEqual( - 'child "description" fails because ["description" is required]' + '[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]' ); expect(resultOrError[2]).toEqual({ actions: [], @@ -402,8 +385,6 @@ describe('create_rules_stream_from_ndjson', () => { enabled: true, false_positives: [], immutable: false, - query: '', - language: 'kuery', max_signals: 100, exceptions_list: [], tags: [], diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules_stream_from_ndjson.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules_stream_from_ndjson.ts index 034813b8d100d..932a4ef9eed92 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules_stream_from_ndjson.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules_stream_from_ndjson.ts @@ -4,13 +4,21 @@ * you may not use this file except in compliance with the Elastic License. */ import { Transform } from 'stream'; -import { ImportRuleAlertRest } from '../types'; +import * as t from 'io-ts'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { fold } from 'fp-ts/lib/Either'; +import { importRuleValidateTypeDependents } from '../../../../common/detection_engine/schemas/request/import_rules_type_dependents'; +import { exactCheck } from '../../../../common/exact_check'; +import { + importRulesSchema, + ImportRulesSchema, + ImportRulesSchemaDecoded, +} from '../../../../common/detection_engine/schemas/request/import_rules_schema'; import { createSplitStream, createMapStream, createConcatStream, } from '../../../../../../../src/legacy/utils/streams'; -import { importRulesSchema } from '../routes/schemas/import_rules_schema'; import { BadRequestError } from '../errors/bad_request_error'; import { parseNdjsonStrings, @@ -19,14 +27,22 @@ import { } from '../../../utils/read_stream/create_stream_from_ndjson'; export const validateRules = (): Transform => { - return createMapStream((obj: ImportRuleAlertRest) => { + return createMapStream((obj: ImportRulesSchema) => { if (!(obj instanceof Error)) { - const validated = importRulesSchema.validate(obj); - if (validated.error != null) { - return new BadRequestError(validated.error.message); - } else { - return validated.value; - } + const decoded = importRulesSchema.decode(obj); + const checked = exactCheck(obj, decoded); + const onLeft = (errors: t.Errors): BadRequestError | ImportRulesSchemaDecoded => { + return new BadRequestError(errors.join()); + }; + const onRight = (schema: ImportRulesSchema): BadRequestError | ImportRulesSchemaDecoded => { + const validationErrors = importRuleValidateTypeDependents(schema); + if (validationErrors.length) { + return new BadRequestError(validationErrors.join()); + } else { + return schema as ImportRulesSchemaDecoded; + } + }; + return pipe(checked, fold(onLeft, onRight)); } else { return obj; } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/delete_rules.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/delete_rules.test.ts index f96a9e38d6a6c..ddc1b509eaf02 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/delete_rules.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/delete_rules.test.ts @@ -49,7 +49,7 @@ describe('deleteRules', () => { expect(result).toEqual({ id: notificationId }); }); - it('should call alertsClient.delete if ruleId was null', async () => { + it('should call alertsClient.delete if ruleId was undefined', async () => { (readRules as jest.Mock).mockResolvedValue({ id: null, }); @@ -57,7 +57,7 @@ describe('deleteRules', () => { const result = await deleteRules({ alertsClient, id: notificationId, - ruleId: null, + ruleId: undefined, }); expect(alertsClient.delete).toHaveBeenCalledWith( @@ -68,7 +68,7 @@ describe('deleteRules', () => { expect(result).toEqual({ id: null }); }); - it('should return null if alertsClient.delete rejects with 404 if ruleId was null', async () => { + it('should return null if alertsClient.delete rejects with 404 if ruleId was undefined', async () => { (readRules as jest.Mock).mockResolvedValue({ id: null, }); @@ -82,7 +82,7 @@ describe('deleteRules', () => { const result = await deleteRules({ alertsClient, id: notificationId, - ruleId: null, + ruleId: undefined, }); expect(alertsClient.delete).toHaveBeenCalledWith( @@ -93,7 +93,7 @@ describe('deleteRules', () => { expect(result).toEqual(null); }); - it('should return error object if alertsClient.delete rejects with status different than 404 and if ruleId was null', async () => { + it('should return error object if alertsClient.delete rejects with status different than 404 and if ruleId was undefined', async () => { (readRules as jest.Mock).mockResolvedValue({ id: null, }); @@ -111,7 +111,7 @@ describe('deleteRules', () => { await deleteRules({ alertsClient, id: notificationId, - ruleId: null, + ruleId: undefined, }); } catch (error) { errorResult = error; @@ -125,7 +125,7 @@ describe('deleteRules', () => { expect(errorResult).toEqual(errorObject); }); - it('should return null if ruleId and id was null', async () => { + it('should return null if ruleId and id was undefined', async () => { (readRules as jest.Mock).mockResolvedValue({ id: null, }); @@ -133,7 +133,7 @@ describe('deleteRules', () => { const result = await deleteRules({ alertsClient, id: undefined, - ruleId: null, + ruleId: undefined, }); expect(result).toEqual(null); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/delete_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/delete_rules.ts index 92a80bc50afc6..cde95a4967d86 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/delete_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/delete_rules.ts @@ -5,9 +5,9 @@ */ import { readRules } from './read_rules'; -import { DeleteRuleParams } from './types'; +import { DeleteRuleOptions } from './types'; -export const deleteRules = async ({ alertsClient, id, ruleId }: DeleteRuleParams) => { +export const deleteRules = async ({ alertsClient, id, ruleId }: DeleteRuleOptions) => { const rule = await readRules({ alertsClient, id, ruleId }); if (rule == null) { return null; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/find_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/find_rules.ts index c634f07387825..18b851c440e20 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/find_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/find_rules.ts @@ -6,7 +6,7 @@ import { FindResult } from '../../../../../alerts/server'; import { SIGNALS_ID } from '../../../../common/constants'; -import { FindRuleParams } from './types'; +import { FindRuleOptions } from './types'; export const getFilter = (filter: string | null | undefined) => { if (filter == null) { @@ -24,7 +24,7 @@ export const findRules = async ({ filter, sortField, sortOrder, -}: FindRuleParams): Promise => { +}: FindRuleOptions): Promise => { return alertsClient.find({ options: { fields, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_existing_prepackaged_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_existing_prepackaged_rules.ts index a3119131a0037..b7ff1cb698e17 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_existing_prepackaged_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_existing_prepackaged_rules.ts @@ -34,6 +34,7 @@ export const getRulesCount = async ({ page: 1, sortField: 'createdAt', sortOrder: 'desc', + fields: undefined, }); return firstRule.total; }; @@ -53,6 +54,7 @@ export const getRules = async ({ page: 1, sortField: 'createdAt', sortOrder: 'desc', + fields: undefined, }); if (isAlertTypes(rules.data)) { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_by_object_ids.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_by_object_ids.ts index 38cf8008f65c8..1a965842348ac 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_by_object_ids.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_export_by_object_ids.ts @@ -51,7 +51,7 @@ export const getRulesFromObjects = async ( objects.reduce>>((accumPromise, object) => { const exportWorkerPromise = new Promise(async (resolve) => { try { - const rule = await readRules({ alertsClient, ruleId: object.rule_id }); + const rule = await readRules({ alertsClient, ruleId: object.rule_id, id: undefined }); if (rule != null && isAlertType(rule) && rule.params.immutable !== true) { const transformedRule = transformAlertToRule(rule); resolve({ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_prepackaged_rules.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_prepackaged_rules.test.ts index b2e1ed794043a..597a74f6efbbd 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_prepackaged_rules.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_prepackaged_rules.test.ts @@ -5,8 +5,8 @@ */ import { getPrepackagedRules } from './get_prepackaged_rules'; -import { PrepackagedRules } from '../types'; import { isEmpty } from 'lodash/fp'; +import { AddPrepackagedRulesSchemaDecoded } from '../../../../common/detection_engine/schemas/request/add_prepackaged_rules_schema'; describe('get_existing_prepackaged_rules', () => { test('should not throw any errors with the existing checked in pre-packaged rules', () => { @@ -14,9 +14,9 @@ describe('get_existing_prepackaged_rules', () => { }); test('no rule should have the same rule_id as another rule_id', () => { - const prePacakgedRules = getPrepackagedRules(); - let existingRuleIds: PrepackagedRules[] = []; - prePacakgedRules.forEach((rule) => { + const prePackagedRules = getPrepackagedRules(); + let existingRuleIds: AddPrepackagedRulesSchemaDecoded[] = []; + prePackagedRules.forEach((rule) => { const foundDuplicate = existingRuleIds.reduce((accum, existingRule) => { if (existingRule.rule_id === rule.rule_id) { return `Found duplicate rule_id of ${rule.rule_id} between these two rule names of "${rule.name}" and "${existingRule.name}"`; @@ -33,14 +33,16 @@ describe('get_existing_prepackaged_rules', () => { }); test('should throw an exception if a pre-packaged rule is not valid', () => { + // TODO: Improve the error formatter around [object Object] expect(() => getPrepackagedRules([{ not_valid_made_up_key: true }])).toThrow( - 'name: "(rule name unknown)", rule_id: "(rule rule_id unknown)" within the folder rules/prepackaged_rules is not a valid detection engine rule. Expect the system to not work with pre-packaged rules until this rule is fixed or the file is removed. Error is: child "description" fails because ["description" is required], Full rule contents are:\n{\n "not_valid_made_up_key": true\n}' + 'name: "(rule name unknown)", rule_id: "(rule rule_id unknown)" within the folder rules/prepackaged_rules is not a valid detection engine rule. Expect the system to not work with pre-packaged rules until this rule is fixed or the file is removed. Error is: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object], Full rule contents are:\n{\n "not_valid_made_up_key": true\n}' ); }); test('should throw an exception with a message having rule_id and name in it', () => { + // TODO: Improve the error formatter around [object Object] expect(() => getPrepackagedRules([{ name: 'rule name', rule_id: 'id-123' }])).toThrow( - 'name: "rule name", rule_id: "id-123" within the folder rules/prepackaged_rules is not a valid detection engine rule. Expect the system to not work with pre-packaged rules until this rule is fixed or the file is removed. Error is: child "description" fails because ["description" is required]' + 'name: "rule name", rule_id: "id-123" within the folder rules/prepackaged_rules is not a valid detection engine rule. Expect the system to not work with pre-packaged rules until this rule is fixed or the file is removed. Error is: [object Object],[object Object],[object Object],[object Object],[object Object], Full rule contents are:\n{\n "name": "rule name",\n "rule_id": "id-123"\n}' ); }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_prepackaged_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_prepackaged_rules.ts index d150db1875065..d2af93c329636 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_prepackaged_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_prepackaged_rules.ts @@ -4,8 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ -import { PrepackagedRules } from '../types'; -import { addPrepackagedRulesSchema } from '../routes/schemas/add_prepackaged_rules_schema'; +import * as t from 'io-ts'; +import { fold } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { exactCheck } from '../../../../common/exact_check'; +import { + addPrepackagedRulesSchema, + AddPrepackagedRulesSchema, + AddPrepackagedRulesSchemaDecoded, +} from '../../../../common/detection_engine/schemas/request/add_prepackaged_rules_schema'; import { BadRequestError } from '../errors/bad_request_error'; import { rawRules } from './prepackaged_rules'; @@ -14,26 +21,34 @@ import { rawRules } from './prepackaged_rules'; * that they are adding incorrect schema rules. Also this will auto-flush in all the default * aspects such as default interval of 5 minutes, default arrays, etc... */ -export const validateAllPrepackagedRules = (rules: PrepackagedRules[]): PrepackagedRules[] => { +export const validateAllPrepackagedRules = ( + rules: AddPrepackagedRulesSchema[] +): AddPrepackagedRulesSchemaDecoded[] => { return rules.map((rule) => { - const validatedRule = addPrepackagedRulesSchema.validate(rule); - if (validatedRule.error != null) { + const decoded = addPrepackagedRulesSchema.decode(rule); + const checked = exactCheck(rule, decoded); + + const onLeft = (errors: t.Errors): AddPrepackagedRulesSchemaDecoded => { const ruleName = rule.name ? rule.name : '(rule name unknown)'; const ruleId = rule.rule_id ? rule.rule_id : '(rule rule_id unknown)'; throw new BadRequestError( `name: "${ruleName}", rule_id: "${ruleId}" within the folder rules/prepackaged_rules ` + `is not a valid detection engine rule. Expect the system ` + `to not work with pre-packaged rules until this rule is fixed ` + - `or the file is removed. Error is: ${ - validatedRule.error.message - }, Full rule contents are:\n${JSON.stringify(rule, null, 2)}` + `or the file is removed. Error is: ${errors.join()}, Full rule contents are:\n${JSON.stringify( + rule, + null, + 2 + )}` ); - } else { - return validatedRule.value; - } + }; + + const onRight = (schema: AddPrepackagedRulesSchema): AddPrepackagedRulesSchemaDecoded => { + return schema as AddPrepackagedRulesSchemaDecoded; + }; + return pipe(checked, fold(onLeft, onRight)); }); }; -export const getPrepackagedRules = (rules = rawRules): PrepackagedRules[] => { - return validateAllPrepackagedRules(rules); -}; +export const getPrepackagedRules = (rules = rawRules): AddPrepackagedRulesSchemaDecoded[] => + validateAllPrepackagedRules(rules); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_rules_to_install.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_rules_to_install.test.ts index ee76bf2ef15b8..04e3ecc4e0ac0 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_rules_to_install.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_rules_to_install.test.ts @@ -5,7 +5,8 @@ */ import { getRulesToInstall } from './get_rules_to_install'; -import { getResult, mockPrepackagedRule } from '../routes/__mocks__/request_responses'; +import { getResult } from '../routes/__mocks__/request_responses'; +import { getAddPrepackagedRulesSchemaDecodedMock } from '../../../../common/detection_engine/schemas/request/add_prepackaged_rules_schema.mock'; describe('get_rules_to_install', () => { test('should return empty array if both rule sets are empty', () => { @@ -14,7 +15,7 @@ describe('get_rules_to_install', () => { }); test('should return empty array if the two rule ids match', () => { - const ruleFromFileSystem = mockPrepackagedRule(); + const ruleFromFileSystem = getAddPrepackagedRulesSchemaDecodedMock(); ruleFromFileSystem.rule_id = 'rule-1'; const installedRule = getResult(); @@ -24,7 +25,7 @@ describe('get_rules_to_install', () => { }); test('should return the rule to install if the id of the two rules do not match', () => { - const ruleFromFileSystem = mockPrepackagedRule(); + const ruleFromFileSystem = getAddPrepackagedRulesSchemaDecodedMock(); ruleFromFileSystem.rule_id = 'rule-1'; const installedRule = getResult(); @@ -34,10 +35,10 @@ describe('get_rules_to_install', () => { }); test('should return two rules to install if both the ids of the two rules do not match', () => { - const ruleFromFileSystem1 = mockPrepackagedRule(); + const ruleFromFileSystem1 = getAddPrepackagedRulesSchemaDecodedMock(); ruleFromFileSystem1.rule_id = 'rule-1'; - const ruleFromFileSystem2 = mockPrepackagedRule(); + const ruleFromFileSystem2 = getAddPrepackagedRulesSchemaDecodedMock(); ruleFromFileSystem2.rule_id = 'rule-2'; const installedRule = getResult(); @@ -47,13 +48,13 @@ describe('get_rules_to_install', () => { }); test('should return two rules of three to install if both the ids of the two rules do not match but the third does', () => { - const ruleFromFileSystem1 = mockPrepackagedRule(); + const ruleFromFileSystem1 = getAddPrepackagedRulesSchemaDecodedMock(); ruleFromFileSystem1.rule_id = 'rule-1'; - const ruleFromFileSystem2 = mockPrepackagedRule(); + const ruleFromFileSystem2 = getAddPrepackagedRulesSchemaDecodedMock(); ruleFromFileSystem2.rule_id = 'rule-2'; - const ruleFromFileSystem3 = mockPrepackagedRule(); + const ruleFromFileSystem3 = getAddPrepackagedRulesSchemaDecodedMock(); ruleFromFileSystem3.rule_id = 'rule-3'; const installedRule = getResult(); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_rules_to_install.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_rules_to_install.ts index 4b56bc104b817..69e0255e9b55b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_rules_to_install.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_rules_to_install.ts @@ -4,13 +4,13 @@ * you may not use this file except in compliance with the Elastic License. */ -import { PrepackagedRules } from '../types'; +import { AddPrepackagedRulesSchemaDecoded } from '../../../../common/detection_engine/schemas/request/add_prepackaged_rules_schema'; import { RuleAlertType } from './types'; export const getRulesToInstall = ( - rulesFromFileSystem: PrepackagedRules[], + rulesFromFileSystem: AddPrepackagedRulesSchemaDecoded[], installedRules: RuleAlertType[] -): PrepackagedRules[] => { +): AddPrepackagedRulesSchemaDecoded[] => { return rulesFromFileSystem.filter( (rule) => !installedRules.some((installedRule) => installedRule.params.ruleId === rule.rule_id) ); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_rules_to_update.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_rules_to_update.test.ts index 40e303bddac1a..5b2eb24bcdcd2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_rules_to_update.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_rules_to_update.test.ts @@ -5,7 +5,8 @@ */ import { getRulesToUpdate } from './get_rules_to_update'; -import { getResult, mockPrepackagedRule } from '../routes/__mocks__/request_responses'; +import { getResult } from '../routes/__mocks__/request_responses'; +import { getAddPrepackagedRulesSchemaDecodedMock } from '../../../../common/detection_engine/schemas/request/add_prepackaged_rules_schema.mock'; describe('get_rules_to_update', () => { test('should return empty array if both rule sets are empty', () => { @@ -14,7 +15,7 @@ describe('get_rules_to_update', () => { }); test('should return empty array if the id of the two rules do not match', () => { - const ruleFromFileSystem = mockPrepackagedRule(); + const ruleFromFileSystem = getAddPrepackagedRulesSchemaDecodedMock(); ruleFromFileSystem.rule_id = 'rule-1'; ruleFromFileSystem.version = 2; @@ -26,7 +27,7 @@ describe('get_rules_to_update', () => { }); test('should return empty array if the id of file system rule is less than the installed version', () => { - const ruleFromFileSystem = mockPrepackagedRule(); + const ruleFromFileSystem = getAddPrepackagedRulesSchemaDecodedMock(); ruleFromFileSystem.rule_id = 'rule-1'; ruleFromFileSystem.version = 1; @@ -38,7 +39,7 @@ describe('get_rules_to_update', () => { }); test('should return empty array if the id of file system rule is the same as the installed version', () => { - const ruleFromFileSystem = mockPrepackagedRule(); + const ruleFromFileSystem = getAddPrepackagedRulesSchemaDecodedMock(); ruleFromFileSystem.rule_id = 'rule-1'; ruleFromFileSystem.version = 1; @@ -50,7 +51,7 @@ describe('get_rules_to_update', () => { }); test('should return the rule to update if the id of file system rule is greater than the installed version', () => { - const ruleFromFileSystem = mockPrepackagedRule(); + const ruleFromFileSystem = getAddPrepackagedRulesSchemaDecodedMock(); ruleFromFileSystem.rule_id = 'rule-1'; ruleFromFileSystem.version = 2; @@ -62,7 +63,7 @@ describe('get_rules_to_update', () => { }); test('should return 1 rule out of 2 to update if the id of file system rule is greater than the installed version of just one', () => { - const ruleFromFileSystem = mockPrepackagedRule(); + const ruleFromFileSystem = getAddPrepackagedRulesSchemaDecodedMock(); ruleFromFileSystem.rule_id = 'rule-1'; ruleFromFileSystem.version = 2; @@ -79,11 +80,11 @@ describe('get_rules_to_update', () => { }); test('should return 2 rules out of 2 to update if the id of file system rule is greater than the installed version of both', () => { - const ruleFromFileSystem1 = mockPrepackagedRule(); + const ruleFromFileSystem1 = getAddPrepackagedRulesSchemaDecodedMock(); ruleFromFileSystem1.rule_id = 'rule-1'; ruleFromFileSystem1.version = 2; - const ruleFromFileSystem2 = mockPrepackagedRule(); + const ruleFromFileSystem2 = getAddPrepackagedRulesSchemaDecodedMock(); ruleFromFileSystem2.rule_id = 'rule-2'; ruleFromFileSystem2.version = 2; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_rules_to_update.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_rules_to_update.ts index 4deb01eff8b63..577ad44789bdc 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_rules_to_update.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/get_rules_to_update.ts @@ -4,13 +4,13 @@ * you may not use this file except in compliance with the Elastic License. */ -import { PrepackagedRules } from '../types'; +import { AddPrepackagedRulesSchemaDecoded } from '../../../../common/detection_engine/schemas/request/add_prepackaged_rules_schema'; import { RuleAlertType } from './types'; export const getRulesToUpdate = ( - rulesFromFileSystem: PrepackagedRules[], + rulesFromFileSystem: AddPrepackagedRulesSchemaDecoded[], installedRules: RuleAlertType[] -): PrepackagedRules[] => { +): AddPrepackagedRulesSchemaDecoded[] => { return rulesFromFileSystem.filter((rule) => installedRules.some((installedRule) => { return ( diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/install_prepacked_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/install_prepacked_rules.ts index 7b2cef9060f8c..a51acf99b570c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/install_prepacked_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/install_prepacked_rules.ts @@ -4,14 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ +import { AddPrepackagedRulesSchemaDecoded } from '../../../../common/detection_engine/schemas/request/add_prepackaged_rules_schema'; import { Alert } from '../../../../../alerts/common'; import { AlertsClient } from '../../../../../alerts/server'; import { createRules } from './create_rules'; -import { PrepackagedRules } from '../types'; +import { PartialFilter } from '../types'; export const installPrepackagedRules = ( alertsClient: AlertsClient, - rules: PrepackagedRules[], + rules: AddPrepackagedRulesSchemaDecoded[], outputIndex: string ): Array> => rules.reduce>>((acc, rule) => { @@ -21,7 +22,6 @@ export const installPrepackagedRules = ( enabled, false_positives: falsePositives, from, - immutable, query, language, machine_learning_job_id: machineLearningJobId, @@ -29,7 +29,7 @@ export const installPrepackagedRules = ( timeline_id: timelineId, timeline_title: timelineTitle, meta, - filters, + filters: filtersObject, rule_id: ruleId, index, interval, @@ -44,8 +44,11 @@ export const installPrepackagedRules = ( references, note, version, - exceptions_list, + exceptions_list: exceptionsList, } = rule; + // TODO: Fix these either with an is conversion or by better typing them within io-ts + const filters: PartialFilter[] | undefined = filtersObject as PartialFilter[]; + return [ ...acc, createRules({ @@ -55,7 +58,7 @@ export const installPrepackagedRules = ( enabled, falsePositives, from, - immutable, + immutable: true, // At the moment we force all prepackaged rules to be immutable query, language, machineLearningJobId, @@ -79,7 +82,7 @@ export const installPrepackagedRules = ( references, note, version, - exceptions_list, + exceptionsList, actions: [], // At this time there is no pre-packaged actions }), ]; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.mock.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.mock.ts new file mode 100644 index 0000000000000..e711d8d2ac287 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.mock.ts @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { PatchRulesOptions } from './types'; +import { alertsClientMock } from '../../../../../alerts/server/mocks'; +import { savedObjectsClientMock } from '../../../../../../../src/core/server/mocks'; +import { INTERNAL_RULE_ID_KEY, INTERNAL_IMMUTABLE_KEY } from '../../../../common/constants'; +import { SanitizedAlert } from '../../../../../alerts/common'; + +const rule: SanitizedAlert = { + id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd', + name: 'Detect Root/Admin Users', + tags: [`${INTERNAL_RULE_ID_KEY}:rule-1`, `${INTERNAL_IMMUTABLE_KEY}:false`], + alertTypeId: 'siem.signals', + consumer: 'siem', + params: { + anomalyThreshold: undefined, + description: 'Detecting root and admin users', + ruleId: 'rule-1', + index: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + falsePositives: [], + from: 'now-6m', + immutable: false, + query: 'user.name: root or user.name: admin', + language: 'kuery', + machineLearningJobId: undefined, + outputIndex: '.siem-signals', + timelineId: 'some-timeline-id', + timelineTitle: 'some-timeline-title', + meta: { someMeta: 'someField' }, + filters: [ + { + query: { + match_phrase: { + 'host.name': 'some-host', + }, + }, + }, + ], + riskScore: 50, + maxSignals: 100, + severity: 'high', + to: 'now', + type: 'query', + threat: [ + { + framework: 'MITRE ATT&CK', + tactic: { + id: 'TA0040', + name: 'impact', + reference: 'https://attack.mitre.org/tactics/TA0040/', + }, + technique: [ + { + id: 'T1499', + name: 'endpoint denial of service', + reference: 'https://attack.mitre.org/techniques/T1499/', + }, + ], + }, + ], + references: ['http://www.example.com', 'https://ww.example.com'], + note: '# Investigative notes', + version: 1, + exceptionsList: [ + { + field: 'source.ip', + values_operator: 'included', + values_type: 'exists', + }, + { + field: 'host.name', + values_operator: 'excluded', + values_type: 'match', + values: [ + { + name: 'rock01', + }, + ], + and: [ + { + field: 'host.id', + values_operator: 'included', + values_type: 'match_all', + values: [ + { + name: '123', + }, + { + name: '678', + }, + ], + }, + ], + }, + ], + }, + createdAt: new Date('2019-12-13T16:40:33.400Z'), + updatedAt: new Date('2019-12-13T16:40:33.400Z'), + schedule: { interval: '5m' }, + enabled: true, + actions: [], + throttle: null, + createdBy: 'elastic', + updatedBy: 'elastic', + apiKeyOwner: 'elastic', + muteAll: false, + mutedInstanceIds: [], + scheduledTaskId: '2dabe330-0702-11ea-8b50-773b89126888', +}; + +export const getPatchRulesOptionsMock = (): PatchRulesOptions => ({ + alertsClient: alertsClientMock.create(), + savedObjectsClient: savedObjectsClientMock.create(), + anomalyThreshold: undefined, + description: 'some description', + enabled: true, + falsePositives: ['false positive 1', 'false positive 2'], + from: 'now-6m', + query: 'user.name: root or user.name: admin', + language: 'kuery', + savedId: 'savedId-123', + timelineId: 'timelineid-123', + timelineTitle: 'timeline-title-123', + meta: {}, + machineLearningJobId: undefined, + filters: [], + index: ['index-123'], + interval: '5m', + maxSignals: 100, + riskScore: 80, + outputIndex: 'output-1', + name: 'Query with a rule id', + severity: 'high', + tags: [], + threat: [], + to: 'now', + type: 'query', + references: ['http://www.example.com'], + note: '# sample markdown', + version: 1, + exceptionsList: [], + actions: [], + rule, +}); + +export const getPatchMlRulesOptionsMock = (): PatchRulesOptions => ({ + alertsClient: alertsClientMock.create(), + savedObjectsClient: savedObjectsClientMock.create(), + anomalyThreshold: 55, + description: 'some description', + enabled: true, + falsePositives: ['false positive 1', 'false positive 2'], + from: 'now-6m', + query: undefined, + language: undefined, + savedId: 'savedId-123', + timelineId: 'timelineid-123', + timelineTitle: 'timeline-title-123', + meta: {}, + machineLearningJobId: 'new_job_id', + filters: [], + index: ['index-123'], + interval: '5m', + maxSignals: 100, + riskScore: 80, + outputIndex: 'output-1', + name: 'Machine Learning Job', + severity: 'high', + tags: [], + threat: [], + to: 'now', + type: 'machine_learning', + references: ['http://www.example.com'], + note: '# sample markdown', + version: 1, + exceptionsList: [], + actions: [], + rule, +}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.test.ts index 0dffa665f780b..1ca10d9067bd9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.test.ts @@ -4,83 +4,53 @@ * you may not use this file except in compliance with the Elastic License. */ -import { savedObjectsClientMock } from '../../../../../../../src/core/server/mocks'; -import { alertsClientMock } from '../../../../../alerts/server/mocks'; -import { getResult, getMlResult } from '../routes/__mocks__/request_responses'; import { patchRules } from './patch_rules'; +import { getPatchRulesOptionsMock, getPatchMlRulesOptionsMock } from './patch_rules.mock'; +import { PatchRulesOptions } from './types'; describe('patchRules', () => { - let alertsClient: ReturnType; - let savedObjectsClient: ReturnType; - - beforeEach(() => { - alertsClient = alertsClientMock.create(); - savedObjectsClient = savedObjectsClientMock.create(); - }); - - it('should call alertsClient.disable is the rule was enabled and enabled is false', async () => { - const existingRule = getResult(); - const params = getResult().params; - - await patchRules({ - alertsClient, - savedObjectsClient, - rule: existingRule, - ...params, + it('should call alertsClient.disable if the rule was enabled and enabled is false', async () => { + const rulesOptionsMock = getPatchRulesOptionsMock(); + const ruleOptions: PatchRulesOptions = { + ...rulesOptionsMock, enabled: false, - interval: '', - name: '', - tags: [], - }); - - expect(alertsClient.disable).toHaveBeenCalledWith( + }; + await patchRules(ruleOptions); + expect(ruleOptions.alertsClient.disable).toHaveBeenCalledWith( expect.objectContaining({ - id: existingRule.id, + id: ruleOptions.rule?.id, }) ); }); - it('should call alertsClient.enable is the rule was disabled and enabled is true', async () => { - const existingRule = { - ...getResult(), - enabled: false, - }; - const params = getResult().params; - - await patchRules({ - alertsClient, - savedObjectsClient, - rule: existingRule, - ...params, + it('should call alertsClient.enable if the rule was disabled and enabled is true', async () => { + const rulesOptionsMock = getPatchRulesOptionsMock(); + const ruleOptions: PatchRulesOptions = { + ...rulesOptionsMock, enabled: true, - interval: '', - name: '', - tags: [], - }); - - expect(alertsClient.enable).toHaveBeenCalledWith( + }; + if (ruleOptions.rule != null) { + ruleOptions.rule.enabled = false; + } + await patchRules(ruleOptions); + expect(ruleOptions.alertsClient.enable).toHaveBeenCalledWith( expect.objectContaining({ - id: existingRule.id, + id: ruleOptions.rule?.id, }) ); }); it('calls the alertsClient with ML params', async () => { - const existingRule = getMlResult(); - const params = { - ...getMlResult().params, - anomalyThreshold: 55, - machineLearningJobId: 'new_job_id', + const rulesOptionsMock = getPatchMlRulesOptionsMock(); + const ruleOptions: PatchRulesOptions = { + ...rulesOptionsMock, + enabled: true, }; - - await patchRules({ - alertsClient, - savedObjectsClient, - rule: existingRule, - ...params, - }); - - expect(alertsClient.update).toHaveBeenCalledWith( + if (ruleOptions.rule != null) { + ruleOptions.rule.enabled = false; + } + await patchRules(ruleOptions); + expect(ruleOptions.alertsClient.update).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ params: expect.objectContaining({ @@ -94,25 +64,22 @@ describe('patchRules', () => { describe('regression tests', () => { it("updates the rule's actions if provided", async () => { - const existingRule = getResult(); - - const action = { - action_type_id: '.slack', - id: '2933e581-d81c-4fe3-88fe-c57c6b8a5bfd', - params: { - message: 'Rule {{context.rule.name}} generated {{state.signals_count}} signals', - }, - group: 'default', + const rulesOptionsMock = getPatchRulesOptionsMock(); + const ruleOptions: PatchRulesOptions = { + ...rulesOptionsMock, + actions: [ + { + action_type_id: '.slack', + id: '2933e581-d81c-4fe3-88fe-c57c6b8a5bfd', + params: { + message: 'Rule {{context.rule.name}} generated {{state.signals_count}} signals', + }, + group: 'default', + }, + ], }; - - await patchRules({ - alertsClient, - savedObjectsClient, - actions: [action], - rule: existingRule, - }); - - expect(alertsClient.update).toHaveBeenCalledWith( + await patchRules(ruleOptions); + expect(ruleOptions.alertsClient.update).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ actions: [ @@ -131,9 +98,10 @@ describe('patchRules', () => { }); it('does not update actions if none are specified', async () => { - const existingRule = { - ...getResult(), - actions: [ + const ruleOptions = getPatchRulesOptionsMock(); + delete ruleOptions.actions; + if (ruleOptions.rule != null) { + ruleOptions.rule.actions = [ { actionTypeId: '.slack', id: '2933e581-d81c-4fe3-88fe-c57c6b8a5bfd', @@ -142,16 +110,11 @@ describe('patchRules', () => { }, group: 'default', }, - ], - }; - - await patchRules({ - alertsClient, - savedObjectsClient, - rule: existingRule, - }); + ]; + } - expect(alertsClient.update).toHaveBeenCalledWith( + await patchRules(ruleOptions); + expect(ruleOptions.alertsClient.update).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ actions: [ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.ts index 950a3e90fb70c..3796df353abb8 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/patch_rules.ts @@ -7,10 +7,11 @@ import { defaults } from 'lodash/fp'; import { PartialAlert } from '../../../../../alerts/server'; import { transformRuleToAlertAction } from '../../../../common/detection_engine/transform_actions'; -import { PatchRuleParams } from './types'; +import { PatchRulesOptions } from './types'; import { addTags } from './add_tags'; import { calculateVersion, calculateName, calculateInterval } from './utils'; import { ruleStatusSavedObjectsClientFactory } from '../signals/rule_status_saved_objects_client'; +import { Meta } from '../types'; export const patchRules = async ({ alertsClient, @@ -27,7 +28,6 @@ export const patchRules = async ({ meta, filters, from, - immutable, index, interval, maxSignals, @@ -42,11 +42,11 @@ export const patchRules = async ({ references, note, version, - exceptions_list, + exceptionsList, anomalyThreshold, machineLearningJobId, actions, -}: PatchRuleParams): Promise => { +}: PatchRulesOptions): Promise => { if (rule == null) { return null; } @@ -60,7 +60,7 @@ export const patchRules = async ({ savedId, timelineId, timelineTitle, - meta, + meta: meta as Meta | undefined, // TODO: Remove this cast once we fix the types for calculate version and patch, filters, from, index, @@ -76,7 +76,7 @@ export const patchRules = async ({ references, version, note, - exceptions_list, + exceptionsList, anomalyThreshold, machineLearningJobId, }); @@ -89,7 +89,6 @@ export const patchRules = async ({ description, falsePositives, from, - immutable, query, language, outputIndex, @@ -108,7 +107,7 @@ export const patchRules = async ({ references, note, version: calculatedVersion, - exceptions_list, + exceptionsList, anomalyThreshold, machineLearningJobId, } @@ -117,7 +116,7 @@ export const patchRules = async ({ const update = await alertsClient.update({ id: rule.id, data: { - tags: addTags(tags ?? rule.tags, rule.params.ruleId, immutable ?? rule.params.immutable), + tags: addTags(tags ?? rule.tags, rule.params.ruleId, rule.params.immutable), throttle: null, name: calculateName({ updatedName: name, originalName: rule.name }), schedule: { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/read_rules.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/read_rules.test.ts index ef8e70c78422c..b17a7358cfa52 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/read_rules.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/read_rules.test.ts @@ -81,18 +81,6 @@ describe('read_rules', () => { } }); - test('should return the output from alertsClient if id is set but ruleId is null', async () => { - const alertsClient = alertsClientMock.create(); - alertsClient.get.mockResolvedValue(getResult()); - - const rule = await readRules({ - alertsClient, - id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd', - ruleId: null, - }); - expect(rule).toEqual(getResult()); - }); - test('should return the output from alertsClient if id is undefined but ruleId is set', async () => { const alertsClient = alertsClientMock.create(); alertsClient.get.mockResolvedValue(getResult()); @@ -126,25 +114,12 @@ describe('read_rules', () => { const rule = await readRules({ alertsClient, - id: null, + id: undefined, ruleId: 'rule-1', }); expect(rule).toEqual(getResult()); }); - test('should return null if id and ruleId are null', async () => { - const alertsClient = alertsClientMock.create(); - alertsClient.get.mockResolvedValue(getResult()); - alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); - - const rule = await readRules({ - alertsClient, - id: null, - ruleId: null, - }); - expect(rule).toEqual(null); - }); - test('should return null if id and ruleId are undefined', async () => { const alertsClient = alertsClientMock.create(); alertsClient.get.mockResolvedValue(getResult()); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/read_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/read_rules.ts index a8b76aeb8c453..e4bb65a907e2d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/read_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/read_rules.ts @@ -7,7 +7,7 @@ import { SanitizedAlert } from '../../../../../alerts/common'; import { INTERNAL_RULE_ID_KEY } from '../../../../common/constants'; import { findRules } from './find_rules'; -import { ReadRuleParams, isAlertType } from './types'; +import { isAlertType, ReadRuleOptions } from './types'; /** * This reads the rules through a cascade try of what is fastest to what is slowest. @@ -21,7 +21,7 @@ export const readRules = async ({ alertsClient, id, ruleId, -}: ReadRuleParams): Promise => { +}: ReadRuleOptions): Promise => { if (id != null) { try { const rule = await alertsClient.get({ id }); @@ -43,6 +43,10 @@ export const readRules = async ({ alertsClient, filter: `alert.attributes.tags: "${INTERNAL_RULE_ID_KEY}:${ruleId}"`, page: 1, + fields: undefined, + perPage: undefined, + sortField: undefined, + sortOrder: undefined, }); if (ruleFromFind.data.length === 0 || !isAlertType(ruleFromFind.data[0])) { return null; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/types.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/types.ts index 70d53090f81cc..8bdb1287c6df2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/types.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/types.ts @@ -13,29 +13,67 @@ import { SavedObjectsFindResponse, SavedObjectsClientContract, } from 'kibana/server'; +import { RuleAlertAction } from '../../../../common/detection_engine/types'; +import { ListsDefaultArraySchema } from '../../../../common/detection_engine/schemas/types/lists_default_array'; +import { + FalsePositives, + From, + RuleId, + Immutable, + DescriptionOrUndefined, + Interval, + MaxSignals, + RiskScore, + OutputIndex, + Name, + Severity, + Tags, + Threat, + To, + Type, + References, + Version, + AnomalyThresholdOrUndefined, + QueryOrUndefined, + LanguageOrUndefined, + SavedIdOrUndefined, + TimelineIdOrUndefined, + TimelineTitleOrUndefined, + MachineLearningJobIdOrUndefined, + IndexOrUndefined, + NoteOrUndefined, + MetaOrUndefined, + Description, + Enabled, + VersionOrUndefined, + IdOrUndefined, + RuleIdOrUndefined, + EnabledOrUndefined, + FalsePositivesOrUndefined, + FromOrUndefined, + OutputIndexOrUndefined, + IntervalOrUndefined, + MaxSignalsOrUndefined, + RiskScoreOrUndefined, + NameOrUndefined, + SeverityOrUndefined, + TagsOrUndefined, + ToOrUndefined, + ThreatOrUndefined, + TypeOrUndefined, + ReferencesOrUndefined, + ListAndOrUndefined, + PerPageOrUndefined, + PageOrUndefined, + SortFieldOrUndefined, + QueryFilterOrUndefined, + FieldsOrUndefined, + SortOrderOrUndefined, +} from '../../../../common/detection_engine/schemas/common/schemas'; import { AlertsClient, PartialAlert } from '../../../../../alerts/server'; import { Alert, SanitizedAlert } from '../../../../../alerts/common'; import { SIGNALS_ID } from '../../../../common/constants'; -import { RuleAlertParams, RuleTypeParams, RuleAlertParamsRest } from '../types'; - -export type PatchRuleAlertParamsRest = Partial & { - id: string | undefined; - rule_id: RuleAlertParams['ruleId'] | undefined; -}; - -export type UpdateRuleAlertParamsRest = RuleAlertParamsRest & { - id: string | undefined; - rule_id: RuleAlertParams['ruleId'] | undefined; -}; - -export interface FindParamsRest { - per_page: number; - page: number; - sort_field: string; - sort_order: 'asc' | 'desc'; - fields: string[]; - filter: string; -} +import { RuleAlertParams, RuleTypeParams, PartialFilter } from '../types'; export interface RuleAlertType extends Alert { params: RuleTypeParams; @@ -90,81 +128,17 @@ export interface HapiReadableStream extends Readable { filename: string; }; } -export interface ImportRulesRequestParams { - query: { overwrite: boolean }; - body: { file: HapiReadableStream }; -} - -export interface ExportRulesRequestParams { - body: { objects: Array<{ rule_id: string }> | null | undefined }; - query: { - file_name: string; - exclude_export_details: boolean; - }; -} - -export interface RuleRequestParams { - id: string | undefined; - rule_id: string | undefined; -} - -export type ReadRuleRequestParams = RuleRequestParams; -export type DeleteRuleRequestParams = RuleRequestParams; -export type DeleteRulesRequestParams = RuleRequestParams[]; - -export interface FindRuleParams { - alertsClient: AlertsClient; - perPage?: number; - page?: number; - sortField?: string; - filter?: string; - fields?: string[]; - sortOrder?: 'asc' | 'desc'; -} - -export interface FindRulesRequestParams { - per_page: number; - page: number; - search?: string; - sort_field?: string; - filter?: string; - fields?: string[]; - sort_order?: 'asc' | 'desc'; -} - -export interface FindRulesStatusesRequestParams { - ids: string[]; -} export interface Clients { alertsClient: AlertsClient; } +// TODO: Try and remove this patch export type PatchRuleParams = Partial> & { rule: SanitizedAlert | null; savedObjectsClient: SavedObjectsClientContract; } & Clients; -export type UpdateRuleParams = Omit & { - id: string | undefined | null; - savedObjectsClient: SavedObjectsClientContract; -} & Clients; - -export type DeleteRuleParams = Clients & { - id: string | undefined; - ruleId: string | undefined | null; -}; - -export type CreateRuleParams = Omit & { - ruleId: string; -} & Clients; - -export interface ReadRuleParams { - alertsClient: AlertsClient; - id?: string | undefined | null; - ruleId?: string | undefined | null; -} - export const isAlertTypes = (partialAlert: PartialAlert[]): partialAlert is RuleAlertType[] => { return partialAlert.every((rule) => isAlertType(rule)); }; @@ -190,3 +164,131 @@ export const isRuleStatusFindTypes = ( ): obj is Array> => { return obj ? obj.every((ruleStatus) => isRuleStatusFindType(ruleStatus)) : false; }; + +export interface CreateRulesOptions { + alertsClient: AlertsClient; + anomalyThreshold: AnomalyThresholdOrUndefined; + description: Description; + enabled: Enabled; + falsePositives: FalsePositives; + from: From; + query: QueryOrUndefined; + language: LanguageOrUndefined; + savedId: SavedIdOrUndefined; + timelineId: TimelineIdOrUndefined; + timelineTitle: TimelineTitleOrUndefined; + meta: MetaOrUndefined; + machineLearningJobId: MachineLearningJobIdOrUndefined; + filters: PartialFilter[]; + ruleId: RuleId; + immutable: Immutable; + index: IndexOrUndefined; + interval: Interval; + maxSignals: MaxSignals; + riskScore: RiskScore; + outputIndex: OutputIndex; + name: Name; + severity: Severity; + tags: Tags; + threat: Threat; + to: To; + type: Type; + references: References; + note: NoteOrUndefined; + version: Version; + exceptionsList: ListsDefaultArraySchema; + actions: RuleAlertAction[]; +} + +export interface UpdateRulesOptions { + id: IdOrUndefined; + savedObjectsClient: SavedObjectsClientContract; + alertsClient: AlertsClient; + anomalyThreshold: AnomalyThresholdOrUndefined; + description: Description; + enabled: Enabled; + falsePositives: FalsePositives; + from: From; + query: QueryOrUndefined; + language: LanguageOrUndefined; + savedId: SavedIdOrUndefined; + timelineId: TimelineIdOrUndefined; + timelineTitle: TimelineTitleOrUndefined; + meta: MetaOrUndefined; + machineLearningJobId: MachineLearningJobIdOrUndefined; + filters: PartialFilter[]; + ruleId: RuleIdOrUndefined; + index: IndexOrUndefined; + interval: Interval; + maxSignals: MaxSignals; + riskScore: RiskScore; + outputIndex: OutputIndex; + name: Name; + severity: Severity; + tags: Tags; + threat: Threat; + to: To; + type: Type; + references: References; + note: NoteOrUndefined; + version: VersionOrUndefined; + exceptionsList: ListsDefaultArraySchema; + actions: RuleAlertAction[]; +} + +export interface PatchRulesOptions { + savedObjectsClient: SavedObjectsClientContract; + alertsClient: AlertsClient; + anomalyThreshold: AnomalyThresholdOrUndefined; + description: DescriptionOrUndefined; + enabled: EnabledOrUndefined; + falsePositives: FalsePositivesOrUndefined; + from: FromOrUndefined; + query: QueryOrUndefined; + language: LanguageOrUndefined; + savedId: SavedIdOrUndefined; + timelineId: TimelineIdOrUndefined; + timelineTitle: TimelineTitleOrUndefined; + meta: MetaOrUndefined; + machineLearningJobId: MachineLearningJobIdOrUndefined; + filters: PartialFilter[]; + index: IndexOrUndefined; + interval: IntervalOrUndefined; + maxSignals: MaxSignalsOrUndefined; + riskScore: RiskScoreOrUndefined; + outputIndex: OutputIndexOrUndefined; + name: NameOrUndefined; + severity: SeverityOrUndefined; + tags: TagsOrUndefined; + threat: ThreatOrUndefined; + to: ToOrUndefined; + type: TypeOrUndefined; + references: ReferencesOrUndefined; + note: NoteOrUndefined; + version: VersionOrUndefined; + exceptionsList: ListAndOrUndefined; + actions: RuleAlertAction[] | undefined; + rule: SanitizedAlert | null; +} + +export interface ReadRuleOptions { + alertsClient: AlertsClient; + id: IdOrUndefined; + ruleId: RuleIdOrUndefined; +} + +export interface DeleteRuleOptions { + alertsClient: AlertsClient; + id: IdOrUndefined; + ruleId: RuleIdOrUndefined; +} + +export interface FindRuleOptions { + alertsClient: AlertsClient; + perPage: PerPageOrUndefined; + page: PageOrUndefined; + sortField: SortFieldOrUndefined; + filter: QueryFilterOrUndefined; + fields: FieldsOrUndefined; + sortOrder: SortOrderOrUndefined; +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_prepacked_rules.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_prepacked_rules.test.ts index ede5c51d1e5e7..1945d00c75c88 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_prepacked_rules.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_prepacked_rules.test.ts @@ -6,12 +6,10 @@ import { savedObjectsClientMock } from '../../../../../../../src/core/server/mocks'; import { alertsClientMock } from '../../../../../alerts/server/mocks'; -import { - mockPrepackagedRule, - getFindResultWithSingleHit, -} from '../routes/__mocks__/request_responses'; +import { getFindResultWithSingleHit } from '../routes/__mocks__/request_responses'; import { updatePrepackagedRules } from './update_prepacked_rules'; import { patchRules } from './patch_rules'; +import { getAddPrepackagedRulesSchemaDecodedMock } from '../../../../common/detection_engine/schemas/request/add_prepackaged_rules_schema.mock'; jest.mock('./patch_rules'); describe('updatePrepackagedRules', () => { @@ -33,7 +31,7 @@ describe('updatePrepackagedRules', () => { }, ]; const outputIndex = 'outputIndex'; - const prepackagedRule = mockPrepackagedRule(); + const prepackagedRule = getAddPrepackagedRulesSchemaDecodedMock(); alertsClient.find.mockResolvedValue(getFindResultWithSingleHit()); await updatePrepackagedRules( @@ -44,9 +42,14 @@ describe('updatePrepackagedRules', () => { ); expect(patchRules).toHaveBeenCalledWith( - expect.not.objectContaining({ - enabled: true, - actions, + expect.objectContaining({ + actions: undefined, + }) + ); + + expect(patchRules).toHaveBeenCalledWith( + expect.objectContaining({ + enabled: undefined, }) ); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_prepacked_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_prepacked_rules.ts index c793d7eb9b6dc..c4792eaa97ee1 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_prepacked_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_prepacked_rules.ts @@ -5,15 +5,16 @@ */ import { SavedObjectsClientContract } from 'kibana/server'; +import { AddPrepackagedRulesSchemaDecoded } from '../../../../common/detection_engine/schemas/request/add_prepackaged_rules_schema'; import { AlertsClient } from '../../../../../alerts/server'; import { patchRules } from './patch_rules'; -import { PrepackagedRules } from '../types'; import { readRules } from './read_rules'; +import { PartialFilter } from '../types'; export const updatePrepackagedRules = async ( alertsClient: AlertsClient, savedObjectsClient: SavedObjectsClientContract, - rules: PrepackagedRules[], + rules: AddPrepackagedRulesSchemaDecoded[], outputIndex: string ): Promise => { await Promise.all( @@ -22,12 +23,11 @@ export const updatePrepackagedRules = async ( description, false_positives: falsePositives, from, - immutable, query, language, saved_id: savedId, meta, - filters, + filters: filtersObject, rule_id: ruleId, index, interval, @@ -42,10 +42,18 @@ export const updatePrepackagedRules = async ( references, version, note, + anomaly_threshold: anomalyThreshold, + timeline_id: timelineId, + timeline_title: timelineTitle, + machine_learning_job_id: machineLearningJobId, + exceptions_list: exceptionsList, } = rule; const existingRule = await readRules({ alertsClient, ruleId, id: undefined }); + // TODO: Fix these either with an is conversion or by better typing them within io-ts + const filters: PartialFilter[] | undefined = filtersObject as PartialFilter[]; + // Note: we do not pass down enabled as we do not want to suddenly disable // or enable rules on the user when they were not expecting it if a rule updates return patchRules({ @@ -53,7 +61,6 @@ export const updatePrepackagedRules = async ( description, falsePositives, from, - immutable, query, language, outputIndex, @@ -75,6 +82,13 @@ export const updatePrepackagedRules = async ( references, version, note, + anomalyThreshold, + enabled: undefined, + timelineId, + timelineTitle, + machineLearningJobId, + exceptionsList, + actions: undefined, }); }) ); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.mock.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.mock.ts new file mode 100644 index 0000000000000..7812c66a74d1f --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.mock.ts @@ -0,0 +1,81 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { UpdateRulesOptions } from './types'; +import { alertsClientMock } from '../../../../../alerts/server/mocks'; +import { savedObjectsClientMock } from '../../../../../../../src/core/server/mocks'; + +export const getUpdateRulesOptionsMock = (): UpdateRulesOptions => ({ + id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd', + alertsClient: alertsClientMock.create(), + savedObjectsClient: savedObjectsClientMock.create(), + anomalyThreshold: undefined, + description: 'some description', + enabled: true, + falsePositives: ['false positive 1', 'false positive 2'], + from: 'now-6m', + query: 'user.name: root or user.name: admin', + language: 'kuery', + savedId: 'savedId-123', + timelineId: 'timelineid-123', + timelineTitle: 'timeline-title-123', + meta: {}, + machineLearningJobId: undefined, + filters: [], + ruleId: undefined, + index: ['index-123'], + interval: '5m', + maxSignals: 100, + riskScore: 80, + outputIndex: 'output-1', + name: 'Query with a rule id', + severity: 'high', + tags: [], + threat: [], + to: 'now', + type: 'query', + references: ['http://www.example.com'], + note: '# sample markdown', + version: 1, + exceptionsList: [], + actions: [], +}); + +export const getUpdateMlRulesOptionsMock = (): UpdateRulesOptions => ({ + id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd', + alertsClient: alertsClientMock.create(), + savedObjectsClient: savedObjectsClientMock.create(), + anomalyThreshold: 55, + description: 'some description', + enabled: true, + falsePositives: ['false positive 1', 'false positive 2'], + from: 'now-6m', + query: undefined, + language: undefined, + savedId: 'savedId-123', + timelineId: 'timelineid-123', + timelineTitle: 'timeline-title-123', + meta: {}, + machineLearningJobId: 'new_job_id', + filters: [], + ruleId: undefined, + index: ['index-123'], + interval: '5m', + maxSignals: 100, + riskScore: 80, + outputIndex: 'output-1', + name: 'Machine Learning Job', + severity: 'high', + tags: [], + threat: [], + to: 'now', + type: 'machine_learning', + references: ['http://www.example.com'], + note: '# sample markdown', + version: 1, + exceptionsList: [], + actions: [], +}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.test.ts index 222411deb37ab..cf59d2bb5e8c4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.test.ts @@ -4,96 +4,69 @@ * you may not use this file except in compliance with the Elastic License. */ -import { savedObjectsClientMock } from '../../../../../../../src/core/server/mocks'; -import { alertsClientMock } from '../../../../../alerts/server/mocks'; import { getResult, getMlResult } from '../routes/__mocks__/request_responses'; import { updateRules } from './update_rules'; +import { getUpdateRulesOptionsMock, getUpdateMlRulesOptionsMock } from './update_rules.mock'; +import { AlertsClientMock } from '../../../../../alerts/server/alerts_client.mock'; describe('updateRules', () => { - let alertsClient: ReturnType; - let savedObjectsClient: ReturnType; - - beforeEach(() => { - alertsClient = alertsClientMock.create(); - savedObjectsClient = savedObjectsClientMock.create(); - }); - - it('should call alertsClient.disable is the rule was enabled and enabled is false', async () => { - const rule = getResult(); - alertsClient.get.mockResolvedValue(getResult()); - - await updateRules({ - alertsClient, - savedObjectsClient, - id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd', - ...rule.params, + it('should call alertsClient.disable if the rule was enabled and enabled is false', async () => { + const rulesOptionsMock = getUpdateRulesOptionsMock(); + const ruleOptions = { + ...rulesOptionsMock, enabled: false, - interval: '', - name: '', - tags: [], - actions: [], - }); + }; + ((ruleOptions.alertsClient as unknown) as AlertsClientMock).get.mockResolvedValue(getResult()); + + await updateRules(ruleOptions); - expect(alertsClient.disable).toHaveBeenCalledWith( + expect(ruleOptions.alertsClient.disable).toHaveBeenCalledWith( expect.objectContaining({ - id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd', + id: rulesOptionsMock.id, }) ); }); - it('should call alertsClient.enable is the rule was disabled and enabled is true', async () => { - const rule = getResult(); - alertsClient.get.mockResolvedValue({ + it('should call alertsClient.enable if the rule was disabled and enabled is true', async () => { + const rulesOptionsMock = getUpdateRulesOptionsMock(); + const ruleOptions = { + ...rulesOptionsMock, + enabled: true, + }; + + ((ruleOptions.alertsClient as unknown) as AlertsClientMock).get.mockResolvedValue({ ...getResult(), enabled: false, }); - await updateRules({ - alertsClient, - savedObjectsClient, - id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd', - ...rule.params, - enabled: true, - interval: '', - name: '', - tags: [], - actions: [], - }); + await updateRules(ruleOptions); - expect(alertsClient.enable).toHaveBeenCalledWith( + expect(ruleOptions.alertsClient.enable).toHaveBeenCalledWith( expect.objectContaining({ - id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd', + id: rulesOptionsMock.id, }) ); }); it('calls the alertsClient with ML params', async () => { - alertsClient.get.mockResolvedValue(getMlResult()); - - const params = { - ...getMlResult().params, - anomalyThreshold: 55, - machineLearningJobId: 'new_job_id', + const rulesOptionsMock = getUpdateMlRulesOptionsMock(); + const ruleOptions = { + ...rulesOptionsMock, + enabled: true, }; - await updateRules({ - alertsClient, - savedObjectsClient, - id: '04128c15-0d1b-4716-a4c5-46997ac7f3bd', - ...params, - enabled: true, - interval: '', - name: '', - tags: [], - actions: [], - }); + ((ruleOptions.alertsClient as unknown) as AlertsClientMock).get.mockResolvedValue( + getMlResult() + ); + + await updateRules(ruleOptions); - expect(alertsClient.update).toHaveBeenCalledWith( + expect(ruleOptions.alertsClient.update).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ params: expect.objectContaining({ - anomalyThreshold: 55, - machineLearningJobId: 'new_job_id', + anomalyThreshold: rulesOptionsMock.anomalyThreshold, + machineLearningJobId: rulesOptionsMock.machineLearningJobId, }), }), }) diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.ts index 54031b6e35bf1..0236c357988d5 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/update_rules.ts @@ -7,11 +7,12 @@ import { transformRuleToAlertAction } from '../../../../common/detection_engine/transform_actions'; import { PartialAlert } from '../../../../../alerts/server'; import { readRules } from './read_rules'; -import { UpdateRuleParams } from './types'; +import { UpdateRulesOptions } from './types'; import { addTags } from './add_tags'; import { calculateVersion } from './utils'; import { hasListsFeature } from '../feature_flags'; import { ruleStatusSavedObjectsClientFactory } from '../signals/rule_status_saved_objects_client'; +import { Meta } from '../types'; export const updateRules = async ({ alertsClient, @@ -43,11 +44,11 @@ export const updateRules = async ({ references, version, note, - exceptions_list, + exceptionsList, anomalyThreshold, machineLearningJobId, actions, -}: UpdateRuleParams): Promise => { +}: UpdateRulesOptions): Promise => { const rule = await readRules({ alertsClient, ruleId, id }); if (rule == null) { return null; @@ -62,7 +63,7 @@ export const updateRules = async ({ savedId, timelineId, timelineTitle, - meta, + meta: meta as Meta, // TODO: Remove this cast once we fix the types for calculate version and patch filters, from, index, @@ -83,7 +84,7 @@ export const updateRules = async ({ }); // TODO: Remove this and use regular exceptions_list once the feature is stable for a release - const exceptionsListParam = hasListsFeature() ? { exceptions_list } : {}; + const exceptionsListParam = hasListsFeature() ? { exceptionsList } : {}; const update = await alertsClient.update({ id: rule.id, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/scripts/create_ndjson_prepackaged_rules.sh b/x-pack/plugins/security_solution/server/lib/detection_engine/scripts/create_ndjson_prepackaged_rules.sh new file mode 100755 index 0000000000000..29c69ae857f3e --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/scripts/create_ndjson_prepackaged_rules.sh @@ -0,0 +1,17 @@ +#!/bin/sh + +# +# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one +# or more contributor license agreements. Licensed under the Elastic License; +# you may not use this file except in compliance with the Elastic License. +# + +i=0; +for f in ../rules/prepackaged_rules/*.json ; do + ((i++)); + echo "converting $f" + cat ../rules/prepackaged_rules/windows_msxsl_network.json | tr -d '\n' | tr -d ' ' >> pre_packaged_rules.ndjson + echo "" >> pre_packaged_rules.ndjson +done +echo "{\"exported_count\":$i,\"missing_rules\":[],\"missing_rules_count\":0}" >> pre_packaged_rules.ndjson + diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/__mocks__/es_results.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/__mocks__/es_results.ts index 2d75ba4f42d12..46a16e7dca153 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/__mocks__/es_results.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/__mocks__/es_results.ts @@ -44,7 +44,7 @@ export const sampleRuleAlertParams = ( meta: undefined, threat: undefined, version: 1, - exceptions_list: [ + exceptionsList: [ { field: 'source.ip', values_operator: 'included', diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_exceptions_query.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_exceptions_query.ts index b33a2376589ef..d4efd9a2e8a1a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_exceptions_query.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_exceptions_query.ts @@ -189,7 +189,7 @@ export const buildQueryExceptions = ({ }: { query: string; language: Language; - lists: RuleAlertParams['exceptions_list']; + lists: RuleAlertParams['exceptionsList']; }): Query[] => { if (lists && lists !== null) { const exceptions = buildExceptions({ lists, language, query }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_rule.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_rule.ts index 93d4e5e7719b2..de8de1bc513e3 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_rule.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_rule.ts @@ -72,7 +72,7 @@ export const buildRule = ({ version: ruleParams.version, created_at: createdAt, updated_at: updatedAt, - exceptions_list: ruleParams.exceptions_list, + exceptions_list: ruleParams.exceptionsList, machine_learning_job_id: ruleParams.machineLearningJobId, anomaly_threshold: ruleParams.anomalyThreshold, }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.ts index 07435fda0da2e..29b8b54d162df 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.ts @@ -14,7 +14,7 @@ import { RuleAlertParams } from '../types'; interface FilterEventsAgainstList { listClient: ListClient; - exceptionsList: RuleAlertParams['exceptions_list']; + exceptionsList: RuleAlertParams['exceptionsList']; logger: Logger; eventSearchResult: SignalSearchResponse; } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.ts index 1630192b3c03a..c464238715afd 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.ts @@ -22,7 +22,7 @@ export const getQueryFilter = ( language: Language, filters: PartialFilter[], index: string[], - lists: RuleAlertParams['exceptions_list'] + lists: RuleAlertParams['exceptionsList'] ) => { const indexPattern = { fields: [], @@ -53,7 +53,7 @@ interface GetFilterArgs { savedId: string | undefined | null; services: AlertServices; index: string[] | undefined | null; - lists: RuleAlertParams['exceptions_list']; + lists: RuleAlertParams['exceptionsList']; } interface QueryAttributes { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts index e44b82224d1ce..b7bea906475db 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts @@ -18,7 +18,7 @@ interface SearchAfterAndBulkCreateParams { ruleParams: RuleTypeParams; services: AlertServices; listClient: ListClient | undefined; // TODO: undefined is for temporary development, remove before merged - exceptionsList: RuleAlertParams['exceptions_list']; + exceptionsList: RuleAlertParams['exceptionsList']; logger: Logger; id: string; inputIndexPattern: string[]; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_params_schema.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_params_schema.ts index 81a6ce9b08f02..d42ba8fe57005 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_params_schema.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_params_schema.ts @@ -39,5 +39,5 @@ export const signalParamsSchema = () => type: schema.string(), references: schema.arrayOf(schema.string(), { defaultValue: [] }), version: schema.number({ defaultValue: 1 }), - exceptions_list: schema.maybe(schema.arrayOf(schema.object({}, { unknowns: 'allow' }))), + exceptionsList: schema.maybe(schema.arrayOf(schema.object({}, { unknowns: 'allow' }))), }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.ts index 6885b4c814679..567274be6a9f8 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.ts @@ -79,7 +79,7 @@ export const signalRulesAlertType = ({ query, to, type, - exceptions_list: exceptionsList, + exceptionsList, } = params; const searchAfterSize = Math.min(maxSignals, DEFAULT_SEARCH_AFTER_PAGE_SIZE); let hasError: boolean = false; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/types.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/types.ts index 90497b6e34cb4..869c81f640561 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/types.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/types.ts @@ -21,20 +21,6 @@ export interface SignalsStatusParams { status: 'open' | 'closed'; } -export interface SignalQueryParams { - query: object | undefined | null; - aggs: object | undefined | null; - _source: string[] | undefined | null; - size: number | undefined | null; - track_total_hits: boolean | undefined | null; -} - -export type SignalsStatusRestParams = Omit & { - signal_ids: SignalsStatusParams['signalIds']; -}; - -export type SignalsQueryRestParams = SignalQueryParams; - export type SearchTypes = | string | string[] diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/tags/read_tags.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/tags/read_tags.ts index 2bb2b5ec47e2f..5bf2b47c78181 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/tags/read_tags.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/tags/read_tags.ts @@ -61,6 +61,7 @@ export const readRawTags = async ({ page: 1, sortField: 'createdAt', sortOrder: 'desc', + filter: undefined, }); // Get all the rules to aggregate over all the tags of the rules const rules = await findRules({ @@ -70,6 +71,7 @@ export const readRawTags = async ({ sortField: 'createdAt', sortOrder: 'desc', page: 1, + filter: undefined, }); const tagSet = convertTagsToSet(rules.data); return Array.from(tagSet); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/types.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/types.ts index 53c8a9bf0a7e7..9062de49fa6ce 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/types.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/types.ts @@ -68,7 +68,7 @@ export interface RuleAlertParams { type: RuleType; version: number; throttle: string | undefined | null; - exceptions_list: ListsDefaultArraySchema | null | undefined; + exceptionsList: ListsDefaultArraySchema | null | undefined; } export type RuleTypeParams = Omit< @@ -83,6 +83,7 @@ export type RuleAlertParamsRest = Omit< | 'falsePositives' | 'immutable' | 'maxSignals' + | 'exceptionsList' | 'machineLearningJobId' | 'savedId' | 'riskScore' @@ -101,6 +102,7 @@ export type RuleAlertParamsRest = Omit< | 'lastFailureMessage' > & { anomaly_threshold: RuleAlertParams['anomalyThreshold']; + exceptions_list: RuleAlertParams['exceptionsList']; rule_id: RuleAlertParams['ruleId']; false_positives: RuleAlertParams['falsePositives']; saved_id?: RuleAlertParams['savedId']; @@ -127,24 +129,6 @@ export type OutputRuleAlertRest = RuleAlertParamsRest & { immutable: boolean; }; -export type ImportRuleAlertRest = Omit & { - id: string | undefined | null; - rule_id: string; - immutable: boolean; -}; - -export type PrepackagedRules = Omit< - RuleAlertParamsRest, - | 'status' - | 'status_date' - | 'last_failure_at' - | 'last_success_at' - | 'last_failure_message' - | 'last_success_message' - | 'updated_at' - | 'created_at' -> & { rule_id: string; immutable: boolean }; - // eslint-disable-next-line @typescript-eslint/no-explicit-any export type CallWithRequest, V> = ( endpoint: string, diff --git a/x-pack/plugins/security_solution/server/lib/timeline/pick_saved_timeline.ts b/x-pack/plugins/security_solution/server/lib/timeline/pick_saved_timeline.ts index 40c568ecda741..281726d488abe 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/pick_saved_timeline.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/pick_saved_timeline.ts @@ -39,17 +39,15 @@ export const pickSavedTimeline = ( savedTimeline.templateTimelineVersion = savedTimeline.templateTimelineVersion + 1; } } - } else if (savedTimeline.status === TimelineStatus.draft) { - savedTimeline.status = !isEmpty(savedTimeline.title) - ? TimelineStatus.active - : TimelineStatus.draft; - savedTimeline.templateTimelineId = null; - savedTimeline.templateTimelineVersion = null; } else { savedTimeline.timelineType = savedTimeline.timelineType ?? TimelineType.default; savedTimeline.templateTimelineId = null; savedTimeline.templateTimelineVersion = null; } + if (!isEmpty(savedTimeline.title) && savedTimeline.status === TimelineStatus.draft) { + savedTimeline.status = TimelineStatus.active; + } + return savedTimeline; }; diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/clean_draft_timelines_route.test.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/clean_draft_timelines_route.test.ts index 9dc957604d4df..0e53cee0bf8ac 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/clean_draft_timelines_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/clean_draft_timelines_route.test.ts @@ -17,6 +17,7 @@ import { cleanDraftTimelinesRequest, createTimelineWithTimelineId, } from './__mocks__/request_responses'; +import { draftTimelineDefaults } from '../default_timeline'; describe('clean draft timelines', () => { let server: ReturnType; @@ -81,7 +82,12 @@ describe('clean draft timelines', () => { }); const response = await server.inject(cleanDraftTimelinesRequest(TimelineType.default), context); + const req = cleanDraftTimelinesRequest(TimelineType.default); expect(mockPersistTimeline).toHaveBeenCalled(); + expect(mockPersistTimeline.mock.calls[0][3]).toEqual({ + ...draftTimelineDefaults, + timelineType: req.body.timelineType, + }); expect(response.status).toEqual(200); expect(response.body).toEqual({ data: { @@ -100,8 +106,13 @@ describe('clean draft timelines', () => { mockGetTimeline.mockResolvedValue({ ...mockGetDraftTimelineValue }); const response = await server.inject(cleanDraftTimelinesRequest(TimelineType.default), context); + const req = cleanDraftTimelinesRequest(TimelineType.default); + expect(mockPersistTimeline).not.toHaveBeenCalled(); expect(mockResetTimeline).toHaveBeenCalled(); + expect(mockResetTimeline.mock.calls[0][1]).toEqual([mockGetDraftTimelineValue.savedObjectId]); + expect(mockResetTimeline.mock.calls[0][2]).toEqual(req.body.timelineType); + expect(mockGetTimeline).toHaveBeenCalled(); expect(response.status).toEqual(200); expect(response.body).toEqual({ diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/clean_draft_timelines_route.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/clean_draft_timelines_route.ts index 30225da6b42cc..9ad50b8f2266c 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/clean_draft_timelines_route.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/clean_draft_timelines_route.ts @@ -40,7 +40,11 @@ export const cleanDraftTimelinesRoute = ( } = await getDraftTimeline(frameworkRequest, request.body.timelineType); if (draftTimeline?.savedObjectId) { - await resetTimeline(frameworkRequest, [draftTimeline.savedObjectId]); + await resetTimeline( + frameworkRequest, + [draftTimeline.savedObjectId], + request.body.timelineType + ); const cleanedDraftTimeline = await getTimeline( frameworkRequest, draftTimeline.savedObjectId @@ -57,12 +61,10 @@ export const cleanDraftTimelinesRoute = ( }); } - const newTimelineResponse = await persistTimeline( - frameworkRequest, - null, - null, - draftTimelineDefaults - ); + const newTimelineResponse = await persistTimeline(frameworkRequest, null, null, { + ...draftTimelineDefaults, + timelineType: request.body.timelineType, + }); if (newTimelineResponse.code === 200) { return response.ok({ diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/get_draft_timelines_route.test.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/get_draft_timelines_route.test.ts index e9bceb2c66806..5447da8ef49d2 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/get_draft_timelines_route.test.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/get_draft_timelines_route.test.ts @@ -17,6 +17,7 @@ import { getDraftTimelinesRequest, createTimelineWithTimelineId, } from './__mocks__/request_responses'; +import { draftTimelineDefaults } from '../default_timeline'; describe('get draft timelines', () => { let server: ReturnType; @@ -80,12 +81,14 @@ describe('get draft timelines', () => { mockGetDraftTimeline.mockResolvedValue({ timeline: [], }); - - const response = await server.inject( - getDraftTimelinesRequest(TimelineType.default), - context - ); + const req = getDraftTimelinesRequest(TimelineType.default); + const response = await server.inject(req, context); expect(mockPersistTimeline).toHaveBeenCalled(); + expect(mockPersistTimeline.mock.calls[0][3]).toEqual({ + ...draftTimelineDefaults, + timelineType: req.query.timelineType, + }); + expect(response.status).toEqual(200); expect(response.body).toEqual({ data: { diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/get_draft_timelines_route.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/get_draft_timelines_route.ts index 7b379741fc217..4db434ec816aa 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/get_draft_timelines_route.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/get_draft_timelines_route.ts @@ -51,12 +51,10 @@ export const getDraftTimelinesRoute = ( }); } - const newTimelineResponse = await persistTimeline( - frameworkRequest, - null, - null, - draftTimelineDefaults - ); + const newTimelineResponse = await persistTimeline(frameworkRequest, null, null, { + ...draftTimelineDefaults, + timelineType: request.query.timelineType, + }); if (newTimelineResponse.code === 200) { return response.ok({ diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/update_timelines_route.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/update_timelines_route.ts index a479c818cb01d..d5ecd408a6ef4 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/update_timelines_route.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/update_timelines_route.ts @@ -52,6 +52,7 @@ export const updateTimelinesRoute = ( templateTimelineId != null ? await getTemplateTimeline(frameworkRequest, templateTimelineId) : null; + const errorObj = checkIsFailureCases( isHandlingTemplateTimeline, version, diff --git a/x-pack/plugins/security_solution/server/lib/timeline/saved_object.ts b/x-pack/plugins/security_solution/server/lib/timeline/saved_object.ts index dfbf273cbdec2..bbb11cd642c4c 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/saved_object.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/saved_object.ts @@ -7,7 +7,7 @@ import { getOr } from 'lodash/fp'; import { SavedObjectsFindOptions } from '../../../../../../src/core/server'; -import { UNAUTHENTICATED_USER } from '../../../common/constants'; +import { UNAUTHENTICATED_USER, disableTemplate } from '../../../common/constants'; import { NoteSavedObject } from '../../../common/types/timeline/note'; import { PinnedEventSavedObject } from '../../../common/types/timeline/pinned_event'; import { @@ -122,7 +122,6 @@ const getTimelineTypeFilter = ( const draftFilter = includeDraft ? `siem-ui-timeline.attributes.status: ${TimelineStatus.draft}` : `not siem-ui-timeline.attributes.status: ${TimelineStatus.draft}`; - return `${typeFilter} and ${draftFilter}`; }; @@ -147,7 +146,7 @@ export const getAllTimeline = async ( * Remove the comment here to enable template timeline and apply the change below * filter: getTimelineTypeFilter(timelineType, false) */ - filter: getTimelineTypeFilter(TimelineType.default, false), + filter: getTimelineTypeFilter(disableTemplate ? TimelineType.default : timelineType, false), sortField: sort != null ? sort.sortField : undefined, sortOrder: sort != null ? sort.sortOrder : undefined, }; @@ -321,7 +320,11 @@ const updatePartialSavedTimeline = async ( ); }; -export const resetTimeline = async (request: FrameworkRequest, timelineIds: string[]) => { +export const resetTimeline = async ( + request: FrameworkRequest, + timelineIds: string[], + timelineType: TimelineType +) => { if (!timelineIds.length) { return Promise.reject(new Error('timelineIds is empty')); } @@ -337,7 +340,7 @@ export const resetTimeline = async (request: FrameworkRequest, timelineIds: stri const response = await Promise.all( timelineIds.map((timelineId) => - updatePartialSavedTimeline(request, timelineId, draftTimelineDefaults) + updatePartialSavedTimeline(request, timelineId, { ...draftTimelineDefaults, timelineType }) ) ); diff --git a/x-pack/plugins/security_solution/server/utils/read_stream/create_stream_from_ndjson.test.ts b/x-pack/plugins/security_solution/server/utils/read_stream/create_stream_from_ndjson.test.ts index 2b5b34edca140..ca2f881d6abd8 100644 --- a/x-pack/plugins/security_solution/server/utils/read_stream/create_stream_from_ndjson.test.ts +++ b/x-pack/plugins/security_solution/server/utils/read_stream/create_stream_from_ndjson.test.ts @@ -4,10 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ import { transformDataToNdjson } from './create_stream_from_ndjson'; -import { ImportRuleAlertRest } from '../../lib/detection_engine/types'; import { sampleRule } from '../../lib/detection_engine/signals/__mocks__/es_results'; +import { ImportRulesSchemaDecoded } from '../../../common/detection_engine/schemas/request/import_rules_schema'; -export const getOutputSample = (): Partial => ({ +export const getOutputSample = (): Partial => ({ rule_id: 'rule-1', output_index: '.siem-signals', risk_score: 50, @@ -21,7 +21,7 @@ export const getOutputSample = (): Partial => ({ type: 'query', }); -export const getSampleAsNdjson = (sample: Partial): string => { +export const getSampleAsNdjson = (sample: Partial): string => { return `${JSON.stringify(sample)}\n`; }; diff --git a/x-pack/plugins/security_solution/server/utils/read_stream/create_stream_from_ndjson.ts b/x-pack/plugins/security_solution/server/utils/read_stream/create_stream_from_ndjson.ts index 7da9fbcfb7662..f455ac0696e4e 100644 --- a/x-pack/plugins/security_solution/server/utils/read_stream/create_stream_from_ndjson.ts +++ b/x-pack/plugins/security_solution/server/utils/read_stream/create_stream_from_ndjson.ts @@ -5,9 +5,17 @@ */ import { Transform } from 'stream'; import { has, isString } from 'lodash/fp'; -import { ImportRuleAlertRest } from '../../lib/detection_engine/types'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { fold } from 'fp-ts/lib/Either'; +import * as t from 'io-ts'; +import { importRuleValidateTypeDependents } from '../../../common/detection_engine/schemas/request/import_rules_type_dependents'; +import { + ImportRulesSchemaDecoded, + importRulesSchema, + ImportRulesSchema, +} from '../../../common/detection_engine/schemas/request/import_rules_schema'; +import { exactCheck } from '../../../common/exact_check'; import { createMapStream, createFilterStream } from '../../../../../../src/legacy/utils/streams'; -import { importRulesSchema } from '../../lib/detection_engine/routes/schemas/import_rules_schema'; import { BadRequestError } from '../../lib/detection_engine/errors/bad_request_error'; export interface RulesObjectsExportResultDetails { @@ -28,20 +36,28 @@ export const parseNdjsonStrings = (): Transform => { }; export const filterExportedCounts = (): Transform => { - return createFilterStream( + return createFilterStream( (obj) => obj != null && !has('exported_count', obj) ); }; export const validateRules = (): Transform => { - return createMapStream((obj: ImportRuleAlertRest) => { + return createMapStream((obj: ImportRulesSchema) => { if (!(obj instanceof Error)) { - const validated = importRulesSchema.validate(obj); - if (validated.error != null) { - return new BadRequestError(validated.error.message); - } else { - return validated.value; - } + const decoded = importRulesSchema.decode(obj); + const checked = exactCheck(obj, decoded); + const onLeft = (errors: t.Errors): BadRequestError | ImportRulesSchemaDecoded => { + return new BadRequestError(errors.join()); + }; + const onRight = (schema: ImportRulesSchema): BadRequestError | ImportRulesSchemaDecoded => { + const validationErrors = importRuleValidateTypeDependents(schema); + if (validationErrors.length) { + return new BadRequestError(validationErrors.join()); + } else { + return schema as ImportRulesSchemaDecoded; + } + }; + return pipe(checked, fold(onLeft, onRight)); } else { return obj; } diff --git a/x-pack/plugins/transform/public/app/common/pivot_aggs.test.ts b/x-pack/plugins/transform/public/app/common/pivot_aggs.test.ts index ab00211313d62..9e748068742f3 100644 --- a/x-pack/plugins/transform/public/app/common/pivot_aggs.test.ts +++ b/x-pack/plugins/transform/public/app/common/pivot_aggs.test.ts @@ -44,4 +44,29 @@ describe('getAggConfigFromEsAgg', () => { }, }); }); + + test('should resolve sub-aggregations', () => { + const esConfig = { + filter: { + term: { region: 'sa-west-1' }, + }, + aggs: { + test_avg: { + avg: { + field: 'test_field', + }, + }, + }, + }; + + const result = getAggConfigFromEsAgg(esConfig, 'test_3'); + + expect(result.subAggs!.test_avg).toEqual({ + agg: 'avg', + aggName: 'test_avg', + dropDownName: 'test_avg', + field: 'test_field', + parentAgg: result, + }); + }); }); diff --git a/x-pack/plugins/transform/public/app/common/pivot_aggs.ts b/x-pack/plugins/transform/public/app/common/pivot_aggs.ts index d6b3fb974783d..54dfd9ecda7b1 100644 --- a/x-pack/plugins/transform/public/app/common/pivot_aggs.ts +++ b/x-pack/plugins/transform/public/app/common/pivot_aggs.ts @@ -79,17 +79,32 @@ export type PivotAggDict = { [key in AggName]: PivotAgg; }; +/** + * The maximum level of sub-aggregations + */ +export const MAX_NESTING_SUB_AGGS = 10; + // The internal representation of an aggregation definition. export interface PivotAggsConfigBase { agg: PivotSupportedAggs; aggName: AggName; dropDownName: string; + /** Indicates if aggregation supports sub-aggregations */ + isSubAggsSupported?: boolean; + /** Dictionary of the sub-aggregations */ + subAggs?: PivotAggsConfigDict; + /** Reference to the parent aggregation */ + parentAgg?: PivotAggsConfig; } /** * Resolves agg UI config from provided ES agg definition */ -export function getAggConfigFromEsAgg(esAggDefinition: Record, aggName: string) { +export function getAggConfigFromEsAgg( + esAggDefinition: Record, + aggName: string, + parentRef?: PivotAggsConfig +) { const aggKeys = Object.keys(esAggDefinition); // Find the main aggregation key @@ -108,12 +123,21 @@ export function getAggConfigFromEsAgg(esAggDefinition: Record, aggN const config = getAggFormConfig(agg, commonConfig); + if (parentRef) { + config.parentAgg = parentRef; + } + if (isPivotAggsWithExtendedForm(config)) { config.setUiConfigFromEs(esAggDefinition[agg]); } if (aggKeys.includes('aggs')) { - // TODO process sub-aggregation + config.subAggs = {}; + for (const [subAggName, subAggConfigs] of Object.entries( + esAggDefinition.aggs as Record + )) { + config.subAggs[subAggName] = getAggConfigFromEsAgg(subAggConfigs, subAggName, config); + } } return config; @@ -199,6 +223,7 @@ export function getEsAggFromAggConfig( delete esAgg.agg; delete esAgg.aggName; delete esAgg.dropDownName; + delete esAgg.parentAgg; if (isPivotAggsWithExtendedForm(pivotAggsConfig)) { esAgg = pivotAggsConfig.getEsAggConfig(); @@ -208,7 +233,20 @@ export function getEsAggFromAggConfig( } } - return { + const result = { [pivotAggsConfig.agg]: esAgg, }; + + if ( + isPivotAggsConfigWithUiSupport(pivotAggsConfig) && + pivotAggsConfig.subAggs !== undefined && + Object.keys(pivotAggsConfig.subAggs).length > 0 + ) { + result.aggs = {}; + for (const subAggConfig of Object.values(pivotAggsConfig.subAggs)) { + result.aggs[subAggConfig.aggName] = getEsAggFromAggConfig(subAggConfig); + } + } + + return result; } diff --git a/x-pack/plugins/transform/public/app/hooks/use_pivot_data.ts b/x-pack/plugins/transform/public/app/hooks/use_pivot_data.ts index 6266defc01e16..13544b80ed1b2 100644 --- a/x-pack/plugins/transform/public/app/hooks/use_pivot_data.ts +++ b/x-pack/plugins/transform/public/app/hooks/use_pivot_data.ts @@ -31,12 +31,25 @@ import { PivotGroupByConfig, PivotQuery, PreviewMappings, + PivotAggsConfig, } from '../common'; import { SearchItems } from './use_search_items'; import { useApi } from './use_api'; import { isPivotAggsWithExtendedForm } from '../common/pivot_aggs'; +/** + * Checks if the aggregations collection is invalid. + */ +function isConfigInvalid(aggsArray: PivotAggsConfig[]): boolean { + return aggsArray.some((agg) => { + return ( + (isPivotAggsWithExtendedForm(agg) && !agg.isValid()) || + (agg.subAggs && isConfigInvalid(Object.values(agg.subAggs))) + ); + }); +} + function sortColumns(groupByArr: PivotGroupByConfig[]) { return (a: string, b: string) => { // make sure groupBy fields are always most left columns @@ -62,7 +75,7 @@ export const usePivotData = ( const [previewMappings, setPreviewMappings] = useState({ properties: {} }); const api = useApi(); - const aggsArr = dictionaryToArray(aggs); + const aggsArr = useMemo(() => dictionaryToArray(aggs), [aggs]); const groupByArr = dictionaryToArray(groupBy); // Filters mapping properties of type `object`, which get returned for nested field parents. @@ -136,11 +149,7 @@ export const usePivotData = ( return; } - const isConfigInvalid = aggsArr.some( - (agg) => isPivotAggsWithExtendedForm(agg) && !agg.isValid() - ); - - if (isConfigInvalid) { + if (isConfigInvalid(aggsArr)) { return; } @@ -185,7 +194,7 @@ export const usePivotData = ( /* eslint-disable react-hooks/exhaustive-deps */ }, [ indexPatternTitle, - JSON.stringify(aggsArr), + aggsArr, JSON.stringify(groupByArr), JSON.stringify(query), /* eslint-enable react-hooks/exhaustive-deps */ diff --git a/x-pack/plugins/transform/public/app/sections/create_transform/components/aggregation_dropdown/dropdown.tsx b/x-pack/plugins/transform/public/app/sections/create_transform/components/aggregation_dropdown/dropdown.tsx index e5381f09713b5..c28588f727e97 100644 --- a/x-pack/plugins/transform/public/app/sections/create_transform/components/aggregation_dropdown/dropdown.tsx +++ b/x-pack/plugins/transform/public/app/sections/create_transform/components/aggregation_dropdown/dropdown.tsx @@ -13,6 +13,7 @@ interface Props { placeholder?: string; changeHandler(d: EuiComboBoxOptionOption[]): void; testSubj?: string; + isDisabled?: boolean; } export const DropDown: React.FC = ({ @@ -20,6 +21,7 @@ export const DropDown: React.FC = ({ options, placeholder = 'Search ...', testSubj, + isDisabled, }) => { return ( = ({ onChange={changeHandler} isClearable={false} data-test-subj={testSubj} + isDisabled={isDisabled} /> ); }; diff --git a/x-pack/plugins/transform/public/app/sections/create_transform/components/aggregation_list/__snapshots__/agg_label_form.test.tsx.snap b/x-pack/plugins/transform/public/app/sections/create_transform/components/aggregation_list/__snapshots__/agg_label_form.test.tsx.snap index ed32fb3d6ad5f..10258f53aa25b 100644 --- a/x-pack/plugins/transform/public/app/sections/create_transform/components/aggregation_list/__snapshots__/agg_label_form.test.tsx.snap +++ b/x-pack/plugins/transform/public/app/sections/create_transform/components/aggregation_list/__snapshots__/agg_label_form.test.tsx.snap @@ -1,70 +1,72 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Transform: Date histogram aggregation 1`] = ` - - + - - the-group-by-agg-name - - - - - } - closePopover={[Function]} - display="inlineBlock" - hasArrow={true} - id="transformFormPopover" - isOpen={false} - ownFocus={true} - panelPaddingSize="m" + + the-group-by-agg-name + + + - } - onChange={[Function]} - options={Object {}} - otherAggNames={Array []} + closePopover={[Function]} + display="inlineBlock" + hasArrow={true} + id="transformFormPopover" + isOpen={false} + ownFocus={true} + panelPaddingSize="m" + > + + + + + - - - - - - + + + `; diff --git a/x-pack/plugins/transform/public/app/sections/create_transform/components/aggregation_list/__snapshots__/list_form.test.tsx.snap b/x-pack/plugins/transform/public/app/sections/create_transform/components/aggregation_list/__snapshots__/list_form.test.tsx.snap index 3134af4c8b21d..89b54e6d0a22f 100644 --- a/x-pack/plugins/transform/public/app/sections/create_transform/components/aggregation_list/__snapshots__/list_form.test.tsx.snap +++ b/x-pack/plugins/transform/public/app/sections/create_transform/components/aggregation_list/__snapshots__/list_form.test.tsx.snap @@ -3,7 +3,7 @@ exports[`Transform: Minimal initialization 1`] = ` = ({ const helperText = isPivotAggsWithExtendedForm(item) && item.helperText && item.helperText(); + const isSubAggSupported = + isPivotAggsConfigWithUiSupport(item) && + item.isSubAggsSupported && + (isPivotAggsWithExtendedForm(item) ? item.isValid() : true); + return ( - - - - {item.aggName} - - - {helperText && ( - - - {helperText} - + <> + + + + {item.aggName} + - )} - - setPopoverVisibility(!isPopoverVisible)} - data-test-subj="transformAggregationEntryEditButton" + {helperText && ( + + + {helperText} + + + )} + + setPopoverVisibility(!isPopoverVisible)} + data-test-subj="transformAggregationEntryEditButton" + /> + } + isOpen={isPopoverVisible} + closePopover={() => setPopoverVisibility(false)} + > + - } - isOpen={isPopoverVisible} - closePopover={() => setPopoverVisibility(false)} - > - + + + deleteHandler(item.aggName)} + data-test-subj="transformAggregationEntryDeleteButton" /> - - - - deleteHandler(item.aggName)} - data-test-subj="transformAggregationEntryDeleteButton" - /> - - + + + + {isSubAggSupported && } + ); }; diff --git a/x-pack/plugins/transform/public/app/sections/create_transform/components/aggregation_list/list_form.tsx b/x-pack/plugins/transform/public/app/sections/create_transform/components/aggregation_list/list_form.tsx index cbcb6c668b58a..a02f4455250d7 100644 --- a/x-pack/plugins/transform/public/app/sections/create_transform/components/aggregation_list/list_form.tsx +++ b/x-pack/plugins/transform/public/app/sections/create_transform/components/aggregation_list/list_form.tsx @@ -32,7 +32,7 @@ export const AggListForm: React.FC = ({ deleteHandler, list, onCha const otherAggNames = listKeys.filter((k) => k !== aggName); return ( - + = ({ item }) => { + const { state, actions } = useContext(PivotConfigurationContext)!; + + const addSubAggHandler = useCallback( + (d: EuiComboBoxOptionOption[]) => { + actions.addSubAggregation(item, d); + }, + [actions, item] + ); + + const updateSubAggHandler = useCallback( + (prevSubItemName: string, subItem: PivotAggsConfig) => { + actions.updateSubAggregation(prevSubItemName, subItem); + }, + [actions] + ); + + const deleteSubAggHandler = useCallback( + (subAggName: string) => { + actions.deleteSubAggregation(item, subAggName); + }, + [actions, item] + ); + + const isNewSubAggAllowed: boolean = useMemo(() => { + let nestingLevel = 1; + let parentItem = item.parentAgg; + while (parentItem !== undefined) { + nestingLevel++; + parentItem = parentItem.parentAgg; + } + return nestingLevel <= MAX_NESTING_SUB_AGGS; + }, [item]); + + const dropdown = ( + + ); + + return ( + <> + + {item.subAggs && ( + + )} + {isNewSubAggAllowed ? ( + dropdown + ) : ( + + } + > + {dropdown} + + )} + + ); +}; diff --git a/x-pack/plugins/transform/public/app/sections/create_transform/components/pivot_configuration/pivot_configuration.tsx b/x-pack/plugins/transform/public/app/sections/create_transform/components/pivot_configuration/pivot_configuration.tsx index 5de35a683a376..a3a2e7c4eadfa 100644 --- a/x-pack/plugins/transform/public/app/sections/create_transform/components/pivot_configuration/pivot_configuration.tsx +++ b/x-pack/plugins/transform/public/app/sections/create_transform/components/pivot_configuration/pivot_configuration.tsx @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { isEqual } from 'lodash'; -import React, { memo, FC } from 'react'; +import React, { memo, FC, createContext } from 'react'; import { EuiFormRow } from '@elastic/eui'; @@ -16,20 +15,32 @@ import { DropDown } from '../aggregation_dropdown'; import { GroupByListForm } from '../group_by_list'; import { StepDefineFormHook } from '../step_define'; +export const PivotConfigurationContext = createContext< + StepDefineFormHook['pivotConfig'] | undefined +>(undefined); + export const PivotConfiguration: FC = memo( - ({ - actions: { + ({ actions, state }) => { + const { addAggregation, addGroupBy, deleteAggregation, deleteGroupBy, updateAggregation, updateGroupBy, - }, - state: { aggList, aggOptions, aggOptionsData, groupByList, groupByOptions, groupByOptionsData }, - }) => { + } = actions; + + const { + aggList, + aggOptions, + aggOptionsData, + groupByList, + groupByOptions, + groupByOptionsData, + } = state; + return ( - <> + = memo( /> - + ); - }, - (prevProps, nextProps) => { - return isEqual(prevProps.state, nextProps.state); } ); diff --git a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_agg_form.test.tsx b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_agg_form.test.tsx index 7e23e799ae32e..35f9734a59482 100644 --- a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_agg_form.test.tsx +++ b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_agg_form.test.tsx @@ -42,7 +42,7 @@ describe('FilterAggForm', () => { ); - expect(getByLabelText('Filter agg')).toBeInTheDocument(); + expect(getByLabelText('Filter query')).toBeInTheDocument(); const { options } = (await findByTestId('transformFilterAggTypeSelector')) as HTMLSelectElement; diff --git a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_agg_form.tsx b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_agg_form.tsx index 3e67a16e3c1ed..ac6e93d3ed5eb 100644 --- a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_agg_form.tsx +++ b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_agg_form.tsx @@ -62,7 +62,7 @@ export const FilterAggForm: PivotAggsConfigFilter['AggFormComponent'] = ({ label={ } > diff --git a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_range_form.tsx b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_range_form.tsx index cfc6bb27c88a1..7f6c23dddb9fc 100644 --- a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_range_form.tsx +++ b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_range_form.tsx @@ -60,7 +60,8 @@ export const FilterRangeForm: FilterAggConfigRange['aggTypeConfig']['FilterAggFo onChange={(e) => { updateConfig({ from: e.target.value === '' ? undefined : Number(e.target.value) }); }} - step={0.1} + // @ts-ignore + step="any" prepend={ { updateConfig({ to: e.target.value === '' ? undefined : Number(e.target.value) }); }} - step={0.1} + // @ts-ignore + step="any" append={ { // Simulate initial load. onSearchChange(''); + return () => { + // make sure the ongoing request is canceled + fetchOptions.cancel(); + }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); @@ -115,7 +117,6 @@ export const FilterTermForm: FilterAggConfigTerm['aggTypeConfig']['FilterAggForm value: undefined, }, }); - // eslint-disable-next-line react-hooks/exhaustive-deps }, [selectedField]); const selectedOptions = config?.value ? [{ label: config.value }] : undefined; diff --git a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/config.ts b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/config.ts index 8602a82db8f2f..d8b37b25f50d1 100644 --- a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/config.ts +++ b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/config.ts @@ -30,6 +30,7 @@ export function getFilterAggConfig( ): PivotAggsConfigFilter { return { ...commonConfig, + isSubAggsSupported: true, field: isPivotAggsConfigWithUiSupport(commonConfig) ? commonConfig.field : '', AggFormComponent: FilterAggForm, aggConfig: {}, diff --git a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/hooks/use_pivot_config.ts b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/hooks/use_pivot_config.ts index 72bfbe369757b..d35d567fc8469 100644 --- a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/hooks/use_pivot_config.ts +++ b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/hooks/use_pivot_config.ts @@ -4,12 +4,18 @@ * you may not use this file except in compliance with the Elastic License. */ -import { useState } from 'react'; +import { useCallback, useMemo, useState } from 'react'; import { dictionaryToArray } from '../../../../../../../common/types/common'; import { useToastNotifications } from '../../../../../app_dependencies'; -import { AggName, DropDownLabel, PivotAggsConfig, PivotGroupByConfig } from '../../../../../common'; +import { + AggName, + DropDownLabel, + PivotAggsConfig, + PivotAggsConfigDict, + PivotGroupByConfig, +} from '../../../../../common'; import { getAggNameConflictToastMessages, @@ -18,136 +24,297 @@ import { } from '../common'; import { StepDefineFormProps } from '../step_define_form'; +/** + * Clones aggregation configuration and updates parent references + * for the sub-aggregations. + */ +function cloneAggItem(item: PivotAggsConfig, parentRef?: PivotAggsConfig) { + const newItem = { ...item }; + if (parentRef !== undefined) { + newItem.parentAgg = parentRef; + } + if (newItem.subAggs !== undefined) { + const newSubAggs: PivotAggsConfigDict = {}; + for (const [key, subItem] of Object.entries(newItem.subAggs)) { + newSubAggs[key] = cloneAggItem(subItem, newItem); + } + newItem.subAggs = newSubAggs; + } + return newItem; +} + +/** + * Returns a root aggregation configuration + * for provided aggregation item. + */ +function getRootAggregation(item: PivotAggsConfig) { + let rootItem = item; + while (rootItem.parentAgg !== undefined) { + rootItem = rootItem.parentAgg; + } + return rootItem; +} + export const usePivotConfig = ( defaults: StepDefineExposedState, indexPattern: StepDefineFormProps['searchItems']['indexPattern'] ) => { const toastNotifications = useToastNotifications(); - const { - aggOptions, - aggOptionsData, - groupByOptions, - groupByOptionsData, - } = getPivotDropdownOptions(indexPattern); + const { aggOptions, aggOptionsData, groupByOptions, groupByOptionsData } = useMemo( + () => getPivotDropdownOptions(indexPattern), + [indexPattern] + ); + // The list of selected aggregations + const [aggList, setAggList] = useState(defaults.aggList); // The list of selected group by fields const [groupByList, setGroupByList] = useState(defaults.groupByList); - const addGroupBy = (d: DropDownLabel[]) => { - const label: AggName = d[0].label; - const config: PivotGroupByConfig = groupByOptionsData[label]; - const aggName: AggName = config.aggName; + const addGroupBy = useCallback( + (d: DropDownLabel[]) => { + const label: AggName = d[0].label; + const config: PivotGroupByConfig = groupByOptionsData[label]; + const aggName: AggName = config.aggName; - const aggNameConflictMessages = getAggNameConflictToastMessages(aggName, aggList, groupByList); - if (aggNameConflictMessages.length > 0) { - aggNameConflictMessages.forEach((m) => toastNotifications.addDanger(m)); - return; - } + const aggNameConflictMessages = getAggNameConflictToastMessages( + aggName, + aggList, + groupByList + ); + if (aggNameConflictMessages.length > 0) { + aggNameConflictMessages.forEach((m) => toastNotifications.addDanger(m)); + return; + } - groupByList[aggName] = config; - setGroupByList({ ...groupByList }); - }; - - const updateGroupBy = (previousAggName: AggName, item: PivotGroupByConfig) => { - const groupByListWithoutPrevious = { ...groupByList }; - delete groupByListWithoutPrevious[previousAggName]; - - const aggNameConflictMessages = getAggNameConflictToastMessages( - item.aggName, - aggList, - groupByListWithoutPrevious - ); - if (aggNameConflictMessages.length > 0) { - aggNameConflictMessages.forEach((m) => toastNotifications.addDanger(m)); - return; - } + groupByList[aggName] = config; + setGroupByList({ ...groupByList }); + }, + [aggList, groupByList, groupByOptionsData, toastNotifications] + ); - groupByListWithoutPrevious[item.aggName] = item; - setGroupByList(groupByListWithoutPrevious); - }; + const updateGroupBy = useCallback( + (previousAggName: AggName, item: PivotGroupByConfig) => { + const groupByListWithoutPrevious = { ...groupByList }; + delete groupByListWithoutPrevious[previousAggName]; - const deleteGroupBy = (aggName: AggName) => { - delete groupByList[aggName]; - setGroupByList({ ...groupByList }); - }; + const aggNameConflictMessages = getAggNameConflictToastMessages( + item.aggName, + aggList, + groupByListWithoutPrevious + ); + if (aggNameConflictMessages.length > 0) { + aggNameConflictMessages.forEach((m) => toastNotifications.addDanger(m)); + return; + } - // The list of selected aggregations - const [aggList, setAggList] = useState(defaults.aggList); + groupByListWithoutPrevious[item.aggName] = item; + setGroupByList(groupByListWithoutPrevious); + }, + [aggList, groupByList, toastNotifications] + ); + + const deleteGroupBy = useCallback( + (aggName: AggName) => { + delete groupByList[aggName]; + setGroupByList({ ...groupByList }); + }, + [groupByList] + ); /** * Adds an aggregation to the list. */ - const addAggregation = (d: DropDownLabel[]) => { - const label: AggName = d[0].label; - const config: PivotAggsConfig = aggOptionsData[label]; - const aggName: AggName = config.aggName; - - const aggNameConflictMessages = getAggNameConflictToastMessages(aggName, aggList, groupByList); - if (aggNameConflictMessages.length > 0) { - aggNameConflictMessages.forEach((m) => toastNotifications.addDanger(m)); - return; - } + const addAggregation = useCallback( + (d: DropDownLabel[]) => { + const label: AggName = d[0].label; + const config: PivotAggsConfig = aggOptionsData[label]; + const aggName: AggName = config.aggName; + + const aggNameConflictMessages = getAggNameConflictToastMessages( + aggName, + aggList, + groupByList + ); + if (aggNameConflictMessages.length > 0) { + aggNameConflictMessages.forEach((m) => toastNotifications.addDanger(m)); + return; + } - aggList[aggName] = config; - setAggList({ ...aggList }); - }; + aggList[aggName] = config; + setAggList({ ...aggList }); + }, + [aggList, aggOptionsData, groupByList, toastNotifications] + ); /** * Adds updated aggregation to the list */ - const updateAggregation = (previousAggName: AggName, item: PivotAggsConfig) => { - const aggListWithoutPrevious = { ...aggList }; - delete aggListWithoutPrevious[previousAggName]; - - const aggNameConflictMessages = getAggNameConflictToastMessages( - item.aggName, - aggListWithoutPrevious, - groupByList - ); - if (aggNameConflictMessages.length > 0) { - aggNameConflictMessages.forEach((m) => toastNotifications.addDanger(m)); - return; - } + const updateAggregation = useCallback( + (previousAggName: AggName, item: PivotAggsConfig) => { + const aggListWithoutPrevious = { ...aggList }; + delete aggListWithoutPrevious[previousAggName]; + + const aggNameConflictMessages = getAggNameConflictToastMessages( + item.aggName, + aggListWithoutPrevious, + groupByList + ); + if (aggNameConflictMessages.length > 0) { + aggNameConflictMessages.forEach((m) => toastNotifications.addDanger(m)); + return; + } + aggListWithoutPrevious[item.aggName] = item; + setAggList(aggListWithoutPrevious); + }, + [aggList, groupByList, toastNotifications] + ); - aggListWithoutPrevious[item.aggName] = item; - setAggList(aggListWithoutPrevious); - }; + /** + * Adds sub-aggregation to the aggregation item + */ + const addSubAggregation = useCallback( + (item: PivotAggsConfig, d: DropDownLabel[]) => { + if (!item.isSubAggsSupported) { + throw new Error(`Aggregation "${item.agg}" does not support sub-aggregations`); + } + const label: AggName = d[0].label; + const config: PivotAggsConfig = aggOptionsData[label]; + + item.subAggs = item.subAggs ?? {}; + + const aggNameConflictMessages = getAggNameConflictToastMessages( + config.aggName, + item.subAggs, + {} + ); + if (aggNameConflictMessages.length > 0) { + aggNameConflictMessages.forEach((m) => toastNotifications.addDanger(m)); + return; + } + + item.subAggs[config.aggName] = config; + + const newRootItem = cloneAggItem(getRootAggregation(item)); + updateAggregation(newRootItem.aggName, newRootItem); + }, + [aggOptionsData, toastNotifications, updateAggregation] + ); + + /** + * Updates sub-aggregation of the aggregation item + */ + const updateSubAggregation = useCallback( + (prevSubItemName: AggName, subItem: PivotAggsConfig) => { + const parent = subItem.parentAgg; + if (!parent || !parent.subAggs) { + throw new Error('No parent aggregation reference found'); + } + + const { [prevSubItemName]: deleted, ...newSubAgg } = parent.subAggs; + + const aggNameConflictMessages = getAggNameConflictToastMessages( + subItem.aggName, + newSubAgg, + {} + ); + if (aggNameConflictMessages.length > 0) { + aggNameConflictMessages.forEach((m) => toastNotifications.addDanger(m)); + return; + } + + parent.subAggs = { + ...newSubAgg, + [subItem.aggName]: subItem, + }; + const newRootItem = cloneAggItem(getRootAggregation(subItem)); + updateAggregation(newRootItem.aggName, newRootItem); + }, + [toastNotifications, updateAggregation] + ); + + /** + * Deletes sub-aggregation of the aggregation item + */ + const deleteSubAggregation = useCallback( + (item: PivotAggsConfig, subAggName: string) => { + if (!item.subAggs || !item.subAggs[subAggName]) { + throw new Error('Unable to delete a sub-agg'); + } + delete item.subAggs[subAggName]; + const newRootItem = cloneAggItem(getRootAggregation(item)); + updateAggregation(newRootItem.aggName, newRootItem); + }, + [updateAggregation] + ); /** * Deletes aggregation from the list */ - const deleteAggregation = (aggName: AggName) => { - delete aggList[aggName]; - setAggList({ ...aggList }); - }; + const deleteAggregation = useCallback( + (aggName: AggName) => { + delete aggList[aggName]; + setAggList({ ...aggList }); + }, + [aggList] + ); - const pivotAggsArr = dictionaryToArray(aggList); - const pivotGroupByArr = dictionaryToArray(groupByList); + const pivotAggsArr = useMemo(() => dictionaryToArray(aggList), [aggList]); + const pivotGroupByArr = useMemo(() => dictionaryToArray(groupByList), [groupByList]); const valid = pivotGroupByArr.length > 0 && pivotAggsArr.length > 0; - return { - actions: { + const actions = useMemo(() => { + return { addAggregation, addGroupBy, + addSubAggregation, + updateSubAggregation, + deleteSubAggregation, deleteAggregation, deleteGroupBy, setAggList, setGroupByList, updateAggregation, updateGroupBy, - }, - state: { - aggList, - aggOptions, - aggOptionsData, - groupByList, - groupByOptions, - groupByOptionsData, - pivotAggsArr, - pivotGroupByArr, - valid, - }, - }; + }; + }, [ + addAggregation, + addGroupBy, + addSubAggregation, + deleteAggregation, + deleteGroupBy, + deleteSubAggregation, + updateAggregation, + updateGroupBy, + updateSubAggregation, + ]); + + return useMemo(() => { + return { + actions, + state: { + aggList, + aggOptions, + aggOptionsData, + groupByList, + groupByOptions, + groupByOptionsData, + pivotAggsArr, + pivotGroupByArr, + valid, + }, + }; + }, [ + actions, + aggList, + aggOptions, + aggOptionsData, + groupByList, + groupByOptions, + groupByOptionsData, + pivotAggsArr, + pivotGroupByArr, + valid, + ]); }; diff --git a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/hooks/use_step_define_form.ts b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/hooks/use_step_define_form.ts index fc47a9e3d3477..f5980ae2243d3 100644 --- a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/hooks/use_step_define_form.ts +++ b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/hooks/use_step_define_form.ts @@ -73,7 +73,7 @@ export const useStepDefineForm = ({ overrides, onChange, searchItems }: StepDefi }, [ JSON.stringify(advancedPivotEditor.state), JSON.stringify(advancedSourceEditor.state), - JSON.stringify(pivotConfig.state), + pivotConfig.state, JSON.stringify(searchBar.state), /* eslint-enable react-hooks/exhaustive-deps */ ]); diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index aa45fd4bcb292..76636779001e7 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -138,16 +138,6 @@ "charts.controls.rangeErrorMessage": "値は{min}と{max}の間でなければなりません", "charts.controls.vislibBasicOptions.legendPositionLabel": "凡例位置", "charts.controls.vislibBasicOptions.showTooltipLabel": "ツールヒントを表示", - "common.ui.errorUrlOverflow.breadcrumbs.errorText": "エラー", - "common.ui.errorUrlOverflow.errorDescription": "とても長い URL ですね。残念なお知らせがあります。ご使用のブラウザは Kibana の超巨大 URL に対応していません。問題を避けるため、Kibana はご使用のブラウザでの URL を {urlCharacterLimit} 文字に制限します。", - "common.ui.errorUrlOverflow.errorTitle": "おっと!", - "common.ui.errorUrlOverflow.footnoteText": "脚注:パーティーサイズのキャンディバーはほんのちょこっと。パーティーサイズのロールサンドイッチは巨大。不思議なものですね。", - "common.ui.errorUrlOverflow.howTofixError.doNotUseIEText": "IE は避けましょう。他の対応ブラウザにはこの制限がありません。", - "common.ui.errorUrlOverflow.howTofixError.enableOptionText": "{kibanaSettingsLink} の {storeInSessionStorageConfig} オプションを有効にしてください。これにより URL が長くなるのを避けられますが、若干ポータビリティが損なわれます。", - "common.ui.errorUrlOverflow.howTofixError.enableOptionText.advancedSettingsLinkText": "高度な設定", - "common.ui.errorUrlOverflow.howTofixError.removeStuffFromDashboardText": "ダッシュボードからいくつか項目を取り除きましょう。これにより URL が短くなり、IE の動作が改善されます。", - "common.ui.errorUrlOverflow.howTofixErrorDescription": "これは大抵大規模で複雑なダッシュボードで起こるため、いくつかのオプションがあります。", - "common.ui.errorUrlOverflow.howTofixErrorTitle": "どうすれば良いのでしょう?", "common.ui.flotCharts.aprLabel": "4 月", "common.ui.flotCharts.augLabel": "8 月", "common.ui.flotCharts.decLabel": "12 月", @@ -2177,9 +2167,9 @@ "kbn.advancedSettings.visualization.tileMap.wmsDefaultsTitle": "デフォルトの WMS プロパティ", "visualizations.advancedSettings.visualizeEnableLabsText": "ユーザーが実験的なビジュアライゼーションを作成、表示、編集できるようになります。無効の場合、\n ユーザーは本番準備が整ったビジュアライゼーションのみを利用できます。", "visualizations.advancedSettings.visualizeEnableLabsTitle": "実験的なビジュアライゼーションを有効にする", - "kibana_legacy.bigUrlWarningNotificationMessage": "{advancedSettingsLink}で{storeInSessionStorageParam}オプションを有効にするか、オンスクリーンビジュアルを簡素化してください。", - "kibana_legacy.bigUrlWarningNotificationMessage.advancedSettingsLinkText": "高度な設定", - "kibana_legacy.bigUrlWarningNotificationTitle": "URLが大きく、Kibanaの動作が停止する可能性があります", + "core.ui.errorUrlOverflow.bigUrlWarningNotificationMessage": "{advancedSettingsLink}で{storeInSessionStorageParam}オプションを有効にするか、オンスクリーンビジュアルを簡素化してください。", + "core.ui.errorUrlOverflow.bigUrlWarningNotificationMessage.advancedSettingsLinkText": "高度な設定", + "core.ui.errorUrlOverflow.bigUrlWarningNotificationTitle": "URLが大きく、Kibanaの動作が停止する可能性があります", "kibana_legacy.notify.fatalError.errorStatusMessage": "エラー {errStatus} {errStatusText}: {errMessage}", "kibana_legacy.notify.fatalError.unavailableServerErrorMessage": "HTTP リクエストで接続に失敗しました。Kibana サーバーが実行されていて、ご使用のブラウザの接続が正常に動作していることを確認するか、システム管理者にお問い合わせください。", "kibana_legacy.notify.toaster.errorMessage": "エラー: {errorMessage}\n {errorStack}", @@ -8372,7 +8362,6 @@ "xpack.ingestManager.enrollmentTokensList.newKeyButton": "新しい登録トークン", "xpack.ingestManager.enrollmentTokensList.pageDescription": "これは、エージェントを登録するために使用できる登録トークンのリストです。", "xpack.ingestManager.enrollmentTokensList.secretTitle": "シークレット", - "xpack.ingestManager.epm.addDatasourceButtonText": "データソースを作成", "xpack.ingestManager.epm.browseAllButtonText": "すべての統合を参照", "xpack.ingestManager.epm.illustrationAltText": "Elastic統合の例", "xpack.ingestManager.epm.pageSubtitle": "一般的なアプリやサービスの統合を参照する", @@ -9665,7 +9654,6 @@ "xpack.ml.dataframe.analytics.classificationExploration.showActions": "アクションを表示", "xpack.ml.dataframe.analytics.classificationExploration.showAllColumns": "すべての列を表示", "xpack.ml.dataframe.analytics.classificationExploration.tableJobIdTitle": "分類ジョブID {jobId}のデスティネーションインデックス", - "xpack.ml.dataframe.analytics.clone.flyoutHeaderTitle": "{job_id} からのジョブのクローンを作成", "xpack.ml.dataframe.analytics.create.advancedEditor.codeEditorAriaLabel": "高度な分析ジョブエディター", "xpack.ml.dataframe.analytics.create.advancedEditor.configRequestBody": "構成リクエスト本文", "xpack.ml.dataframe.analytics.create.advancedEditor.jobIdExistsError": "このIDの分析ジョブが既に存在します。", @@ -9698,22 +9686,12 @@ "xpack.ml.dataframe.analytics.create.destinationIndexLabel": "デスティネーションインデックス", "xpack.ml.dataframe.analytics.create.duplicateIndexPatternErrorMessage": "Kibanaインデックスパターンの作成中にエラーが発生しました。", "xpack.ml.dataframe.analytics.create.duplicateIndexPatternErrorMessageError": "インデックスパターン{indexPatternName}はすでに作成されています。", - "xpack.ml.dataframe.analytics.create.enableAdvancedEditorHelpText": "高度なエディターからこのフォームには戻れません。", - "xpack.ml.dataframe.analytics.create.enableAdvancedEditorSwitch": "詳細エディターを有効にする", "xpack.ml.dataframe.analytics.create.errorCreatingDataFrameAnalyticsJob": "データフレーム分析ジョブの作成中にエラーが発生しました。", "xpack.ml.dataframe.analytics.create.errorGettingDataFrameAnalyticsList": "既存のデータフレーム分析ジョブIDの取得中にエラーが発生しました。", "xpack.ml.dataframe.analytics.create.errorGettingDataFrameIndexNames": "既存のインデックス名の取得中にエラーが発生しました。", "xpack.ml.dataframe.analytics.create.errorGettingIndexPatternTitles": "既存のインデックスパターンのタイトルの取得中にエラーが発生しました。", "xpack.ml.dataframe.analytics.create.errorStartingDataFrameAnalyticsJob": "データフレーム分析ジョブの開始中にエラーが発生しました。", - "xpack.ml.dataframe.analytics.create.excludedFieldsHelpText": "分析から除外するフィールドを選択してください。他のすべてのサポートされるフィールドが含まれます。", "xpack.ml.dataframe.analytics.create.excludedFieldsLabel": "除外されたフィールド", - "xpack.ml.dataframe.analytics.create.excludesInputAriaLabel": "任意。除外するフィールドを入力または選択してください。", - "xpack.ml.dataframe.analytics.create.excludesOptionsNoSupportedFields": "このインデックスパターンのサポートされている分析フィールドが見つかりませんでした。", - "xpack.ml.dataframe.analytics.create.flyoutCancelButton": "キャンセル", - "xpack.ml.dataframe.analytics.create.flyoutCloseButton": "閉じる", - "xpack.ml.dataframe.analytics.create.flyoutCreateButton": "作成", - "xpack.ml.dataframe.analytics.create.flyoutHeaderTitle": "分析ジョブの作成", - "xpack.ml.dataframe.analytics.create.flyoutStartButton": "開始", "xpack.ml.dataframe.analytics.create.indexPatternAlreadyExistsError": "このタイトルのインデックスパターンが既に存在します。", "xpack.ml.dataframe.analytics.create.indexPatternExistsError": "このタイトルのインデックスパターンが既に存在します。", "xpack.ml.dataframe.analytics.create.jobDescription.helpText": "オプションの説明テキストです", @@ -9734,12 +9712,6 @@ "xpack.ml.dataframe.analytics.create.numTopFeatureImportanceValuesLabel": "機能重要度値", "xpack.ml.dataframe.analytics.create.outlierDetectionHelpText": "外れ値検出ジョブは、表に示すようなデータ構造でマッピングされたソースインデックスを必要とし、数字とブール値フィールドのみを分析します。カスタムオプションを構成に追加するには、詳細エディターを使用します。", "xpack.ml.dataframe.analytics.create.outlierRegressionHelpText": "リグレッションジョブは数値フィールドのみを分析します。予測フィールド名などのカスタムオプションを適用するには、詳細エディターを使用します。", - "xpack.ml.dataframe.analytics.create.sourceIndexFieldCheckError": "数値フィールドの確認中に問題が発生しました。ページを更新して再起動してください。", - "xpack.ml.dataframe.analytics.create.sourceIndexHelpText": "このインデックスパターンには数字タイプのフィールドが含まれていません。分析ジョブで外れ値が検出されない可能性があります。", - "xpack.ml.dataframe.analytics.create.sourceIndexInputAriaLabel": "ソースインデックスパターンまたは検索。", - "xpack.ml.dataframe.analytics.create.sourceIndexInvalidError": "無効なソースインデックス名。スペースや{characterList}を含めることはできません", - "xpack.ml.dataframe.analytics.create.sourceIndexLabel": "ソースインデックス", - "xpack.ml.dataframe.analytics.create.sourceIndexPlaceholder": "ソースインデックスパターンを選択してください。", "xpack.ml.dataframe.analytics.create.startDataFrameAnalyticsSuccessMessage": "データフレーム分析 {jobId} の開始リクエストが受け付けられました。", "xpack.ml.dataframe.analytics.create.trainingPercentLabel": "トレーニングパーセンテージ", "xpack.ml.dataframe.analytics.errorCallout.evaluateErrorTitle": "データの読み込み中にエラーが発生しました。", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 56d373a6fcd2f..331e9d67c3897 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -138,16 +138,6 @@ "charts.controls.rangeErrorMessage": "值必须是在 {min} 到 {max} 的范围内", "charts.controls.vislibBasicOptions.legendPositionLabel": "图例位置", "charts.controls.vislibBasicOptions.showTooltipLabel": "显示工具提示", - "common.ui.errorUrlOverflow.breadcrumbs.errorText": "错误", - "common.ui.errorUrlOverflow.errorDescription": "您的 URL 真不小。我有一些不幸的消息:您的浏览器与 Kibana 的超长 URL 不太兼容。为了避免您遇到问题,Kibana 在您的浏览器中将 URL 长度限制在 {urlCharacterLimit} 个字符。", - "common.ui.errorUrlOverflow.errorTitle": "喔哦!", - "common.ui.errorUrlOverflow.footnoteText": "脚注:聚会供应的糖果真够小的。聚会供应的小三明治真够大的。确实得让您好好想一想。", - "common.ui.errorUrlOverflow.howTofixError.doNotUseIEText": "切勿使用 IE。我们了解的所有其他受支持浏览器都没有这个限制。", - "common.ui.errorUrlOverflow.howTofixError.enableOptionText": "在 {kibanaSettingsLink} 中启用 {storeInSessionStorageConfig} 选项。这会阻止 URL 变长,但会使它们的可移植性差点。", - "common.ui.errorUrlOverflow.howTofixError.enableOptionText.advancedSettingsLinkText": "高级设置", - "common.ui.errorUrlOverflow.howTofixError.removeStuffFromDashboardText": "从您的仪表板中删除一些内容。这回减小 URL 的长度,使 IE 能够处理它。", - "common.ui.errorUrlOverflow.howTofixErrorDescription": "通常只有较大的、复杂的仪表板会发生此问题,因此您会有一些选项:", - "common.ui.errorUrlOverflow.howTofixErrorTitle": "那么,我如何解决此问题?", "common.ui.flotCharts.aprLabel": "四月", "common.ui.flotCharts.augLabel": "八月", "common.ui.flotCharts.decLabel": "十二月", @@ -2180,9 +2170,9 @@ "kbn.advancedSettings.visualization.tileMap.wmsDefaultsTitle": "默认 WMS 属性", "visualizations.advancedSettings.visualizeEnableLabsText": "允许用户创建、查看和编辑实验性可视化。如果禁用,\n 仅被视为生产就绪的可视化可供用户使用。", "visualizations.advancedSettings.visualizeEnableLabsTitle": "启用实验性可视化", - "kibana_legacy.bigUrlWarningNotificationMessage": "在{advancedSettingsLink}中启用“{storeInSessionStorageParam}”选项或简化屏幕视觉效果。", - "kibana_legacy.bigUrlWarningNotificationMessage.advancedSettingsLinkText": "高级设置", - "kibana_legacy.bigUrlWarningNotificationTitle": "URL 过长,Kibana 可能无法工作", + "core.ui.errorUrlOverflow.bigUrlWarningNotificationMessage": "在{advancedSettingsLink}中启用“{storeInSessionStorageParam}”选项或简化屏幕视觉效果。", + "core.ui.errorUrlOverflow.bigUrlWarningNotificationMessage.advancedSettingsLinkText": "高级设置", + "core.ui.errorUrlOverflow.bigUrlWarningNotificationTitle": "URL 过长,Kibana 可能无法工作", "kibana_legacy.notify.fatalError.errorStatusMessage": "错误 {errStatus} {errStatusText}:{errMessage}", "kibana_legacy.notify.fatalError.unavailableServerErrorMessage": "HTTP 请求无法连接。请检查 Kibana 服务器是否正在运行以及您的浏览器是否具有有效的连接,或请联系您的系统管理员。", "kibana_legacy.notify.toaster.errorMessage": "错误:{errorMessage}\n {errorStack}", @@ -8376,7 +8366,6 @@ "xpack.ingestManager.enrollmentTokensList.newKeyButton": "新建注册令牌", "xpack.ingestManager.enrollmentTokensList.pageDescription": "这是可用于注册代理的注册令牌列表。", "xpack.ingestManager.enrollmentTokensList.secretTitle": "密钥", - "xpack.ingestManager.epm.addDatasourceButtonText": "创建数据源", "xpack.ingestManager.epm.browseAllButtonText": "浏览所有集成", "xpack.ingestManager.epm.illustrationAltText": "Elastic 集成的图示", "xpack.ingestManager.epm.pageSubtitle": "浏览集成以了解热门应用和服务。", @@ -9669,7 +9658,6 @@ "xpack.ml.dataframe.analytics.classificationExploration.showActions": "显示操作", "xpack.ml.dataframe.analytics.classificationExploration.showAllColumns": "显示所有列", "xpack.ml.dataframe.analytics.classificationExploration.tableJobIdTitle": "分类作业 ID {jobId} 的目标索引", - "xpack.ml.dataframe.analytics.clone.flyoutHeaderTitle": "从 {job_id} 克隆作业", "xpack.ml.dataframe.analytics.create.advancedEditor.codeEditorAriaLabel": "高级分析作业编辑器", "xpack.ml.dataframe.analytics.create.advancedEditor.configRequestBody": "配置请求正文", "xpack.ml.dataframe.analytics.create.advancedEditor.jobIdExistsError": "已存在具有此 ID 的分析作业。", @@ -9702,22 +9690,12 @@ "xpack.ml.dataframe.analytics.create.destinationIndexLabel": "目标 IP", "xpack.ml.dataframe.analytics.create.duplicateIndexPatternErrorMessage": "创建 Kibana 索引模式时发生错误:", "xpack.ml.dataframe.analytics.create.duplicateIndexPatternErrorMessageError": "索引模式 {indexPatternName} 已存在。", - "xpack.ml.dataframe.analytics.create.enableAdvancedEditorHelpText": "您不能从高级编辑器切回到此表单。", - "xpack.ml.dataframe.analytics.create.enableAdvancedEditorSwitch": "启用高级编辑器", "xpack.ml.dataframe.analytics.create.errorCreatingDataFrameAnalyticsJob": "创建数据帧分析作业时发生错误:", "xpack.ml.dataframe.analytics.create.errorGettingDataFrameAnalyticsList": "获取现有数据帧分析作业 ID 时发生错误:", "xpack.ml.dataframe.analytics.create.errorGettingDataFrameIndexNames": "获取现有索引名称时发生错误:", "xpack.ml.dataframe.analytics.create.errorGettingIndexPatternTitles": "获取现有索引模式标题时发生错误:", "xpack.ml.dataframe.analytics.create.errorStartingDataFrameAnalyticsJob": "启动数据帧分析作业时发生错误:", - "xpack.ml.dataframe.analytics.create.excludedFieldsHelpText": "选择要从分析中排除的字段。包括所有其他支持的字段。", "xpack.ml.dataframe.analytics.create.excludedFieldsLabel": "排除的字段", - "xpack.ml.dataframe.analytics.create.excludesInputAriaLabel": "可选。输入或选择要排除的字段。", - "xpack.ml.dataframe.analytics.create.excludesOptionsNoSupportedFields": "没有为此索引模式找到任何支持的分析字段。", - "xpack.ml.dataframe.analytics.create.flyoutCancelButton": "取消", - "xpack.ml.dataframe.analytics.create.flyoutCloseButton": "关闭", - "xpack.ml.dataframe.analytics.create.flyoutCreateButton": "创建", - "xpack.ml.dataframe.analytics.create.flyoutHeaderTitle": "创建分析作业", - "xpack.ml.dataframe.analytics.create.flyoutStartButton": "开始", "xpack.ml.dataframe.analytics.create.indexPatternAlreadyExistsError": "具有此名称的索引模式已存在。", "xpack.ml.dataframe.analytics.create.indexPatternExistsError": "具有此名称的索引模式已存在。", "xpack.ml.dataframe.analytics.create.jobDescription.helpText": "可选的描述文本", @@ -9738,12 +9716,6 @@ "xpack.ml.dataframe.analytics.create.numTopFeatureImportanceValuesLabel": "功能重要性值", "xpack.ml.dataframe.analytics.create.outlierDetectionHelpText": "离群值检测作业需要映射为表状数据结构的源索引,并仅分析数值和布尔值字段。使用高级编辑器将定制选项添加到配置。", "xpack.ml.dataframe.analytics.create.outlierRegressionHelpText": "回归作业仅分析数值字段。使用高级编辑器来应用定制选项,如预测字段名称。", - "xpack.ml.dataframe.analytics.create.sourceIndexFieldCheckError": "检查数值字段时出现问题。请刷新页面并重试。", - "xpack.ml.dataframe.analytics.create.sourceIndexHelpText": "此索引模式不包含任何数值类型字段。分析作业可能无法提供任何离群值。", - "xpack.ml.dataframe.analytics.create.sourceIndexInputAriaLabel": "源索引模式或搜索。", - "xpack.ml.dataframe.analytics.create.sourceIndexInvalidError": "源索引名称无效,其不能包含空格或以下字符:{characterList}", - "xpack.ml.dataframe.analytics.create.sourceIndexLabel": "源索引", - "xpack.ml.dataframe.analytics.create.sourceIndexPlaceholder": "选择源索引模式。", "xpack.ml.dataframe.analytics.create.startDataFrameAnalyticsSuccessMessage": "数据帧分析 {jobId} 启动请求已确认。", "xpack.ml.dataframe.analytics.create.trainingPercentLabel": "训练百分比", "xpack.ml.dataframe.analytics.errorCallout.evaluateErrorTitle": "加载数据时出错。", diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_edit_flyout.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_edit_flyout.tsx index 24dead473fb61..cbbbbfaea7ea3 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_edit_flyout.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_edit_flyout.tsx @@ -197,7 +197,7 @@ export const ConnectorEditFlyout = ({ )} @@ -19,7 +24,16 @@ exports[`CertStatus renders expected elements for valid props 1`] = ` class="euiFlexItem euiFlexItem--flexGrowZero" > - OK + OK +
+
+ for 4 months +
+
diff --git a/x-pack/plugins/uptime/public/components/certificates/cert_status.tsx b/x-pack/plugins/uptime/public/components/certificates/cert_status.tsx index e7a86ce98fa3c..ea0a49a4a6c5b 100644 --- a/x-pack/plugins/uptime/public/components/certificates/cert_status.tsx +++ b/x-pack/plugins/uptime/public/components/certificates/cert_status.tsx @@ -5,45 +5,95 @@ */ import React from 'react'; -import { EuiHealth } from '@elastic/eui'; +import moment from 'moment'; +import styled from 'styled-components'; +import { EuiHealth, EuiText } from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { useSelector } from 'react-redux'; import { Cert } from '../../../common/runtime_types'; import { useCertStatus } from '../../hooks'; import * as labels from './translations'; import { CERT_STATUS } from '../../../common/constants'; +import { selectDynamicSettings } from '../../state/selectors'; interface Props { cert: Cert; } +const DateText = styled(EuiText)` + display: inline-block; + margin-left: 5px; +`; + export const CertStatus: React.FC = ({ cert }) => { const certStatus = useCertStatus(cert?.not_after, cert?.not_before); + const dss = useSelector(selectDynamicSettings); + + const relativeDate = moment(cert?.not_after).fromNow(); + if (certStatus === CERT_STATUS.EXPIRING_SOON) { return ( - {labels.EXPIRES_SOON} + + {labels.EXPIRES_SOON} + {' '} + + {relativeDate} + + ); } if (certStatus === CERT_STATUS.EXPIRED) { return ( - {labels.EXPIRED} + + {labels.EXPIRED} + {' '} + + {relativeDate} + + ); } if (certStatus === CERT_STATUS.TOO_OLD) { + const ageThreshold = dss.settings?.certAgeThreshold; + + const oldRelativeDate = moment(cert?.not_before).add(ageThreshold, 'days').fromNow(); + return ( - {labels.TOO_OLD} + + {labels.TOO_OLD} + + {oldRelativeDate} + + ); } + const okRelativeDate = moment(cert?.not_after).fromNow(true); + return ( - {labels.OK} + + {labels.OK} + {' '} + + + + ); }; diff --git a/x-pack/plugins/uptime/server/lib/requests/search/__tests__/refine_potential_matches.test.ts b/x-pack/plugins/uptime/server/lib/requests/search/__tests__/refine_potential_matches.test.ts new file mode 100644 index 0000000000000..283f5fb8909f6 --- /dev/null +++ b/x-pack/plugins/uptime/server/lib/requests/search/__tests__/refine_potential_matches.test.ts @@ -0,0 +1,112 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { fullyMatchingIds } from '../refine_potential_matches'; +import { MonitorLocCheckGroup } from '..'; + +const mockQueryResult = (opts: { latestSummary: any; latestMatching: any }) => { + return { + aggregations: { + monitor: { + buckets: [ + { + key: 'my-monitor', + location: { + buckets: [ + { + key: 'my-location', + summaries: { + latest: { + hits: { + hits: [ + { + _source: opts.latestSummary, + }, + ], + }, + }, + }, + latest_matching: { + top: { + hits: { + hits: [ + { + _source: opts.latestMatching, + }, + ], + }, + }, + }, + }, + ], + }, + }, + ], + }, + }, + }; +}; + +describe('fully matching IDs', () => { + it('should exclude items whose latest result does not match', () => { + const queryRes = mockQueryResult({ + latestSummary: { + '@timestamp': '2020-06-04T12:39:54.698-0500', + monitor: { + check_group: 'latest-summary-check-group', + }, + summary: { + up: 1, + down: 0, + }, + }, + latestMatching: { + '@timestamp': '2019-06-04T12:39:54.698-0500', + summary: { + up: 1, + down: 0, + }, + }, + }); + const res = fullyMatchingIds(queryRes, undefined); + const expected = new Map(); + expect(res).toEqual(expected); + }); + + it('should include items whose latest result does match', () => { + const queryRes = mockQueryResult({ + latestSummary: { + '@timestamp': '2020-06-04T12:39:54.698-0500', + monitor: { + check_group: 'latest-summary-check-group', + }, + summary: { + up: 1, + down: 0, + }, + }, + latestMatching: { + '@timestamp': '2020-06-04T12:39:54.698-0500', + summary: { + up: 1, + down: 0, + }, + }, + }); + const res = fullyMatchingIds(queryRes, undefined); + const expected = new Map(); + expected.set('my-monitor', [ + { + checkGroup: 'latest-summary-check-group', + location: 'my-location', + monitorId: 'my-monitor', + status: 'up', + summaryTimestamp: new Date('2020-06-04T12:39:54.698-0500'), + }, + ]); + expect(res).toEqual(expected); + }); +}); diff --git a/x-pack/plugins/uptime/server/lib/requests/search/fetch_chunk.ts b/x-pack/plugins/uptime/server/lib/requests/search/fetch_chunk.ts index 77676ac9a6373..2a5f1f1261cb3 100644 --- a/x-pack/plugins/uptime/server/lib/requests/search/fetch_chunk.ts +++ b/x-pack/plugins/uptime/server/lib/requests/search/fetch_chunk.ts @@ -26,12 +26,12 @@ export const fetchChunk: ChunkFetcher = async ( searchAfter: any, size: number ): Promise => { - const { monitorIds, checkGroups, searchAfter: foundSearchAfter } = await findPotentialMatches( + const { monitorIds, searchAfter: foundSearchAfter } = await findPotentialMatches( queryContext, searchAfter, size ); - const matching = await refinePotentialMatches(queryContext, monitorIds, checkGroups); + const matching = await refinePotentialMatches(queryContext, monitorIds); return { monitorGroups: matching, diff --git a/x-pack/plugins/uptime/server/lib/requests/search/find_potential_matches.ts b/x-pack/plugins/uptime/server/lib/requests/search/find_potential_matches.ts index a3e7324086073..ac4ff91230b95 100644 --- a/x-pack/plugins/uptime/server/lib/requests/search/find_potential_matches.ts +++ b/x-pack/plugins/uptime/server/lib/requests/search/find_potential_matches.ts @@ -8,12 +8,8 @@ import { get, set } from 'lodash'; import { CursorDirection } from '../../../../common/runtime_types'; import { QueryContext } from './query_context'; -// This is the first phase of the query. In it, we find the most recent check groups that matched the given query. -// Note that these check groups may not be the most recent groups for the matching monitor ID! We'll filter those /** - * This is the first phase of the query. In it, we find the most recent check groups that matched the given query. - * Note that these check groups may not be the most recent groups for the matching monitor ID. They'll be filtered - * out in the next phase. + * This is the first phase of the query. In it, we find all monitor IDs that have ever matched the given filters. * @param queryContext the data and resources needed to perform the query * @param searchAfter indicates where Elasticsearch should continue querying on subsequent requests, if at all * @param size the minimum size of the matches to chunk @@ -24,29 +20,14 @@ export const findPotentialMatches = async ( size: number ) => { const queryResult = await query(queryContext, searchAfter, size); - const checkGroups = new Set(); const monitorIds: string[] = []; get(queryResult, 'aggregations.monitors.buckets', []).forEach((b: any) => { const monitorId = b.key.monitor_id; monitorIds.push(monitorId); - - // Doc count can be zero if status filter optimization does not match - if (b.doc_count > 0) { - // Here we grab the most recent 2 check groups per location and add them to the list. - // Why 2? Because the most recent one may be a partial result from mode: all, and hence not match a summary doc. - b.locations.buckets.forEach((lb: any) => { - lb.ips.buckets.forEach((ib: any) => { - ib.top.hits.hits.forEach((h: any) => { - checkGroups.add(h._source.monitor.check_group); - }); - }); - }); - } }); return { monitorIds, - checkGroups, searchAfter: queryResult.aggregations?.monitors?.after_key, }; }; @@ -89,29 +70,6 @@ const queryBody = async (queryContext: QueryContext, searchAfter: any, size: num }, ], }, - aggs: { - // Here we grab the most recent 2 check groups per location. - // Why 2? Because the most recent one may not be for a summary, it may be incomplete. - locations: { - terms: { field: 'observer.geo.name', missing: '__missing__' }, - aggs: { - ips: { - terms: { field: 'monitor.ip', missing: '0.0.0.0' }, - aggs: { - top: { - top_hits: { - sort: [{ '@timestamp': 'desc' }], - _source: { - includes: ['monitor.check_group', '@timestamp'], - }, - size: 2, - }, - }, - }, - }, - }, - }, - }, }, }, }; diff --git a/x-pack/plugins/uptime/server/lib/requests/search/refine_potential_matches.ts b/x-pack/plugins/uptime/server/lib/requests/search/refine_potential_matches.ts index e5e3de322cbc7..2f54f3f6dd689 100644 --- a/x-pack/plugins/uptime/server/lib/requests/search/refine_potential_matches.ts +++ b/x-pack/plugins/uptime/server/lib/requests/search/refine_potential_matches.ts @@ -18,18 +18,14 @@ import { MonitorGroups, MonitorLocCheckGroup } from './fetch_page'; // check groups for their associated monitor IDs. If not, it discards the result. export const refinePotentialMatches = async ( queryContext: QueryContext, - potentialMatchMonitorIDs: string[], - potentialMatchCheckGroups: Set + potentialMatchMonitorIDs: string[] ): Promise => { if (potentialMatchMonitorIDs.length === 0) { return []; } - const recentGroupsMatchingStatus = await fullyMatchingIds( - queryContext, - potentialMatchMonitorIDs, - potentialMatchCheckGroups - ); + const queryResult = await query(queryContext, potentialMatchMonitorIDs); + const recentGroupsMatchingStatus = await fullyMatchingIds(queryResult, queryContext.statusFilter); // Return the monitor groups filtering out potential matches that weren't current const matches: MonitorGroups[] = potentialMatchMonitorIDs @@ -49,27 +45,35 @@ export const refinePotentialMatches = async ( return matches; }; -const fullyMatchingIds = async ( - queryContext: QueryContext, - potentialMatchMonitorIDs: string[], - potentialMatchCheckGroups: Set -) => { - const mostRecentQueryResult = await mostRecentCheckGroups(queryContext, potentialMatchMonitorIDs); - +export const fullyMatchingIds = (queryResult: any, statusFilter?: string) => { const matching = new Map(); - MonitorLoop: for (const monBucket of mostRecentQueryResult.aggregations.monitor.buckets) { + MonitorLoop: for (const monBucket of queryResult.aggregations.monitor.buckets) { const monitorId: string = monBucket.key; const groups: MonitorLocCheckGroup[] = []; + // Did at least one location match? + let matched = false; for (const locBucket of monBucket.location.buckets) { const location = locBucket.key; - const topSource = locBucket.top.hits.hits[0]._source; - const checkGroup = topSource.monitor.check_group; - const status = topSource.summary.down > 0 ? 'down' : 'up'; + const latestSource = locBucket.summaries.latest.hits.hits[0]._source; + const latestStillMatchingSource = locBucket.latest_matching.top.hits.hits[0]?._source; + // If the most recent document still matches the most recent document matching the current filters + // we can include this in the result + // + // We just check if the timestamp is greater. Note this may match an incomplete check group + // that has not yet sent a summary doc + if ( + latestStillMatchingSource && + latestStillMatchingSource['@timestamp'] >= latestSource['@timestamp'] + ) { + matched = true; + } + const checkGroup = latestSource.monitor.check_group; + const status = latestSource.summary.down > 0 ? 'down' : 'up'; // This monitor doesn't match, so just skip ahead and don't add it to the output // Only skip in case of up statusFilter, for a monitor to be up, all checks should be up - if (queryContext?.statusFilter === 'up' && queryContext.statusFilter !== status) { + if (statusFilter === 'up' && statusFilter !== status) { continue MonitorLoop; } @@ -78,12 +82,12 @@ const fullyMatchingIds = async ( location, checkGroup, status, - summaryTimestamp: topSource['@timestamp'], + summaryTimestamp: new Date(latestSource['@timestamp']), }); } - // We only truly match the monitor if one of the most recent check groups was found in the potential matches phase - if (groups.some((g) => potentialMatchCheckGroups.has(g.checkGroup))) { + // If one location matched, include data from all locations in the result set + if (matched) { matching.set(monitorId, groups); } } @@ -91,7 +95,7 @@ const fullyMatchingIds = async ( return matching; }; -export const mostRecentCheckGroups = async ( +export const query = async ( queryContext: QueryContext, potentialMatchMonitorIDs: string[] ): Promise => { @@ -104,8 +108,6 @@ export const mostRecentCheckGroups = async ( filter: [ await queryContext.dateRangeFilter(), { terms: { 'monitor.id': potentialMatchMonitorIDs } }, - // only match summary docs because we only want the latest *complete* check group. - { exists: { field: 'summary' } }, ], }, }, @@ -116,13 +118,39 @@ export const mostRecentCheckGroups = async ( location: { terms: { field: 'observer.geo.name', missing: 'N/A', size: 100 }, aggs: { - top: { - top_hits: { - sort: [{ '@timestamp': 'desc' }], - _source: { - includes: ['monitor.check_group', '@timestamp', 'summary.up', 'summary.down'], + summaries: { + // only match summary docs because we only want the latest *complete* check group. + filter: { exists: { field: 'summary' } }, + aggs: { + latest: { + top_hits: { + sort: [{ '@timestamp': 'desc' }], + _source: { + includes: [ + 'monitor.check_group', + '@timestamp', + 'summary.up', + 'summary.down', + ], + }, + size: 1, + }, + }, + }, + }, + // We want to find the latest check group, even if it's not part of a summary + latest_matching: { + filter: queryContext.filterClause || { match_all: {} }, + aggs: { + top: { + top_hits: { + sort: [{ '@timestamp': 'desc' }], + _source: { + includes: ['monitor.check_group', '@timestamp'], + }, + size: 1, + }, }, - size: 1, }, }, }, diff --git a/x-pack/plugins/watcher/public/plugin.ts b/x-pack/plugins/watcher/public/plugin.ts index 80f8503af67ce..3d907ac0dff3a 100644 --- a/x-pack/plugins/watcher/public/plugin.ts +++ b/x-pack/plugins/watcher/public/plugin.ts @@ -64,8 +64,6 @@ export class WatcherUIPlugin implements Plugin { }, }); - watcherESApp.disable(); - // TODO: Fix the below dependency on `home` plugin inner workings // Because the home feature catalogue does not have enable/disable functionality we pass // the config in but keep a reference for enabling and disabling showing on home based on @@ -85,9 +83,16 @@ export class WatcherUIPlugin implements Plugin { home.featureCatalogue.register(watcherHome); licensing.license$.pipe(first(), map(licenseToLicenseStatus)).subscribe(({ valid }) => { + // NOTE: We enable the plugin by default instead of disabling it by default because this + // creates a race condition that can cause the app nav item to not render in the side nav. + // The race condition still exists, but it will result in the item rendering when it shouldn't + // (e.g. on a license it's not available for), instead of *not* rendering when it *should*, + // which is a less frustrating UX. if (valid) { watcherESApp.enable(); watcherHome.showOnHomePage = true; + } else { + watcherESApp.disable(); } }); } diff --git a/x-pack/scripts/functional_tests.js b/x-pack/scripts/functional_tests.js index 4392299a78e72..c120e1f780761 100644 --- a/x-pack/scripts/functional_tests.js +++ b/x-pack/scripts/functional_tests.js @@ -6,6 +6,7 @@ const alwaysImportedTests = [ require.resolve('../test/functional/config.js'), + require.resolve('../test/functional_endpoint/config.ts'), require.resolve('../test/functional_with_es_ssl/config.ts'), require.resolve('../test/functional/config_security_basic.ts'), require.resolve('../test/functional/config_security_trial.ts'), diff --git a/x-pack/test/alerting_api_integration/common/config.ts b/x-pack/test/alerting_api_integration/common/config.ts index 19aee29e9b36d..bc209e2bb4925 100644 --- a/x-pack/test/alerting_api_integration/common/config.ts +++ b/x-pack/test/alerting_api_integration/common/config.ts @@ -88,7 +88,7 @@ export function createTestConfig(name: string, options: CreateTestConfigOptions) 'my-slack1': { actionTypeId: '.slack', name: 'Slack#xyz', - config: { + secrets: { webhookUrl: 'https://hooks.slack.com/services/abcd/efgh/ijklmnopqrstuvwxyz', }, }, diff --git a/x-pack/test/api_integration/apis/endpoint/alerts/index.ts b/x-pack/test/api_integration/apis/endpoint/alerts/index.ts index 67ef3ea42cf16..9ad83f509fc50 100644 --- a/x-pack/test/api_integration/apis/endpoint/alerts/index.ts +++ b/x-pack/test/api_integration/apis/endpoint/alerts/index.ts @@ -70,7 +70,8 @@ export default function ({ getService }: FtrProviderContext) { let nullableEventId = ''; - describe('Endpoint alert API', () => { + // SKIPPED as it is failing ES PROMOTION: https://github.com/elastic/kibana/issues/68613 + describe.skip('Endpoint alert API', () => { describe('when data is in elasticsearch', () => { before(async () => { await esArchiver.load('endpoint/alerts/api_feature'); diff --git a/x-pack/test/api_integration/apis/endpoint/metadata.ts b/x-pack/test/api_integration/apis/endpoint/metadata.ts index 5c4bb52b8d9e2..e48db70fd0124 100644 --- a/x-pack/test/api_integration/apis/endpoint/metadata.ts +++ b/x-pack/test/api_integration/apis/endpoint/metadata.ts @@ -14,7 +14,8 @@ const numberOfHostsInFixture = 3; export default function ({ getService }: FtrProviderContext) { const esArchiver = getService('esArchiver'); const supertest = getService('supertest'); - describe('test metadata api', () => { + // SKIPPED as it is failing on ES PROMOTION: https://github.com/elastic/kibana/issues/68584 + describe.skip('test metadata api', () => { describe('POST /api/endpoint/metadata when index is empty', () => { it('metadata api should return empty result when index is empty', async () => { await esArchiver.unload('endpoint/metadata/api_feature'); diff --git a/x-pack/test/api_integration/apis/endpoint/policy.ts b/x-pack/test/api_integration/apis/endpoint/policy.ts index 792c8440cdea1..c3e95f2db1bc0 100644 --- a/x-pack/test/api_integration/apis/endpoint/policy.ts +++ b/x-pack/test/api_integration/apis/endpoint/policy.ts @@ -10,7 +10,8 @@ import { FtrProviderContext } from '../../ftr_provider_context'; export default function ({ getService }: FtrProviderContext) { const esArchiver = getService('esArchiver'); const supertest = getService('supertest'); - describe('Endpoint policy api', () => { + // SKIPPED as it is failing ES PROMOTION: https://github.com/elastic/kibana/issues/68638 + describe.skip('Endpoint policy api', () => { describe('GET /api/endpoint/policy_response', () => { before(async () => await esArchiver.load('endpoint/policy')); diff --git a/x-pack/test/api_integration/apis/management/index_management/component_templates.ts b/x-pack/test/api_integration/apis/management/index_management/component_templates.ts index a33e82ad9f79d..64bf03a043b55 100644 --- a/x-pack/test/api_integration/apis/management/index_management/component_templates.ts +++ b/x-pack/test/api_integration/apis/management/index_management/component_templates.ts @@ -61,7 +61,10 @@ export default function ({ getService }: FtrProviderContext) { expect(testComponentTemplate).to.eql({ name: COMPONENT_NAME, - component_template: COMPONENT, + usedBy: [], + hasSettings: true, + hasMappings: true, + hasAliases: false, }); }); }); @@ -74,8 +77,9 @@ export default function ({ getService }: FtrProviderContext) { expect(body).to.eql({ name: COMPONENT_NAME, - component_template: { - ...COMPONENT, + ...COMPONENT, + _kbnMeta: { + usedBy: [], }, }); }); diff --git a/x-pack/test/api_integration/apis/management/index_management/data_streams.ts b/x-pack/test/api_integration/apis/management/index_management/data_streams.ts new file mode 100644 index 0000000000000..9a8511b4331ea --- /dev/null +++ b/x-pack/test/api_integration/apis/management/index_management/data_streams.ts @@ -0,0 +1,89 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect'; + +import { FtrProviderContext } from '../../../ftr_provider_context'; +// @ts-ignore +import { API_BASE_PATH } from './constants'; + +export default function ({ getService }: FtrProviderContext) { + const supertest = getService('supertest'); + const es = getService('legacyEs'); + + const createDataStream = (name: string) => { + // A data stream requires an index template before it can be created. + return es.dataManagement + .saveComposableIndexTemplate({ + name, + body: { + index_patterns: ['*'], + template: { + settings: {}, + }, + data_stream: { + timestamp_field: '@timestamp', + }, + }, + }) + .then(() => + es.dataManagement.createDataStream({ + name, + }) + ); + }; + + const deleteDataStream = (name: string) => { + return es.dataManagement + .deleteComposableIndexTemplate({ + name, + }) + .then(() => + es.dataManagement.deleteDataStream({ + name, + }) + ); + }; + + describe('Data streams', function () { + const testDataStreamName = 'test-data-stream'; + + describe('Get', () => { + before(async () => await createDataStream(testDataStreamName)); + after(async () => await deleteDataStream(testDataStreamName)); + + describe('all data streams', () => { + it('returns an array of data streams', async () => { + const { body: dataStreams } = await supertest + .get(`${API_BASE_PATH}/data_streams`) + .set('kbn-xsrf', 'xxx') + .expect(200); + + // ES determines these values so we'll just echo them back. + const { name: indexName, uuid } = dataStreams[0].indices[0]; + expect(dataStreams).to.eql([ + { + name: testDataStreamName, + timeStampField: '@timestamp', + indices: [ + { + name: indexName, + uuid, + }, + ], + generation: 1, + }, + ]); + }); + }); + }); + }); +} diff --git a/x-pack/test/api_integration/apis/management/index_management/index.js b/x-pack/test/api_integration/apis/management/index_management/index.js index fdee325938ff4..93e8a4a8d6130 100644 --- a/x-pack/test/api_integration/apis/management/index_management/index.js +++ b/x-pack/test/api_integration/apis/management/index_management/index.js @@ -10,6 +10,7 @@ export default function ({ loadTestFile }) { loadTestFile(require.resolve('./mapping')); loadTestFile(require.resolve('./settings')); loadTestFile(require.resolve('./stats')); + loadTestFile(require.resolve('./data_streams')); loadTestFile(require.resolve('./templates')); loadTestFile(require.resolve('./component_templates')); }); diff --git a/x-pack/test/api_integration/apis/management/index_management/lib/elasticsearch.js b/x-pack/test/api_integration/apis/management/index_management/lib/elasticsearch.js index b950a56a913db..1a1517567eaed 100644 --- a/x-pack/test/api_integration/apis/management/index_management/lib/elasticsearch.js +++ b/x-pack/test/api_integration/apis/management/index_management/lib/elasticsearch.js @@ -3,6 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ + import { getRandomString } from './random'; /** diff --git a/x-pack/test/api_integration/apis/management/index_management/templates.helpers.js b/x-pack/test/api_integration/apis/management/index_management/templates.helpers.js index 9f1fab4039397..292aabad85054 100644 --- a/x-pack/test/api_integration/apis/management/index_management/templates.helpers.js +++ b/x-pack/test/api_integration/apis/management/index_management/templates.helpers.js @@ -7,10 +7,10 @@ import { API_BASE_PATH, INDEX_PATTERNS } from './constants'; export const registerHelpers = ({ supertest }) => { - const getAllTemplates = () => supertest.get(`${API_BASE_PATH}/index-templates`); + const getAllTemplates = () => supertest.get(`${API_BASE_PATH}/index_templates`); const getOneTemplate = (name, isLegacy = true) => - supertest.get(`${API_BASE_PATH}/index-templates/${name}?legacy=${isLegacy}`); + supertest.get(`${API_BASE_PATH}/index_templates/${name}?legacy=${isLegacy}`); const getTemplatePayload = (name, isLegacy = true) => ({ name, @@ -50,17 +50,17 @@ export const registerHelpers = ({ supertest }) => { }); const createTemplate = (payload) => - supertest.post(`${API_BASE_PATH}/index-templates`).set('kbn-xsrf', 'xxx').send(payload); + supertest.post(`${API_BASE_PATH}/index_templates`).set('kbn-xsrf', 'xxx').send(payload); const deleteTemplates = (templates) => supertest - .post(`${API_BASE_PATH}/delete-index-templates`) + .post(`${API_BASE_PATH}/delete_index_templates`) .set('kbn-xsrf', 'xxx') .send({ templates }); const updateTemplate = (payload, templateName) => supertest - .put(`${API_BASE_PATH}/index-templates/${templateName}`) + .put(`${API_BASE_PATH}/index_templates/${templateName}`) .set('kbn-xsrf', 'xxx') .send(payload); diff --git a/x-pack/test/api_integration/apis/ml/job_validation/validate.ts b/x-pack/test/api_integration/apis/ml/job_validation/validate.ts index 55497940190cb..fc8f837744221 100644 --- a/x-pack/test/api_integration/apis/ml/job_validation/validate.ts +++ b/x-pack/test/api_integration/apis/ml/job_validation/validate.ts @@ -226,6 +226,15 @@ export default ({ getService }: FtrProviderContext) => { .send(requestBody) .expect(200); + // The existance and value of maxModelMemoryLimit depends on ES settings + // and may vary between test environments, e.g. cloud vs non-cloud, + // so it should not be part of the validation + body.forEach((element: any) => { + if (element.hasOwnProperty('maxModelMemoryLimit')) { + delete element.maxModelMemoryLimit; + } + }); + expect(body).to.eql([ { id: 'job_id_valid', diff --git a/x-pack/test/detection_engine_api_integration/basic/tests/delete_rules.ts b/x-pack/test/detection_engine_api_integration/basic/tests/delete_rules.ts index e91b735e1629b..5626d63b8f230 100644 --- a/x-pack/test/detection_engine_api_integration/basic/tests/delete_rules.ts +++ b/x-pack/test/detection_engine_api_integration/basic/tests/delete_rules.ts @@ -92,12 +92,12 @@ export default ({ getService }: FtrProviderContext): void => { it('should return an error if the id does not exist when trying to delete it', async () => { const { body } = await supertest - .delete(`${DETECTION_ENGINE_RULES_URL}?id=fake_id`) + .delete(`${DETECTION_ENGINE_RULES_URL}?id=c1e1b359-7ac1-4e96-bc81-c683c092436f`) .set('kbn-xsrf', 'true') .expect(404); expect(body).to.eql({ - message: 'id: "fake_id" not found', + message: 'id: "c1e1b359-7ac1-4e96-bc81-c683c092436f" not found', status_code: 404, }); }); diff --git a/x-pack/test/detection_engine_api_integration/basic/tests/delete_rules_bulk.ts b/x-pack/test/detection_engine_api_integration/basic/tests/delete_rules_bulk.ts index 687551c2d8313..04f168d5b7953 100644 --- a/x-pack/test/detection_engine_api_integration/basic/tests/delete_rules_bulk.ts +++ b/x-pack/test/detection_engine_api_integration/basic/tests/delete_rules_bulk.ts @@ -114,17 +114,17 @@ export default ({ getService }: FtrProviderContext): void => { it('should return an error if the id does not exist when trying to delete an id', async () => { const { body } = await supertest .delete(`${DETECTION_ENGINE_RULES_URL}/_bulk_delete`) - .send([{ id: 'fake_id' }]) + .send([{ id: 'c4e80a0d-e20f-4efc-84c1-08112da5a612' }]) .set('kbn-xsrf', 'true') .expect(200); expect(body).to.eql([ { error: { - message: 'id: "fake_id" not found', + message: 'id: "c4e80a0d-e20f-4efc-84c1-08112da5a612" not found', status_code: 404, }, - id: 'fake_id', + id: 'c4e80a0d-e20f-4efc-84c1-08112da5a612', }, ]); }); @@ -139,14 +139,20 @@ export default ({ getService }: FtrProviderContext): void => { const { body } = await supertest .delete(`${DETECTION_ENGINE_RULES_URL}/_bulk_delete`) - .send([{ id: bodyWithCreatedRule.id }, { id: 'fake_id' }]) + .send([{ id: bodyWithCreatedRule.id }, { id: 'c4e80a0d-e20f-4efc-84c1-08112da5a612' }]) .set('kbn-xsrf', 'true') .expect(200); const bodyToCompare = removeServerGeneratedPropertiesIncludingRuleId(body[0]); expect([bodyToCompare, body[1]]).to.eql([ getSimpleRuleOutputWithoutRuleId(), - { id: 'fake_id', error: { status_code: 404, message: 'id: "fake_id" not found' } }, + { + id: 'c4e80a0d-e20f-4efc-84c1-08112da5a612', + error: { + status_code: 404, + message: 'id: "c4e80a0d-e20f-4efc-84c1-08112da5a612" not found', + }, + }, ]); }); }); @@ -241,17 +247,17 @@ export default ({ getService }: FtrProviderContext): void => { it('should return an error if the id does not exist when trying to delete an id', async () => { const { body } = await supertest .post(`${DETECTION_ENGINE_RULES_URL}/_bulk_delete`) - .send([{ id: 'fake_id' }]) + .send([{ id: 'c4e80a0d-e20f-4efc-84c1-08112da5a612' }]) .set('kbn-xsrf', 'true') .expect(200); expect(body).to.eql([ { error: { - message: 'id: "fake_id" not found', + message: 'id: "c4e80a0d-e20f-4efc-84c1-08112da5a612" not found', status_code: 404, }, - id: 'fake_id', + id: 'c4e80a0d-e20f-4efc-84c1-08112da5a612', }, ]); }); @@ -266,14 +272,20 @@ export default ({ getService }: FtrProviderContext): void => { const { body } = await supertest .post(`${DETECTION_ENGINE_RULES_URL}/_bulk_delete`) - .send([{ id: bodyWithCreatedRule.id }, { id: 'fake_id' }]) + .send([{ id: bodyWithCreatedRule.id }, { id: 'c4e80a0d-e20f-4efc-84c1-08112da5a612' }]) .set('kbn-xsrf', 'true') .expect(200); const bodyToCompare = removeServerGeneratedPropertiesIncludingRuleId(body[0]); expect([bodyToCompare, body[1]]).to.eql([ getSimpleRuleOutputWithoutRuleId(), - { id: 'fake_id', error: { status_code: 404, message: 'id: "fake_id" not found' } }, + { + id: 'c4e80a0d-e20f-4efc-84c1-08112da5a612', + error: { + status_code: 404, + message: 'id: "c4e80a0d-e20f-4efc-84c1-08112da5a612" not found', + }, + }, ]); }); }); diff --git a/x-pack/test/detection_engine_api_integration/basic/tests/import_rules.ts b/x-pack/test/detection_engine_api_integration/basic/tests/import_rules.ts index e3c4233383be4..66962df14e22d 100644 --- a/x-pack/test/detection_engine_api_integration/basic/tests/import_rules.ts +++ b/x-pack/test/detection_engine_api_integration/basic/tests/import_rules.ts @@ -120,16 +120,6 @@ export default ({ getService }: FtrProviderContext): void => { }); }); - it('should report that it failed to import a thousand and one (10001) simple rules', async () => { - const { body } = await supertest - .post(`${DETECTION_ENGINE_RULES_URL}/_import`) - .set('kbn-xsrf', 'true') - .attach('file', getSimpleRuleAsNdjson(new Array(10001).fill('rule-1')), 'rules.ndjson') - .expect(500); - - expect(body).to.eql({ message: "Can't import more than 10000 rules", status_code: 500 }); - }); - it('should be able to read an imported rule back out correctly', async () => { await supertest .post(`${DETECTION_ENGINE_RULES_URL}/_import`) diff --git a/x-pack/test/detection_engine_api_integration/basic/tests/patch_rules.ts b/x-pack/test/detection_engine_api_integration/basic/tests/patch_rules.ts index 099ea950d128c..01138779ee39c 100644 --- a/x-pack/test/detection_engine_api_integration/basic/tests/patch_rules.ts +++ b/x-pack/test/detection_engine_api_integration/basic/tests/patch_rules.ts @@ -207,12 +207,12 @@ export default ({ getService }: FtrProviderContext) => { const { body } = await supertest .patch(DETECTION_ENGINE_RULES_URL) .set('kbn-xsrf', 'true') - .send({ id: 'fake_id', name: 'some other name' }) + .send({ id: '5096dec6-b6b9-4d8d-8f93-6c2602079d9d', name: 'some other name' }) .expect(404); expect(body).to.eql({ status_code: 404, - message: 'id: "fake_id" not found', + message: 'id: "5096dec6-b6b9-4d8d-8f93-6c2602079d9d" not found', }); }); diff --git a/x-pack/test/detection_engine_api_integration/basic/tests/patch_rules_bulk.ts b/x-pack/test/detection_engine_api_integration/basic/tests/patch_rules_bulk.ts index 0bf80204e2445..26a39a46d07f7 100644 --- a/x-pack/test/detection_engine_api_integration/basic/tests/patch_rules_bulk.ts +++ b/x-pack/test/detection_engine_api_integration/basic/tests/patch_rules_bulk.ts @@ -261,11 +261,17 @@ export default ({ getService }: FtrProviderContext) => { const { body } = await supertest .patch(`${DETECTION_ENGINE_RULES_URL}/_bulk_update`) .set('kbn-xsrf', 'true') - .send([{ id: 'fake_id', name: 'some other name' }]) + .send([{ id: '5096dec6-b6b9-4d8d-8f93-6c2602079d9d', name: 'some other name' }]) .expect(200); expect(body).to.eql([ - { id: 'fake_id', error: { status_code: 404, message: 'id: "fake_id" not found' } }, + { + id: '5096dec6-b6b9-4d8d-8f93-6c2602079d9d', + error: { + status_code: 404, + message: 'id: "5096dec6-b6b9-4d8d-8f93-6c2602079d9d" not found', + }, + }, ]); }); @@ -333,7 +339,7 @@ export default ({ getService }: FtrProviderContext) => { .set('kbn-xsrf', 'true') .send([ { id: createdBody.id, name: 'some other name' }, - { id: 'fake_id', name: 'some other name' }, + { id: '5096dec6-b6b9-4d8d-8f93-6c2602079d9d', name: 'some other name' }, ]) .expect(200); @@ -346,10 +352,10 @@ export default ({ getService }: FtrProviderContext) => { outputRule, { error: { - message: 'id: "fake_id" not found', + message: 'id: "5096dec6-b6b9-4d8d-8f93-6c2602079d9d" not found', status_code: 404, }, - id: 'fake_id', + id: '5096dec6-b6b9-4d8d-8f93-6c2602079d9d', }, ]); }); diff --git a/x-pack/test/detection_engine_api_integration/basic/tests/read_rules.ts b/x-pack/test/detection_engine_api_integration/basic/tests/read_rules.ts index bd83ef00ccf1a..59717724e4201 100644 --- a/x-pack/test/detection_engine_api_integration/basic/tests/read_rules.ts +++ b/x-pack/test/detection_engine_api_integration/basic/tests/read_rules.ts @@ -92,14 +92,14 @@ export default ({ getService }: FtrProviderContext) => { it('should return 404 if given a fake id', async () => { const { body } = await supertest - .get(`${DETECTION_ENGINE_RULES_URL}?id=fake_id`) + .get(`${DETECTION_ENGINE_RULES_URL}?id=c1e1b359-7ac1-4e96-bc81-c683c092436f`) .set('kbn-xsrf', 'true') .send(getSimpleRule()) .expect(404); expect(body).to.eql({ status_code: 404, - message: 'id: "fake_id" not found', + message: 'id: "c1e1b359-7ac1-4e96-bc81-c683c092436f" not found', }); }); diff --git a/x-pack/test/detection_engine_api_integration/basic/tests/update_rules.ts b/x-pack/test/detection_engine_api_integration/basic/tests/update_rules.ts index 83fb991ecef1b..127f688dfbc28 100644 --- a/x-pack/test/detection_engine_api_integration/basic/tests/update_rules.ts +++ b/x-pack/test/detection_engine_api_integration/basic/tests/update_rules.ts @@ -212,7 +212,7 @@ export default ({ getService }: FtrProviderContext) => { it('should give a 404 if it is given a fake id', async () => { const simpleRule = getSimpleRule(); - simpleRule.id = 'fake_id'; + simpleRule.id = '5096dec6-b6b9-4d8d-8f93-6c2602079d9d'; delete simpleRule.rule_id; const { body } = await supertest @@ -223,7 +223,7 @@ export default ({ getService }: FtrProviderContext) => { expect(body).to.eql({ status_code: 404, - message: 'id: "fake_id" not found', + message: 'id: "5096dec6-b6b9-4d8d-8f93-6c2602079d9d" not found', }); }); diff --git a/x-pack/test/detection_engine_api_integration/basic/tests/update_rules_bulk.ts b/x-pack/test/detection_engine_api_integration/basic/tests/update_rules_bulk.ts index 655f2b5d2e33f..54f29939fb6b4 100644 --- a/x-pack/test/detection_engine_api_integration/basic/tests/update_rules_bulk.ts +++ b/x-pack/test/detection_engine_api_integration/basic/tests/update_rules_bulk.ts @@ -269,7 +269,7 @@ export default ({ getService }: FtrProviderContext) => { it('should return a 200 but give a 404 in the message if it is given a fake id', async () => { const ruleUpdate = getSimpleRule('rule-1'); - ruleUpdate.id = 'fake_id'; + ruleUpdate.id = '1fd52120-d3a9-4e7a-b23c-96c0e1a74ae5'; delete ruleUpdate.rule_id; const { body } = await supertest @@ -279,7 +279,13 @@ export default ({ getService }: FtrProviderContext) => { .expect(200); expect(body).to.eql([ - { id: 'fake_id', error: { status_code: 404, message: 'id: "fake_id" not found' } }, + { + id: '1fd52120-d3a9-4e7a-b23c-96c0e1a74ae5', + error: { + status_code: 404, + message: 'id: "1fd52120-d3a9-4e7a-b23c-96c0e1a74ae5" not found', + }, + }, ]); }); @@ -358,7 +364,7 @@ export default ({ getService }: FtrProviderContext) => { const rule2 = getSimpleRule(); delete rule2.rule_id; - rule2.id = 'fake_id'; + rule2.id = 'b3aa019a-656c-4311-b13b-4d9852e24347'; rule2.name = 'some other name'; const { body } = await supertest @@ -376,10 +382,10 @@ export default ({ getService }: FtrProviderContext) => { outputRule, { error: { - message: 'id: "fake_id" not found', + message: 'id: "b3aa019a-656c-4311-b13b-4d9852e24347" not found', status_code: 404, }, - id: 'fake_id', + id: 'b3aa019a-656c-4311-b13b-4d9852e24347', }, ]); }); diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules.ts index 449168d73f4ef..8847b0c3250ac 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules.ts @@ -6,7 +6,10 @@ import expect from '@kbn/expect'; -import { DETECTION_ENGINE_RULES_URL } from '../../../../plugins/security_solution/common/constants'; +import { + DETECTION_ENGINE_RULES_URL, + DETECTION_ENGINE_RULES_STATUS_URL, +} from '../../../../plugins/security_solution/common/constants'; import { FtrProviderContext } from '../../common/ftr_provider_context'; import { createSignalsIndex, @@ -65,6 +68,46 @@ export default ({ getService }: FtrProviderContext) => { expect(bodyToCompare).to.eql(getSimpleRuleOutput()); }); + /* + This test is to ensure no future regressions introduced by the following scenario + a call to updateApiKey was invalidating the api key used by the + rule while the rule was executing, or even before it executed, + on the first rule run. + this pr https://github.com/elastic/kibana/pull/68184 + fixed this by finding the true source of a bug that required the manual + api key update, and removed the call to that function. + + When the api key is updated before / while the rule is executing, the alert + executor no longer has access to a service to update the rule status + saved object in Elasticsearch. Because of this, we cannot set the rule into + a 'failure' state, so the user ends up seeing 'going to run' as that is the + last status set for the rule before it erupts in an error that cannot be + recorded inside of the executor. + + This adds an e2e test for the backend to catch that in case + this pops up again elsewhere. + */ + it('should create a single rule with a rule_id and validate it ran successfully', async () => { + const simpleRule = getSimpleRule(); + const { body } = await supertest + .post(DETECTION_ENGINE_RULES_URL) + .set('kbn-xsrf', 'true') + .send(simpleRule) + .expect(200); + + // wait for Task Manager to execute the rule and update status + await new Promise((resolve) => setTimeout(resolve, 5000)); + const { body: statusBody } = await supertest + .post(DETECTION_ENGINE_RULES_STATUS_URL) + .set('kbn-xsrf', 'true') + .send({ ids: [body.id] }) + .expect(200); + + const bodyToCompare = removeServerGeneratedProperties(body); + expect(bodyToCompare).to.eql(getSimpleRuleOutput()); + expect(statusBody[body.id].current_status.status).to.eql('succeeded'); + }); + it('should create a single rule without an input index', async () => { const { index, ...payload } = getSimpleRule(); const { index: _index, ...expected } = getSimpleRuleOutput(); diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules_bulk.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules_bulk.ts index 6c3b1c45e202e..47b09fd1fe3c7 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules_bulk.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules_bulk.ts @@ -6,7 +6,10 @@ import expect from '@kbn/expect'; -import { DETECTION_ENGINE_RULES_URL } from '../../../../plugins/security_solution/common/constants'; +import { + DETECTION_ENGINE_RULES_URL, + DETECTION_ENGINE_RULES_STATUS_URL, +} from '../../../../plugins/security_solution/common/constants'; import { FtrProviderContext } from '../../common/ftr_provider_context'; import { createSignalsIndex, @@ -68,6 +71,46 @@ export default ({ getService }: FtrProviderContext): void => { expect(bodyToCompare).to.eql(getSimpleRuleOutput()); }); + /* + This test is to ensure no future regressions introduced by the following scenario + a call to updateApiKey was invalidating the api key used by the + rule while the rule was executing, or even before it executed, + on the first rule run. + this pr https://github.com/elastic/kibana/pull/68184 + fixed this by finding the true source of a bug that required the manual + api key update, and removed the call to that function. + + When the api key is updated before / while the rule is executing, the alert + executor no longer has access to a service to update the rule status + saved object in Elasticsearch. Because of this, we cannot set the rule into + a 'failure' state, so the user ends up seeing 'going to run' as that is the + last status set for the rule before it erupts in an error that cannot be + recorded inside of the executor. + + This adds an e2e test for the backend to catch that in case + this pops up again elsewhere. + */ + it('should create a single rule with a rule_id and validate it ran successfully', async () => { + const simpleRule = getSimpleRule(); + const { body } = await supertest + .post(`${DETECTION_ENGINE_RULES_URL}/_bulk_create`) + .set('kbn-xsrf', 'true') + .send([simpleRule]) + .expect(200); + + // wait for Task Manager to execute the rule and update status + await new Promise((resolve) => setTimeout(resolve, 5000)); + const { body: statusBody } = await supertest + .post(DETECTION_ENGINE_RULES_STATUS_URL) + .set('kbn-xsrf', 'true') + .send({ ids: [body[0].id] }) + .expect(200); + + const bodyToCompare = removeServerGeneratedProperties(body[0]); + expect(bodyToCompare).to.eql(getSimpleRuleOutput()); + expect(statusBody[body[0].id].current_status.status).to.eql('succeeded'); + }); + it('should create a single rule without a rule_id', async () => { const { body } = await supertest .post(`${DETECTION_ENGINE_RULES_URL}/_bulk_create`) diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/delete_rules.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/delete_rules.ts index e91b735e1629b..5626d63b8f230 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/delete_rules.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/delete_rules.ts @@ -92,12 +92,12 @@ export default ({ getService }: FtrProviderContext): void => { it('should return an error if the id does not exist when trying to delete it', async () => { const { body } = await supertest - .delete(`${DETECTION_ENGINE_RULES_URL}?id=fake_id`) + .delete(`${DETECTION_ENGINE_RULES_URL}?id=c1e1b359-7ac1-4e96-bc81-c683c092436f`) .set('kbn-xsrf', 'true') .expect(404); expect(body).to.eql({ - message: 'id: "fake_id" not found', + message: 'id: "c1e1b359-7ac1-4e96-bc81-c683c092436f" not found', status_code: 404, }); }); diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/delete_rules_bulk.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/delete_rules_bulk.ts index 687551c2d8313..04f168d5b7953 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/delete_rules_bulk.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/delete_rules_bulk.ts @@ -114,17 +114,17 @@ export default ({ getService }: FtrProviderContext): void => { it('should return an error if the id does not exist when trying to delete an id', async () => { const { body } = await supertest .delete(`${DETECTION_ENGINE_RULES_URL}/_bulk_delete`) - .send([{ id: 'fake_id' }]) + .send([{ id: 'c4e80a0d-e20f-4efc-84c1-08112da5a612' }]) .set('kbn-xsrf', 'true') .expect(200); expect(body).to.eql([ { error: { - message: 'id: "fake_id" not found', + message: 'id: "c4e80a0d-e20f-4efc-84c1-08112da5a612" not found', status_code: 404, }, - id: 'fake_id', + id: 'c4e80a0d-e20f-4efc-84c1-08112da5a612', }, ]); }); @@ -139,14 +139,20 @@ export default ({ getService }: FtrProviderContext): void => { const { body } = await supertest .delete(`${DETECTION_ENGINE_RULES_URL}/_bulk_delete`) - .send([{ id: bodyWithCreatedRule.id }, { id: 'fake_id' }]) + .send([{ id: bodyWithCreatedRule.id }, { id: 'c4e80a0d-e20f-4efc-84c1-08112da5a612' }]) .set('kbn-xsrf', 'true') .expect(200); const bodyToCompare = removeServerGeneratedPropertiesIncludingRuleId(body[0]); expect([bodyToCompare, body[1]]).to.eql([ getSimpleRuleOutputWithoutRuleId(), - { id: 'fake_id', error: { status_code: 404, message: 'id: "fake_id" not found' } }, + { + id: 'c4e80a0d-e20f-4efc-84c1-08112da5a612', + error: { + status_code: 404, + message: 'id: "c4e80a0d-e20f-4efc-84c1-08112da5a612" not found', + }, + }, ]); }); }); @@ -241,17 +247,17 @@ export default ({ getService }: FtrProviderContext): void => { it('should return an error if the id does not exist when trying to delete an id', async () => { const { body } = await supertest .post(`${DETECTION_ENGINE_RULES_URL}/_bulk_delete`) - .send([{ id: 'fake_id' }]) + .send([{ id: 'c4e80a0d-e20f-4efc-84c1-08112da5a612' }]) .set('kbn-xsrf', 'true') .expect(200); expect(body).to.eql([ { error: { - message: 'id: "fake_id" not found', + message: 'id: "c4e80a0d-e20f-4efc-84c1-08112da5a612" not found', status_code: 404, }, - id: 'fake_id', + id: 'c4e80a0d-e20f-4efc-84c1-08112da5a612', }, ]); }); @@ -266,14 +272,20 @@ export default ({ getService }: FtrProviderContext): void => { const { body } = await supertest .post(`${DETECTION_ENGINE_RULES_URL}/_bulk_delete`) - .send([{ id: bodyWithCreatedRule.id }, { id: 'fake_id' }]) + .send([{ id: bodyWithCreatedRule.id }, { id: 'c4e80a0d-e20f-4efc-84c1-08112da5a612' }]) .set('kbn-xsrf', 'true') .expect(200); const bodyToCompare = removeServerGeneratedPropertiesIncludingRuleId(body[0]); expect([bodyToCompare, body[1]]).to.eql([ getSimpleRuleOutputWithoutRuleId(), - { id: 'fake_id', error: { status_code: 404, message: 'id: "fake_id" not found' } }, + { + id: 'c4e80a0d-e20f-4efc-84c1-08112da5a612', + error: { + status_code: 404, + message: 'id: "c4e80a0d-e20f-4efc-84c1-08112da5a612" not found', + }, + }, ]); }); }); diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/find_statuses.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/find_statuses.ts index 6ff5a8c552ab7..f659857b89a97 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/find_statuses.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/find_statuses.ts @@ -42,6 +42,25 @@ export default ({ getService }: FtrProviderContext): void => { expect(body).to.eql({}); }); + /* + This test is to ensure no future regressions introduced by the following scenario + a call to updateApiKey was invalidating the api key used by the + rule while the rule was executing, or even before it executed, + on the first rule run. + this pr https://github.com/elastic/kibana/pull/68184 + fixed this by finding the true source of a bug that required the manual + api key update, and removed the call to that function. + + When the api key is updated before / while the rule is executing, the alert + executor no longer has access to a service to update the rule status + saved object in Elasticsearch. Because of this, we cannot set the rule into + a 'failure' state, so the user ends up seeing 'going to run' as that is the + last status set for the rule before it erupts in an error that cannot be + recorded inside of the executor. + + This adds an e2e test for the backend to catch that in case + this pops up again elsewhere. + */ it('should return a single rule status when a single rule is loaded from a find status with defaults added', async () => { // add a single rule const { body: resBody } = await supertest @@ -61,7 +80,7 @@ export default ({ getService }: FtrProviderContext): void => { .expect(200); // expected result for status should be 'going to run' or 'succeeded - expect(['succeeded', 'going to run']).to.contain(body[resBody.id].current_status.status); + expect(body[resBody.id].current_status.status).to.eql('succeeded'); }); }); }; diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/import_rules.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/import_rules.ts index e3c4233383be4..66962df14e22d 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/import_rules.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/import_rules.ts @@ -120,16 +120,6 @@ export default ({ getService }: FtrProviderContext): void => { }); }); - it('should report that it failed to import a thousand and one (10001) simple rules', async () => { - const { body } = await supertest - .post(`${DETECTION_ENGINE_RULES_URL}/_import`) - .set('kbn-xsrf', 'true') - .attach('file', getSimpleRuleAsNdjson(new Array(10001).fill('rule-1')), 'rules.ndjson') - .expect(500); - - expect(body).to.eql({ message: "Can't import more than 10000 rules", status_code: 500 }); - }); - it('should be able to read an imported rule back out correctly', async () => { await supertest .post(`${DETECTION_ENGINE_RULES_URL}/_import`) diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/patch_rules.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/patch_rules.ts index a199382f29213..3219ae7e0e2d4 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/patch_rules.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/patch_rules.ts @@ -210,12 +210,12 @@ export default ({ getService }: FtrProviderContext) => { const { body } = await supertest .patch(DETECTION_ENGINE_RULES_URL) .set('kbn-xsrf', 'true') - .send({ id: 'fake_id', name: 'some other name' }) + .send({ id: '5096dec6-b6b9-4d8d-8f93-6c2602079d9d', name: 'some other name' }) .expect(404); expect(body).to.eql({ status_code: 404, - message: 'id: "fake_id" not found', + message: 'id: "5096dec6-b6b9-4d8d-8f93-6c2602079d9d" not found', }); }); diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/patch_rules_bulk.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/patch_rules_bulk.ts index 0bf80204e2445..26a39a46d07f7 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/patch_rules_bulk.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/patch_rules_bulk.ts @@ -261,11 +261,17 @@ export default ({ getService }: FtrProviderContext) => { const { body } = await supertest .patch(`${DETECTION_ENGINE_RULES_URL}/_bulk_update`) .set('kbn-xsrf', 'true') - .send([{ id: 'fake_id', name: 'some other name' }]) + .send([{ id: '5096dec6-b6b9-4d8d-8f93-6c2602079d9d', name: 'some other name' }]) .expect(200); expect(body).to.eql([ - { id: 'fake_id', error: { status_code: 404, message: 'id: "fake_id" not found' } }, + { + id: '5096dec6-b6b9-4d8d-8f93-6c2602079d9d', + error: { + status_code: 404, + message: 'id: "5096dec6-b6b9-4d8d-8f93-6c2602079d9d" not found', + }, + }, ]); }); @@ -333,7 +339,7 @@ export default ({ getService }: FtrProviderContext) => { .set('kbn-xsrf', 'true') .send([ { id: createdBody.id, name: 'some other name' }, - { id: 'fake_id', name: 'some other name' }, + { id: '5096dec6-b6b9-4d8d-8f93-6c2602079d9d', name: 'some other name' }, ]) .expect(200); @@ -346,10 +352,10 @@ export default ({ getService }: FtrProviderContext) => { outputRule, { error: { - message: 'id: "fake_id" not found', + message: 'id: "5096dec6-b6b9-4d8d-8f93-6c2602079d9d" not found', status_code: 404, }, - id: 'fake_id', + id: '5096dec6-b6b9-4d8d-8f93-6c2602079d9d', }, ]); }); diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/read_rules.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/read_rules.ts index bd83ef00ccf1a..59717724e4201 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/read_rules.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/read_rules.ts @@ -92,14 +92,14 @@ export default ({ getService }: FtrProviderContext) => { it('should return 404 if given a fake id', async () => { const { body } = await supertest - .get(`${DETECTION_ENGINE_RULES_URL}?id=fake_id`) + .get(`${DETECTION_ENGINE_RULES_URL}?id=c1e1b359-7ac1-4e96-bc81-c683c092436f`) .set('kbn-xsrf', 'true') .send(getSimpleRule()) .expect(404); expect(body).to.eql({ status_code: 404, - message: 'id: "fake_id" not found', + message: 'id: "c1e1b359-7ac1-4e96-bc81-c683c092436f" not found', }); }); diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/update_rules.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/update_rules.ts index 003c8645f1b22..0b1b49e379d17 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/update_rules.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/update_rules.ts @@ -214,7 +214,7 @@ export default ({ getService }: FtrProviderContext) => { it('should give a 404 if it is given a fake id', async () => { const simpleRule = getSimpleRule(); - simpleRule.id = 'fake_id'; + simpleRule.id = '5096dec6-b6b9-4d8d-8f93-6c2602079d9d'; delete simpleRule.rule_id; const { body } = await supertest @@ -225,7 +225,7 @@ export default ({ getService }: FtrProviderContext) => { expect(body).to.eql({ status_code: 404, - message: 'id: "fake_id" not found', + message: 'id: "5096dec6-b6b9-4d8d-8f93-6c2602079d9d" not found', }); }); diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/update_rules_bulk.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/update_rules_bulk.ts index 655f2b5d2e33f..54f29939fb6b4 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/update_rules_bulk.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/update_rules_bulk.ts @@ -269,7 +269,7 @@ export default ({ getService }: FtrProviderContext) => { it('should return a 200 but give a 404 in the message if it is given a fake id', async () => { const ruleUpdate = getSimpleRule('rule-1'); - ruleUpdate.id = 'fake_id'; + ruleUpdate.id = '1fd52120-d3a9-4e7a-b23c-96c0e1a74ae5'; delete ruleUpdate.rule_id; const { body } = await supertest @@ -279,7 +279,13 @@ export default ({ getService }: FtrProviderContext) => { .expect(200); expect(body).to.eql([ - { id: 'fake_id', error: { status_code: 404, message: 'id: "fake_id" not found' } }, + { + id: '1fd52120-d3a9-4e7a-b23c-96c0e1a74ae5', + error: { + status_code: 404, + message: 'id: "1fd52120-d3a9-4e7a-b23c-96c0e1a74ae5" not found', + }, + }, ]); }); @@ -358,7 +364,7 @@ export default ({ getService }: FtrProviderContext) => { const rule2 = getSimpleRule(); delete rule2.rule_id; - rule2.id = 'fake_id'; + rule2.id = 'b3aa019a-656c-4311-b13b-4d9852e24347'; rule2.name = 'some other name'; const { body } = await supertest @@ -376,10 +382,10 @@ export default ({ getService }: FtrProviderContext) => { outputRule, { error: { - message: 'id: "fake_id" not found', + message: 'id: "b3aa019a-656c-4311-b13b-4d9852e24347" not found', status_code: 404, }, - id: 'fake_id', + id: 'b3aa019a-656c-4311-b13b-4d9852e24347', }, ]); }); diff --git a/x-pack/test/functional/apps/index_management/home_page.ts b/x-pack/test/functional/apps/index_management/home_page.ts index e985e338122e7..90bc3603c1613 100644 --- a/x-pack/test/functional/apps/index_management/home_page.ts +++ b/x-pack/test/functional/apps/index_management/home_page.ts @@ -18,12 +18,17 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { await pageObjects.common.navigateToApp('indexManagement'); }); - it('Loads the app', async () => { + it('Loads the app and renders the indices tab by default', async () => { await log.debug('Checking for section heading to say Index Management.'); const headingText = await pageObjects.indexManagement.sectionHeadingText(); expect(headingText).to.be('Index Management'); + // Verify url + const url = await browser.getCurrentUrl(); + expect(url).to.contain(`/indices`); + + // Verify content const indicesList = await testSubjects.exists('indicesList'); expect(indicesList).to.be(true); @@ -31,6 +36,23 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { expect(await reloadIndicesButton.isDisplayed()).to.be(true); }); + describe('Data streams', () => { + it('renders the data streams tab', async () => { + // Navigate to the data streams tab + await pageObjects.indexManagement.changeTabs('data_streamsTab'); + + await pageObjects.header.waitUntilLoadingHasFinished(); + + // Verify url + const url = await browser.getCurrentUrl(); + expect(url).to.contain(`/data_streams`); + + // Verify content + const dataStreamList = await testSubjects.exists('dataStreamList'); + expect(dataStreamList).to.be(true); + }); + }); + describe('Index templates', () => { it('renders the index templates tab', async () => { // Navigate to the index templates tab @@ -47,5 +69,22 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { expect(templateList).to.be(true); }); }); + + describe('Component templates', () => { + it('renders the component templates tab', async () => { + // Navigate to the component templates tab + await pageObjects.indexManagement.changeTabs('component_templatesTab'); + + await pageObjects.header.waitUntilLoadingHasFinished(); + + // Verify url + const url = await browser.getCurrentUrl(); + expect(url).to.contain(`/component_templates`); + + // There should be no component templates by default, so we verify the empty prompt displays + const componentTemplateEmptyPrompt = await testSubjects.exists('emptyList'); + expect(componentTemplateEmptyPrompt).to.be(true); + }); + }); }); }; diff --git a/x-pack/test/functional/apps/ml/data_frame_analytics/classification_creation.ts b/x-pack/test/functional/apps/ml/data_frame_analytics/classification_creation.ts index c8baa13b56408..b0376b35ebd2f 100644 --- a/x-pack/test/functional/apps/ml/data_frame_analytics/classification_creation.ts +++ b/x-pack/test/functional/apps/ml/data_frame_analytics/classification_creation.ts @@ -11,8 +11,7 @@ export default function ({ getService }: FtrProviderContext) { const esArchiver = getService('esArchiver'); const ml = getService('ml'); - // flaky test, see https://github.com/elastic/kibana/issues/68356 - describe.skip('classification creation', function () { + describe('classification creation', function () { before(async () => { await esArchiver.loadIfNeeded('ml/bm_classification'); await ml.testResources.createIndexPatternIfNeeded('ft_bank_marketing', '@timestamp'); @@ -66,7 +65,7 @@ export default function ({ getService }: FtrProviderContext) { }); it('selects the source data and loads the job wizard page', async () => { - ml.jobSourceSelection.selectSourceForAnalyticsJob(testData.source); + await ml.jobSourceSelection.selectSourceForAnalyticsJob(testData.source); }); it('selects the job type', async () => { diff --git a/x-pack/test/functional/apps/ml/data_frame_analytics/outlier_detection_creation.ts b/x-pack/test/functional/apps/ml/data_frame_analytics/outlier_detection_creation.ts index b5c2b7528437c..2daae60b0ad20 100644 --- a/x-pack/test/functional/apps/ml/data_frame_analytics/outlier_detection_creation.ts +++ b/x-pack/test/functional/apps/ml/data_frame_analytics/outlier_detection_creation.ts @@ -63,7 +63,7 @@ export default function ({ getService }: FtrProviderContext) { }); it('selects the source data and loads the job wizard page', async () => { - ml.jobSourceSelection.selectSourceForAnalyticsJob(testData.source); + await ml.jobSourceSelection.selectSourceForAnalyticsJob(testData.source); }); it('selects the job type', async () => { diff --git a/x-pack/test/functional/apps/ml/data_frame_analytics/regression_creation.ts b/x-pack/test/functional/apps/ml/data_frame_analytics/regression_creation.ts index c818619a18378..35425e47526dd 100644 --- a/x-pack/test/functional/apps/ml/data_frame_analytics/regression_creation.ts +++ b/x-pack/test/functional/apps/ml/data_frame_analytics/regression_creation.ts @@ -11,8 +11,7 @@ export default function ({ getService }: FtrProviderContext) { const esArchiver = getService('esArchiver'); const ml = getService('ml'); - // flaky test, see https://github.com/elastic/kibana/issues/68352 - describe.skip('regression creation', function () { + describe('regression creation', function () { before(async () => { await esArchiver.loadIfNeeded('ml/egs_regression'); await ml.testResources.createIndexPatternIfNeeded('ft_egs_regression', '@timestamp'); @@ -66,7 +65,7 @@ export default function ({ getService }: FtrProviderContext) { }); it('selects the source data and loads the job wizard page', async () => { - ml.jobSourceSelection.selectSourceForAnalyticsJob(testData.source); + await ml.jobSourceSelection.selectSourceForAnalyticsJob(testData.source); }); it('selects the job type', async () => { diff --git a/x-pack/test/functional/apps/transform/creation_index_pattern.ts b/x-pack/test/functional/apps/transform/creation_index_pattern.ts index a72f1691af647..d6dbcde436dcc 100644 --- a/x-pack/test/functional/apps/transform/creation_index_pattern.ts +++ b/x-pack/test/functional/apps/transform/creation_index_pattern.ts @@ -57,6 +57,26 @@ export default function ({ getService }: FtrProviderContext) { transformFilterAggTypeSelector: 'term', transformFilterTermValueSelector: 'New York', }, + subAggs: [ + { + identifier: 'max(products.base_price)', + label: 'products.base_price.max', + }, + { + identifier: 'filter(customer_gender)', + label: 'customer_gender.filter', + form: { + transformFilterAggTypeSelector: 'term', + transformFilterTermValueSelector: 'FEMALE', + }, + subAggs: [ + { + identifier: 'avg(taxful_total_price)', + label: 'taxful_total_price.avg', + }, + ], + }, + ], }, ], transformId: `ec_1_${Date.now()}`, @@ -87,12 +107,33 @@ export default function ({ getService }: FtrProviderContext) { field: 'products.base_price', }, }, - 'geoip.city_name.filter': { + 'New York': { filter: { term: { 'geoip.city_name': 'New York', }, }, + aggs: { + 'products.base_price.max': { + max: { + field: 'products.base_price', + }, + }, + FEMALE: { + filter: { + term: { + customer_gender: 'FEMALE', + }, + }, + aggs: { + 'taxful_total_price.avg': { + avg: { + field: 'taxful_total_price', + }, + }, + }, + }, + }, }, }, }, @@ -131,6 +172,12 @@ export default function ({ getService }: FtrProviderContext) { form: { transformFilterAggTypeSelector: 'exists', }, + subAggs: [ + { + identifier: 'max(products.discount_amount)', + label: 'products.discount_amount.max', + }, + ], }, ], transformId: `ec_2_${Date.now()}`, @@ -162,6 +209,13 @@ export default function ({ getService }: FtrProviderContext) { field: 'customer_phone', }, }, + aggs: { + 'products.discount_amount.max': { + max: { + field: 'products.discount_amount', + }, + }, + }, }, }, }, @@ -249,11 +303,7 @@ export default function ({ getService }: FtrProviderContext) { }); it('adds the aggregation entries', async () => { - for (const [index, agg] of testData.aggregationEntries.entries()) { - await transform.wizard.assertAggregationInputExists(); - await transform.wizard.assertAggregationInputValue([]); - await transform.wizard.addAggregationEntry(index, agg.identifier, agg.label, agg.form); - } + await transform.wizard.addAggregationEntries(testData.aggregationEntries); }); it('displays the advanced pivot editor switch', async () => { diff --git a/x-pack/test/functional/page_objects/index_management_page.ts b/x-pack/test/functional/page_objects/index_management_page.ts index d12186f2e2189..5e5d0e7583450 100644 --- a/x-pack/test/functional/page_objects/index_management_page.ts +++ b/x-pack/test/functional/page_objects/index_management_page.ts @@ -44,7 +44,10 @@ export function IndexManagementPageProvider({ getService }: FtrProviderContext) }; }); }, - async changeTabs(tab: 'indicesTab' | 'templatesTab') { + + async changeTabs( + tab: 'indicesTab' | 'data_streamsTab' | 'templatesTab' | 'component_templatesTab' + ) { await testSubjects.click(tab); }, }; diff --git a/x-pack/test/functional/services/transform/wizard.ts b/x-pack/test/functional/services/transform/wizard.ts index 03c8b2867b240..8b61e8c895e30 100644 --- a/x-pack/test/functional/services/transform/wizard.ts +++ b/x-pack/test/functional/services/transform/wizard.ts @@ -242,14 +242,20 @@ export function TransformWizardProvider({ getService }: FtrProviderContext) { await this.assertGroupByEntryExists(index, expectedLabel, expectedIntervalLabel); }, - async assertAggregationInputExists() { - await testSubjects.existOrFail('transformAggregationSelection > comboBoxInput'); + getAggComboBoxInputSelector(parentSelector = ''): string { + return `${parentSelector && `${parentSelector} > `}${ + parentSelector ? 'transformSubAggregationSelection' : 'transformAggregationSelection' + } > comboBoxInput`; }, - async assertAggregationInputValue(expectedIdentifier: string[]) { + async assertAggregationInputExists(parentSelector?: string) { + await testSubjects.existOrFail(this.getAggComboBoxInputSelector(parentSelector)); + }, + + async assertAggregationInputValue(expectedIdentifier: string[], parentSelector?: string) { await retry.tryForTime(2000, async () => { const comboBoxSelectedOptions = await comboBox.getComboBoxSelectedOptions( - 'transformAggregationSelection > comboBoxInput' + this.getAggComboBoxInputSelector(parentSelector) ); expect(comboBoxSelectedOptions).to.eql( expectedIdentifier, @@ -258,11 +264,14 @@ export function TransformWizardProvider({ getService }: FtrProviderContext) { }); }, - async assertAggregationEntryExists(index: number, expectedLabel: string) { - await testSubjects.existOrFail(`transformAggregationEntry ${index}`); + async assertAggregationEntryExists(index: number, expectedLabel: string, parentSelector = '') { + const aggEntryPanelSelector = `${ + parentSelector && `${parentSelector} > ` + }transformAggregationEntry_${index}`; + await testSubjects.existOrFail(aggEntryPanelSelector); const actualLabel = await testSubjects.getVisibleText( - `transformAggregationEntry ${index} > transformAggregationEntryLabel` + `${aggEntryPanelSelector} > transformAggregationEntryLabel` ); expect(actualLabel).to.eql( expectedLabel, @@ -270,15 +279,31 @@ export function TransformWizardProvider({ getService }: FtrProviderContext) { ); }, + async addAggregationEntries(aggregationEntries: any[], parentSelector?: string) { + for (const [index, agg] of aggregationEntries.entries()) { + await this.assertAggregationInputExists(parentSelector); + await this.assertAggregationInputValue([], parentSelector); + await this.addAggregationEntry(index, agg.identifier, agg.label, agg.form, parentSelector); + + if (agg.subAggs) { + await this.addAggregationEntries( + agg.subAggs, + `${parentSelector ? `${parentSelector} > ` : ''}transformAggregationEntry_${index}` + ); + } + } + }, + async addAggregationEntry( index: number, identifier: string, expectedLabel: string, - formData?: Record + formData?: Record, + parentSelector = '' ) { - await comboBox.set('transformAggregationSelection > comboBoxInput', identifier); - await this.assertAggregationInputValue([]); - await this.assertAggregationEntryExists(index, expectedLabel); + await comboBox.set(this.getAggComboBoxInputSelector(parentSelector), identifier); + await this.assertAggregationInputValue([], parentSelector); + await this.assertAggregationEntryExists(index, expectedLabel, parentSelector); if (formData !== undefined) { await this.fillPopoverForm(identifier, expectedLabel, formData); diff --git a/x-pack/test/functional_endpoint/apps/endpoint/host_list.ts b/x-pack/test/functional_endpoint/apps/endpoint/endpoint_list.ts similarity index 84% rename from x-pack/test/functional_endpoint/apps/endpoint/host_list.ts rename to x-pack/test/functional_endpoint/apps/endpoint/endpoint_list.ts index 029953f113a9c..c5338e2a35765 100644 --- a/x-pack/test/functional_endpoint/apps/endpoint/host_list.ts +++ b/x-pack/test/functional_endpoint/apps/endpoint/endpoint_list.ts @@ -13,68 +13,71 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { const testSubjects = getService('testSubjects'); // FLAKY: https://github.com/elastic/kibana/issues/63621 - describe.skip('host list', function () { + describe.skip('endpoint list', function () { this.tags('ciGroup7'); const sleep = (ms = 100) => new Promise((resolve) => setTimeout(resolve, ms)); before(async () => { await esArchiver.load('endpoint/metadata/api_feature'); - await pageObjects.common.navigateToUrlWithBrowserHistory('endpoint', '/hosts'); - await pageObjects.header.waitUntilLoadingHasFinished(); + await pageObjects.endpoint.navigateToEndpointList(); }); it('finds title', async () => { - const title = await testSubjects.getVisibleText('hostListTitle'); - expect(title).to.equal('Hosts'); + const title = await testSubjects.getVisibleText('pageViewHeaderLeftTitle'); + expect(title).to.equal('Endpoints'); }); it('displays table data', async () => { const expectedData = [ [ 'Hostname', + 'Host Status', 'Policy', 'Policy Status', 'Alerts', 'Operating System', 'IP Address', - 'Sensor Version', + 'Version', 'Last Active', ], [ 'cadmann-4.example.com', + 'Error', 'Policy Name', 'Policy Status', '0', 'windows 10.0', '10.192.213.130, 10.70.28.129', - 'version', - 'xxxx', + '6.6.1', + 'Jan 24, 2020 @ 16:06:09.541', ], [ 'thurlow-9.example.com', + 'Error', 'Policy Name', 'Policy Status', '0', 'windows 10.0', '10.46.229.234', - 'version', - 'xxxx', + '6.0.0', + 'Jan 24, 2020 @ 16:06:09.541', ], [ 'rezzani-7.example.com', + 'Error', 'Policy Name', 'Policy Status', '0', 'windows 10.0', '10.101.149.26, 2606:a000:ffc0:39:11ef:37b9:3371:578c', - 'version', - 'xxxx', + '6.8.0', + 'Jan 24, 2020 @ 16:06:09.541', ], ]; const tableData = await pageObjects.endpoint.getEndpointAppTableData('hostListTable'); expect(tableData).to.eql(expectedData); }); - it('no details flyout when host page displayed', async () => { + it('no details flyout when endpoint page displayed', async () => { await testSubjects.missingOrFail('hostDetailsFlyout'); }); @@ -108,22 +111,21 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { await (await testSubjects.findAll('hostnameCellLink'))[1].click(); await sleep(500); // give page time to refresh and verify it did not change const hostDetailTitleNew = await testSubjects.getVisibleText('hostDetailsFlyoutTitle'); - expect(hostDetailTitleNew).to.eql(hostDetailTitleInitial); + expect(hostDetailTitleNew).to.equal(hostDetailTitleInitial); }); describe('no data', () => { before(async () => { // clear out the data and reload the page await esArchiver.unload('endpoint/metadata/api_feature'); - await pageObjects.common.navigateToUrlWithBrowserHistory('endpoint', '/hosts'); - await pageObjects.header.waitUntilLoadingHasFinished(); + await pageObjects.endpoint.navigateToEndpointList(); }); after(async () => { // reload the data so the other tests continue to pass await esArchiver.load('endpoint/metadata/api_feature'); }); it('displays no items found when empty', async () => { - // get the host list table data and verify message + // get the endpoint list table data and verify message const [, [noItemsFoundMessage]] = await pageObjects.endpoint.getEndpointAppTableData( 'hostListTable' ); @@ -133,12 +135,9 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { describe('has a url with a host id', () => { before(async () => { - await pageObjects.common.navigateToUrlWithBrowserHistory( - 'endpoint', - '/hosts', + await pageObjects.endpoint.navigateToEndpointList( 'selected_host=fc0ff548-feba-41b6-8367-65e8790d0eaf' ); - await pageObjects.header.waitUntilLoadingHasFinished(); }); it('shows a flyout', async () => { @@ -168,7 +167,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { '', '0', '00000000-0000-0000-0000-000000000000', - 'Successful', + 'Unknown', '10.101.149.262606:a000:ffc0:39:11ef:37b9:3371:578c', 'rezzani-7.example.com', '6.8.0', diff --git a/x-pack/test/functional_endpoint/apps/endpoint/feature_controls/endpoint_spaces.ts b/x-pack/test/functional_endpoint/apps/endpoint/feature_controls/endpoint_spaces.ts deleted file mode 100644 index 27fabb515757a..0000000000000 --- a/x-pack/test/functional_endpoint/apps/endpoint/feature_controls/endpoint_spaces.ts +++ /dev/null @@ -1,76 +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; - * you may not use this file except in compliance with the Elastic License. - */ -import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../../ftr_provider_context'; - -export default function ({ getPageObjects, getService }: FtrProviderContext) { - const pageObjects = getPageObjects(['common']); - const spacesService = getService('spaces'); - const testSubjects = getService('testSubjects'); - const appsMenu = getService('appsMenu'); - - describe('spaces', () => { - describe('space with no features disabled', () => { - before(async () => { - await spacesService.create({ - id: 'custom_space', - name: 'custom_space', - disabledFeatures: [], - }); - }); - - after(async () => { - await spacesService.delete('custom_space'); - }); - - it('shows endpoint navlink', async () => { - await pageObjects.common.navigateToApp('home', { - basePath: '/s/custom_space', - }); - const navLinks = (await appsMenu.readLinks()).map((link) => link.text); - expect(navLinks).to.contain('Endpoint'); - }); - - it(`endpoint app shows 'Hello World'`, async () => { - await pageObjects.common.navigateToApp('endpoint', { - basePath: '/s/custom_space', - }); - await testSubjects.existOrFail('welcomeTitle'); - }); - - it(`endpoint hosts shows hosts lists page`, async () => { - await pageObjects.common.navigateToUrlWithBrowserHistory('endpoint', '/hosts', undefined, { - basePath: '/s/custom_space', - ensureCurrentUrl: false, - shouldLoginIfPrompted: false, - }); - await testSubjects.existOrFail('hostPage'); - }); - }); - - describe('space with endpoint disabled', () => { - before(async () => { - await spacesService.create({ - id: 'custom_space', - name: 'custom_space', - disabledFeatures: ['endpoint'], - }); - }); - - after(async () => { - await spacesService.delete('custom_space'); - }); - - it(`doesn't show endpoint navlink`, async () => { - await pageObjects.common.navigateToApp('home', { - basePath: '/s/custom_space', - }); - const navLinks = (await appsMenu.readLinks()).map((link) => link.text); - expect(navLinks).not.to.contain('Endpoint'); - }); - }); - }); -} diff --git a/x-pack/test/functional_endpoint/apps/endpoint/feature_controls/index.ts b/x-pack/test/functional_endpoint/apps/endpoint/feature_controls/index.ts deleted file mode 100644 index da0919d7c39f3..0000000000000 --- a/x-pack/test/functional_endpoint/apps/endpoint/feature_controls/index.ts +++ /dev/null @@ -1,13 +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; - * you may not use this file except in compliance with the Elastic License. - */ -import { FtrProviderContext } from '../../../ftr_provider_context'; - -export default function ({ loadTestFile }: FtrProviderContext) { - describe('feature controls', function () { - this.tags('skipFirefox'); - loadTestFile(require.resolve('./endpoint_spaces')); - }); -} diff --git a/x-pack/test/functional_endpoint/apps/endpoint/header_nav.ts b/x-pack/test/functional_endpoint/apps/endpoint/header_nav.ts deleted file mode 100644 index 48cdd6aec5b1a..0000000000000 --- a/x-pack/test/functional_endpoint/apps/endpoint/header_nav.ts +++ /dev/null @@ -1,55 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../ftr_provider_context'; - -export default ({ getPageObjects, getService }: FtrProviderContext) => { - const pageObjects = getPageObjects(['common', 'endpoint']); - const testSubjects = getService('testSubjects'); - - describe('Header nav', function () { - this.tags('ciGroup7'); - before(async () => { - await pageObjects.common.navigateToApp('endpoint'); - }); - - it('renders the tabs when the app loads', async () => { - const homeTabText = await testSubjects.getVisibleText('homeEndpointTab'); - const hostsTabText = await testSubjects.getVisibleText('hostsEndpointTab'); - const alertsTabText = await testSubjects.getVisibleText('alertsEndpointTab'); - const policiesTabText = await testSubjects.getVisibleText('policiesEndpointTab'); - - expect(homeTabText.trim()).to.be('Home'); - expect(hostsTabText.trim()).to.be('Hosts'); - expect(alertsTabText.trim()).to.be('Alerts'); - expect(policiesTabText.trim()).to.be('Policies'); - }); - - it('renders the hosts page when the Hosts tab is selected', async () => { - await (await testSubjects.find('hostsEndpointTab')).click(); - await testSubjects.existOrFail('hostPage'); - }); - - it('renders the alerts page when the Alerts tab is selected', async () => { - await (await testSubjects.find('alertsEndpointTab')).click(); - await testSubjects.existOrFail('alertListPage'); - }); - - it('renders the policy page when Policy tab is selected', async () => { - await (await testSubjects.find('policiesEndpointTab')).click(); - await testSubjects.existOrFail('policyListPage'); - }); - - it('renders the home page when Home tab is selected after selecting another tab', async () => { - await (await testSubjects.find('hostsEndpointTab')).click(); - await testSubjects.existOrFail('hostPage'); - - await (await testSubjects.find('homeEndpointTab')).click(); - await testSubjects.existOrFail('welcomeTitle'); - }); - }); -}; diff --git a/x-pack/test/functional_endpoint/apps/endpoint/index.ts b/x-pack/test/functional_endpoint/apps/endpoint/index.ts index 296ee45ff181c..199d138d1c450 100644 --- a/x-pack/test/functional_endpoint/apps/endpoint/index.ts +++ b/x-pack/test/functional_endpoint/apps/endpoint/index.ts @@ -9,12 +9,11 @@ export default function ({ loadTestFile }: FtrProviderContext) { describe('endpoint', function () { this.tags('ciGroup7'); - loadTestFile(require.resolve('./feature_controls')); - loadTestFile(require.resolve('./landing_page')); - loadTestFile(require.resolve('./header_nav')); - loadTestFile(require.resolve('./host_list')); + loadTestFile(require.resolve('./endpoint_list')); loadTestFile(require.resolve('./policy_list')); - loadTestFile(require.resolve('./alerts')); - loadTestFile(require.resolve('./resolver')); + loadTestFile(require.resolve('./policy_details')); + + // loadTestFile(require.resolve('./alerts')); + // loadTestFile(require.resolve('./resolver')); }); } diff --git a/x-pack/test/functional_endpoint/apps/endpoint/landing_page.ts b/x-pack/test/functional_endpoint/apps/endpoint/landing_page.ts deleted file mode 100644 index f2a55df56421a..0000000000000 --- a/x-pack/test/functional_endpoint/apps/endpoint/landing_page.ts +++ /dev/null @@ -1,29 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../ftr_provider_context'; - -export default ({ getPageObjects, getService }: FtrProviderContext) => { - const pageObjects = getPageObjects(['common', 'endpoint']); - const testSubjects = getService('testSubjects'); - - describe('Endpoint landing page', function () { - this.tags('ciGroup7'); - before(async () => { - await pageObjects.common.navigateToApp('endpoint'); - }); - - it('Loads the endpoint app', async () => { - const welcomeEndpointMessage = await pageObjects.endpoint.welcomeEndpointTitle(); - expect(welcomeEndpointMessage).to.be('Hello World'); - }); - - it('Does not display a toast indicating that the ingest manager failed to initialize', async () => { - await testSubjects.missingOrFail('euiToastHeader'); - }); - }); -}; diff --git a/x-pack/test/functional_endpoint/apps/endpoint/policy_details.ts b/x-pack/test/functional_endpoint/apps/endpoint/policy_details.ts new file mode 100644 index 0000000000000..25fb477b5a99a --- /dev/null +++ b/x-pack/test/functional_endpoint/apps/endpoint/policy_details.ts @@ -0,0 +1,225 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../ftr_provider_context'; +import { PolicyTestResourceInfo } from '../../services/endpoint_policy'; + +export default function ({ getPageObjects, getService }: FtrProviderContext) { + const pageObjects = getPageObjects(['common', 'endpoint', 'policy', 'endpointPageUtils']); + const testSubjects = getService('testSubjects'); + const policyTestResources = getService('policyTestResources'); + + describe('When on the Endpoint Policy Details Page', function () { + this.tags(['ciGroup7']); + + describe('with an invalid policy id', () => { + it('should display an error', async () => { + await pageObjects.policy.navigateToPolicyDetails('invalid-id'); + await testSubjects.existOrFail('policyDetailsIdNotFoundMessage'); + expect(await testSubjects.getVisibleText('policyDetailsIdNotFoundMessage')).to.equal( + 'Saved object [ingest-datasources/invalid-id] not found' + ); + }); + }); + + describe('with a valid policy id', () => { + let policyInfo: PolicyTestResourceInfo; + + before(async () => { + policyInfo = await policyTestResources.createPolicy(); + await pageObjects.policy.navigateToPolicyDetails(policyInfo.datasource.id); + }); + + after(async () => { + if (policyInfo) { + await policyInfo.cleanup(); + } + }); + + it('should display policy view', async () => { + expect(await testSubjects.getVisibleText('pageViewHeaderLeftTitle')).to.equal( + policyInfo.datasource.name + ); + }); + }); + + describe('and the save button is clicked', () => { + let policyInfo: PolicyTestResourceInfo; + + beforeEach(async () => { + policyInfo = await policyTestResources.createPolicy(); + await pageObjects.policy.navigateToPolicyDetails(policyInfo.datasource.id); + }); + + afterEach(async () => { + if (policyInfo) { + await policyInfo.cleanup(); + } + }); + + it('should display success toast on successful save', async () => { + await pageObjects.endpointPageUtils.clickOnEuiCheckbox('policyWindowsEvent_dns'); + await pageObjects.policy.confirmAndSave(); + + await testSubjects.existOrFail('policyDetailsSuccessMessage'); + expect(await testSubjects.getVisibleText('policyDetailsSuccessMessage')).to.equal( + `Policy ${policyInfo.datasource.name} has been updated.` + ); + }); + it('should persist update on the screen', async () => { + await pageObjects.endpointPageUtils.clickOnEuiCheckbox('policyWindowsEvent_process'); + await pageObjects.policy.confirmAndSave(); + + await testSubjects.existOrFail('policyDetailsSuccessMessage'); + await pageObjects.policy.navigateToPolicyList(); + await pageObjects.policy.navigateToPolicyDetails(policyInfo.datasource.id); + + expect(await (await testSubjects.find('policyWindowsEvent_process')).isSelected()).to.equal( + false + ); + }); + it('should have updated policy data in overall agent configuration', async () => { + // This test ensures that updates made to the Endpoint Policy are carried all the way through + // to the generated Agent Configuration that is dispatch down to the Elastic Agent. + + await Promise.all([ + pageObjects.endpointPageUtils.clickOnEuiCheckbox('policyWindowsEvent_file'), + pageObjects.endpointPageUtils.clickOnEuiCheckbox('policyLinuxEvent_file'), + pageObjects.endpointPageUtils.clickOnEuiCheckbox('policyMacEvent_file'), + ]); + await pageObjects.policy.confirmAndSave(); + await testSubjects.existOrFail('policyDetailsSuccessMessage'); + + const agentFullConfig = await policyTestResources.getFullAgentConfig( + policyInfo.agentConfig.id + ); + + expect(agentFullConfig).to.eql({ + datasources: [ + { + enabled: true, + id: policyInfo.datasource.id, + inputs: [ + { + enabled: true, + policy: { + linux: { + advanced: { + elasticsearch: { + indices: { + control: 'control-index', + event: 'event-index', + logging: 'logging-index', + }, + kernel: { + connect: true, + process: true, + }, + }, + }, + events: { + file: false, + network: true, + process: true, + }, + logging: { + file: 'info', + stdout: 'debug', + }, + }, + mac: { + advanced: { + elasticsearch: { + indices: { + control: 'control-index', + event: 'event-index', + logging: 'logging-index', + }, + kernel: { + connect: true, + process: true, + }, + }, + }, + events: { + file: false, + network: true, + process: true, + }, + logging: { + file: 'info', + stdout: 'debug', + }, + malware: { + mode: 'detect', + }, + }, + windows: { + advanced: { + elasticsearch: { + indices: { + control: 'control-index', + event: 'event-index', + logging: 'logging-index', + }, + kernel: { + connect: true, + process: true, + }, + }, + }, + events: { + dll_and_driver_load: true, + dns: true, + file: false, + network: true, + process: true, + registry: true, + security: true, + }, + logging: { + file: 'info', + stdout: 'debug', + }, + malware: { + mode: 'prevent', + }, + }, + }, + streams: [], + type: 'endpoint', + }, + ], + name: 'Protect East Coast', + namespace: 'default', + package: { + name: 'endpoint', + version: policyInfo.packageInfo.version, + }, + use_output: 'default', + }, + ], + id: policyInfo.agentConfig.id, + outputs: { + default: { + hosts: ['http://localhost:9200'], + type: 'elasticsearch', + }, + }, + revision: 3, + settings: { + monitoring: { + enabled: false, + logs: false, + metrics: false, + }, + }, + }); + }); + }); + }); +} diff --git a/x-pack/test/functional_endpoint/apps/endpoint/policy_list.ts b/x-pack/test/functional_endpoint/apps/endpoint/policy_list.ts index 11b1b8e718ff7..9f87f884b327e 100644 --- a/x-pack/test/functional_endpoint/apps/endpoint/policy_list.ts +++ b/x-pack/test/functional_endpoint/apps/endpoint/policy_list.ts @@ -8,15 +8,15 @@ import { FtrProviderContext } from '../../ftr_provider_context'; import { PolicyTestResourceInfo } from '../../services/endpoint_policy'; export default function ({ getPageObjects, getService }: FtrProviderContext) { - const pageObjects = getPageObjects(['common', 'endpoint']); + const pageObjects = getPageObjects(['common', 'endpoint', 'policy']); const testSubjects = getService('testSubjects'); const policyTestResources = getService('policyTestResources'); + const RELATIVE_DATE_FORMAT = /\d (?:seconds|minutes) ago/i; - // FLAKY: https://github.com/elastic/kibana/issues/66579 - describe.skip('When on the Endpoint Policy List', function () { + describe('When on the Endpoint Policy List', function () { this.tags(['ciGroup7']); before(async () => { - await pageObjects.common.navigateToUrlWithBrowserHistory('endpoint', '/policy'); + await pageObjects.policy.navigateToPolicyList(); }); it('loads the Policy List Page', async () => { @@ -34,10 +34,12 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { const allHeaderCells = await pageObjects.endpoint.tableHeaderVisibleText('policyTable'); expect(allHeaderCells).to.eql([ 'Policy Name', - 'Revision', + 'Created By', + 'Created Date', + 'Last Updated By', + 'Last Updated', 'Version', - 'Description', - 'Agent Configuration', + 'Actions', ]); }); it('should show empty table results message', async () => { @@ -47,13 +49,13 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { expect(noItemsFoundMessage).to.equal('No items found'); }); - xdescribe('and policies exists', () => { + describe('and policies exists', () => { let policyInfo: PolicyTestResourceInfo; before(async () => { // load/create a policy and then navigate back to the policy view so that the list is refreshed policyInfo = await policyTestResources.createPolicy(); - await pageObjects.common.navigateToUrlWithBrowserHistory('endpoint', '/policy'); + await pageObjects.policy.navigateToPolicyList(); await pageObjects.endpoint.waitForTableToHaveData('policyTable'); }); after(async () => { @@ -64,26 +66,24 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { it('should show policy on the list', async () => { const [, policyRow] = await pageObjects.endpoint.getEndpointAppTableData('policyTable'); - expect(policyRow).to.eql([ - 'Protect East Coast', - '1', - 'Elastic Endpoint v1.0.0', - 'Protect the worlds data - but in the East Coast', - policyInfo.agentConfig.id, + // Validate row data with the exception of the Date columns - since those are initially + // shown as relative. + expect([policyRow[0], policyRow[1], policyRow[3], policyRow[5], policyRow[6]]).to.eql([ + 'Protect East Coastrev. 1', + 'elastic', + 'elastic', + `${policyInfo.datasource.package?.title} v${policyInfo.datasource.package?.version}`, + '', ]); + [policyRow[2], policyRow[4]].forEach((relativeDate) => { + expect(relativeDate).to.match(RELATIVE_DATE_FORMAT); + }); }); it('should show policy name as link', async () => { const policyNameLink = await testSubjects.find('policyNameLink'); expect(await policyNameLink.getTagName()).to.equal('a'); expect(await policyNameLink.getAttribute('href')).to.match( - new RegExp(`\/endpoint\/policy\/${policyInfo.datasource.id}$`) - ); - }); - it('should show agent configuration as link', async () => { - const agentConfigLink = await testSubjects.find('agentConfigLink'); - expect(await agentConfigLink.getTagName()).to.equal('a'); - expect(await agentConfigLink.getAttribute('href')).to.match( - new RegExp(`\/app\/ingestManager\#\/configs\/${policyInfo.datasource.config_id}$`) + new RegExp(`\/management\/policy\/${policyInfo.datasource.id}$`) ); }); }); diff --git a/x-pack/test/functional_endpoint/page_objects/endpoint_page.ts b/x-pack/test/functional_endpoint/page_objects/endpoint_page.ts index 7f78bd6b804f7..3234169e7265e 100644 --- a/x-pack/test/functional_endpoint/page_objects/endpoint_page.ts +++ b/x-pack/test/functional_endpoint/page_objects/endpoint_page.ts @@ -7,11 +7,22 @@ import { WebElementWrapper } from 'test/functional/services/lib/web_element_wrapper'; import { FtrProviderContext } from '../ftr_provider_context'; -export function EndpointPageProvider({ getService }: FtrProviderContext) { +export function EndpointPageProvider({ getService, getPageObjects }: FtrProviderContext) { const testSubjects = getService('testSubjects'); + const pageObjects = getPageObjects(['common', 'header']); const retry = getService('retry'); return { + /** + * Navigate to the Endpoints list page + */ + async navigateToEndpointList(searchParams?: string) { + await pageObjects.common.navigateToApp('securitySolution', { + hash: `/management/endpoints${searchParams ? `?${searchParams}` : ''}`, + }); + await pageObjects.header.waitUntilLoadingHasFinished(); + }, + /** * Finds the Table with the given `selector` (test subject) and returns * back an array containing the table's header column text @@ -31,10 +42,6 @@ export function EndpointPageProvider({ getService }: FtrProviderContext) { ); }, - async welcomeEndpointTitle() { - return await testSubjects.getVisibleText('welcomeTitle'); - }, - /** * Finds a table and returns the data in a nested array with row 0 is the headers if they exist. * It uses euiTableCellContent to avoid poluting the array data with the euiTableRowCell__mobileHeader data. diff --git a/x-pack/test/functional_endpoint/page_objects/index.ts b/x-pack/test/functional_endpoint/page_objects/index.ts index 8138ce2eeccb3..5b550bea5b55d 100644 --- a/x-pack/test/functional_endpoint/page_objects/index.ts +++ b/x-pack/test/functional_endpoint/page_objects/index.ts @@ -7,9 +7,13 @@ import { pageObjects as xpackFunctionalPageObjects } from '../../functional/page_objects'; import { EndpointPageProvider } from './endpoint_page'; import { EndpointAlertsPageProvider } from './endpoint_alerts_page'; +import { EndpointPolicyPageProvider } from './policy_page'; +import { EndpointPageUtils } from './page_utils'; export const pageObjects = { ...xpackFunctionalPageObjects, endpoint: EndpointPageProvider, + policy: EndpointPolicyPageProvider, + endpointPageUtils: EndpointPageUtils, endpointAlerts: EndpointAlertsPageProvider, }; diff --git a/x-pack/test/functional_endpoint/page_objects/page_utils.ts b/x-pack/test/functional_endpoint/page_objects/page_utils.ts new file mode 100644 index 0000000000000..daf66464f7e1e --- /dev/null +++ b/x-pack/test/functional_endpoint/page_objects/page_utils.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { FtrProviderContext } from '../ftr_provider_context'; + +export function EndpointPageUtils({ getService }: FtrProviderContext) { + const find = getService('find'); + + return { + /** + * Finds a given EuiCheckbox by test subject and clicks on it + * + * @param euiCheckBoxTestId + */ + async clickOnEuiCheckbox(euiCheckBoxTestId: string) { + // This utility is needed because EuiCheckbox forwards the test subject on to + // the actual `` which is not actually visible/accessible on the page. + // In order to actually cause the state of the checkbox to change, the `